问:
Add item to a specific column in ListView Adapter
I have an increment system and I want when onClick to save value from DialogAlert in a column in ListView Adapter.

Here is my Adapter:

```<code>public class VanzatorProduseList extends ArrayAdapter<VanzatorProduse> {

private Activity context;
private SparseBooleanArray selectedListItemsIds;
private List<VanzatorProduse> vanzatorProduseList;

public VanzatorProduseList(Activity context, List<VanzatorProduse> vanzatorProduseList){
    super(context, R.layout.list_produse_vanzator, vanzatorProduseList);
    this.context = context;
    selectedListItemsIds = new SparseBooleanArray();
    this.vanzatorProduseList = vanzatorProduseList;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View listViewItem = inflater.inflate(R.layout.list_produse_vanzator, null, true);

    TextView textViewProdus1 = (TextView) listViewItem.findViewById(R.id.textViewProdus1);
    TextView textViewPret1 = (TextView) listViewItem.findViewById(R.id.textViewPret1);
    final TextView textViewCantitate1 = (TextView) listViewItem.findViewById(R.id.textViewCantitate1);

    final VanzatorProduse vanzatorProduse = vanzatorProduseList.get(position);

    textViewProdus1.setText(vanzatorProduse.getProdus());
    textViewPret1.setText(vanzatorProduse.getPret());

    textViewCantitate1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // custom dialog
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.dialog_alert);
            dialog.setTitle("Alege Canitatea");

            // set the custom dialog components - text, image and button
            final Button dialogBtn = (Button) dialog.findViewById(R.id.dialog_btn);
            final ElegantNumberButton elegantNumberButton = (ElegantNumberButton) dialog.findViewById(R.id.elegantNumberButton);

            // if button is clicked, close the custom dialog
            dialogBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);
                    dialog.dismiss();

                }
            });

            dialog.show();
        }
    });

    return listViewItem;
}
</code>```

Here is what I tried but I got an error and no idea what to do next :

```<code> String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);
</code>```

Error:

```<code>'add(com.dev.darius.neglije.Vanzator.ListaProduse.VanzatorProduse)' in 'java.util.List' cannot be applied to '(java.lang.String)'
</code>```

Here I'm stuck I want to display in TextView called textViewCantitate1.

Hope you understand.

答:
You are trying to add String type into List<VanzatorProduse> vanzatorProduseList. You can add only VanzatorProduse type into vanzatorProduseList list. So, the cause of the problem is:

```<code>String num = elegantNumberButton.getNumber();
vanzatorProduseList.add(num);
</code>```

In your code you have following lines:

```<code>final VanzatorProduse vanzatorProduse = vanzatorProduseList.get(position);

textViewProdus1.setText(vanzatorProduse.getProdus());
textViewPret1.setText(vanzatorProduse.getPret());
</code>```

So, might be you add num value into vanzatorProduse.setProdus(num) or any other appropriate field and then add it into the list:

```<code>vanzatorProduseList.add(vanzatorProduse);
</code>```

Body:
I have an increment system and I want when onClick to save value from DialogAlert in a column in ListView Adapter.

Here is my Adapter:

public class VanzatorProduseList extends ArrayAdapter<VanzatorProduse> {

private Activity context;
private SparseBooleanArray selectedListItemsIds;
private List<VanzatorProduse> vanzatorProduseList;

public VanzatorProduseList(Activity context, List<VanzatorProduse> vanzatorProduseList){
    super(context, R.layout.list_produse_vanzator, vanzatorProduseList);
    this.context = context;
    selectedListItemsIds = new SparseBooleanArray();
    this.vanzatorProduseList = vanzatorProduseList;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View listViewItem = inflater.inflate(R.layout.list_produse_vanzator, null, true);

    TextView textViewProdus1 = (TextView) listViewItem.findViewById(R.id.textViewProdus1);
    TextView textViewPret1 = (TextView) listViewItem.findViewById(R.id.textViewPret1);
    final TextView textViewCantitate1 = (TextView) listViewItem.findViewById(R.id.textViewCantitate1);

    final VanzatorProduse vanzatorProduse = vanzatorProduseList.get(position);

    textViewProdus1.setText(vanzatorProduse.getProdus());
    textViewPret1.setText(vanzatorProduse.getPret());

    textViewCantitate1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // custom dialog
            final Dialog dialog = new Dialog(context);
            dialog.setContentView(R.layout.dialog_alert);
            dialog.setTitle("Alege Canitatea");

            // set the custom dialog components - text, image and button
            final Button dialogBtn = (Button) dialog.findViewById(R.id.dialog_btn);
            final ElegantNumberButton elegantNumberButton = (ElegantNumberButton) dialog.findViewById(R.id.elegantNumberButton);

            // if button is clicked, close the custom dialog
            dialogBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);
                    dialog.dismiss();

                }
            });

            dialog.show();
        }
    });

    return listViewItem;
}

Here is what I tried but I got an error and no idea what to do next :

 String num = elegantNumberButton.getNumber();
                vanzatorProduseList.add(num);

Error:

'add(com.dev.darius.neglije.Vanzator.ListaProduse.VanzatorProduse)' in 'java.util.List' cannot be applied to '(java.lang.String)'

Here I'm stuck I want to display in TextView called textViewCantitate1.

Hope you understand.

Body:
You are trying to add String type into List<VanzatorProduse> vanzatorProduseList. You can add only VanzatorProduse type into vanzatorProduseList list. So, the cause of the problem is:

String num = elegantNumberButton.getNumber();
vanzatorProduseList.add(num);

In your code you have following lines:

final VanzatorProduse vanzatorProduse = vanzatorProduseList.get(position);

textViewProdus1.setText(vanzatorProduse.getProdus());
textViewPret1.setText(vanzatorProduse.getPret());

So, might be you add num value into vanzatorProduse.setProdus(num) or any other appropriate field and then add it into the list:

vanzatorProduseList.add(vanzatorProduse);


来源: stackexchange

问:
Liferay7.0 portlet build with angular and typescript
I'm wondering, is it possible to create a liferay7.0 portlet based on angular(2, angular material v1.1.1) and typescripting.

I know its possible to load (for example) Angular 1.4 lib and create a portlet with plain javascript/angular code
source: https://web.liferay.com/web/sampsa.sohlman/blog/-/blogs/trying-the-angularjs-with-liferay

What i would like to achieve is to create a portlet based on nodejs packages. and to compile it with gulp or something to a war file.

答:
Integrating java based portals with angular is very complicated. Liferay is shipped with AlloyUi. There are side effects for using multiple JS libraries together such as AlloyUI with Angularjs.
Side effects usually manifests themselves in higher load times and possible conflicts. A single angular app protlet is required for every page containing an angular portlet. Once two instances of the same angular portlet are dropped on a page, this will lead to a conflict unless everything is namespaced (
 ==> <div id="myapp<portlet:namespace/>">).
It is not possible to define URLs in advance as in classic application development with angularjs. Liferay portal uses its own System-generated URLs so generated tags are needed(portlet:defineObjects, portlet:resourceURL ...) to create:

```<code> <URLs(portlet:resourceURL id="config"
var="config">/portlet:resourceURL>
<script> var urlConfig = '${config}'; </script>)
</code>```

and these tags will not be available in javascript file since the javascript loads first.
This end up complicating development with angularjs and URLs handling issues are frequently encountered. A lot of workaround code is required to integrate portal URLs into angular since angular also controls URLS. And this is basically a try to integrate two directly competing technologies.
A compromise between AlloyUI and Angular must be developed, which will cause more dilemma than provide any actual benefit.
To be short, technological agnosticism sounds great in theory, but it practically does not work that well and it has more complications and disadvantages than actual benefits.
If you believe that developing then integrating a standalone web application into a portal can solve the problem, then this should be looked again because login credentials cannot be shared with the embedded application. In this case liferay has no utility.

ContentLicense: CC BY-SA 3.0

Body:
Integrating java based portals with angular is very complicated. Liferay is shipped with AlloyUi. There are side effects for using multiple JS libraries together such as AlloyUI with Angularjs.
Side effects usually manifests themselves in higher load times and possible conflicts. A single angular app protlet is required for every page containing an angular portlet. Once two instances of the same angular portlet are dropped on a page, this will lead to a conflict unless everything is namespaced (<div ng-app="myapp"> ==> <div id="myapp<portlet:namespace/>">).
It is not possible to define URLs in advance as in classic application development with angularjs. Liferay portal uses its own System-generated URLs so generated tags are needed(portlet:defineObjects, portlet:resourceURL ...) to create:

 <URLs(portlet:resourceURL id="config"
var="config">/portlet:resourceURL>
<script> var urlConfig = '${config}'; </script>)

and these tags will not be available in javascript file since the javascript loads first.
This end up complicating development with angularjs and URLs handling issues are frequently encountered. A lot of workaround code is required to integrate portal URLs into angular since angular also controls URLS. And this is basically a try to integrate two directly competing technologies.
A compromise between AlloyUI and Angular must be developed, which will cause more dilemma than provide any actual benefit.
To be short, technological agnosticism sounds great in theory, but it practically does not work that well and it has more complications and disadvantages than actual benefits.
If you believe that developing then integrating a standalone web application into a portal can solve the problem, then this should be looked again because login credentials cannot be shared with the embedded application. In this case liferay has no utility.


问:
DevExpress Set XtraTab Selected Page
I was trying to set the XtraTab Selected page in the constructor it self as follows,

```<code> public frmInquiryManagement()
        {
            InitializeComponent();
            tabInquiryManagement.SelectedTabPage = xtraTabPage3;

        }
</code>```

But it doesn't work that way. Please help me to do this.

答:
Use the following code in the Form's Load event handler:

```<code>        tabInquiryManagement.SelectedTabPage = xtraTabPage3;
        tabInquiryManagement.MakePageVisible(xtraTabPage3);
</code>```

Title: DevExpress Set XtraTab Selected Page

Body:
I was trying to set the XtraTab Selected page in the constructor it self as follows,

 public frmInquiryManagement()
        {
            InitializeComponent();
            tabInquiryManagement.SelectedTabPage = xtraTabPage3;

        }

But it doesn't work that way. Please help me to do this.

Body:
Use the following code in the Form's Load event handler:

        tabInquiryManagement.SelectedTabPage = xtraTabPage3;
        tabInquiryManagement.MakePageVisible(xtraTabPage3);


问:
sed delete all occurences of pattern in each line
The following command doesn't repeat the process for each occurence in one line...

input_file.txt :

```<code><!--:nl-->hond <span>bob</span><!--:fr-->chien <span>bob</span><!--:nl-->kat<!--:fr-->chat
<!--:nl-->hond<!--:fr-->chien<!--:nl-->kat<!--:fr-->chat
</code>```

wrong sed command :

```<code>sed -e 's/\(\<\!--\:nl\--\>\).*\(\<\!--\:fr\--\>\)/\1\2/g' input_file.txt > output_file.txt
</code>```

current output_file.txt result :

```<code><!--:nl--><!--:fr-->chat
</code>```

desired output_file.txt result :

```<code>chien <span>bob</span>chat
chienchat
</code>```

[EDIT] hond, chien, kat and chat may have HTML tags around them that need to be kept...

Body:
The following command doesn't repeat the process for each occurence in one line...

input_file.txt :

hond bobchien bobkatchat
hondchienkatchat

wrong sed command :

sed -e 's/\(\<\!--\:nl\--\>\).*\(\<\!--\:fr\--\>\)/\1\2/g' input_file.txt > output_file.txt

current output_file.txt result :

chat

desired output_file.txt result :

chien bobchat
chienchat

[EDIT] hond, chien, kat and chat may have HTML tags around them that need to be kept...

Body:
You can use this sed:

sed 's/<!--:nl-->[^<]*<!--:fr-->//g' file


问:
authenticate on SSH via BSD socket
I'd like to authenticate on ssh-server via BSD socket. I know how to initiate a connection but don't know how to actually authenticate. Thanks for your time when pointing me to the right direction.

Here is the source code:

```<code>//
#include <stdio.h>      // printf()
#include <sys/types.h>  // socket data types
#include <sys/socket.h> // socket(), connect(), send(), recv()
#include <arpa/inet.h>  // sockaddr_in, inet_addr()
#include <stdlib.h>     // free()
#include <unistd.h>     // close()

int *ssh(char *host, int port, char *user, char *pass);

int main(void)
{
// create socket
int *ssh_socket = ssh("127.0.0.1", 22, "root", "password");

// close and free
close(*ssh_socket);
free(ssh_socket);

return 0;
}

int *ssh(char *host, int port, char *user, char *pass)
{
int *sock = calloc(sizeof(int), 1);
struct sockaddr_in addr = {.sin_family=AF_INET, \
                           .sin_port=htons(port), \
                           .sin_addr.s_addr=inet_addr(host)};

*sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // create socket
connect(*sock, (struct sockaddr *)&addr, sizeof(addr)); // init connection

// here is the problem
// how do I authenticate on this socket?

return sock;
}
</code>```

答:
SSH is a quite complex protocol with several layers.

Before getting to the user authentication you have to initiate the protocol, check remote host credentials and start an encrypted connection.

And after that, there are several ways to authenticate an user you may want to support (public key, passwd, keyboard-interactive, etc.).

The Wikipedia page for SSH has links to all the related RFCs.

Really, use libssh or libssh2 or the code from OpenSSH!

ContentLicense: CC BY-SA 2.5

Title: authenticate on SSH via BSD socket

Body:
I'd like to authenticate on ssh-server via BSD socket. I know how to initiate a connection but don't know how to actually authenticate. Thanks for your time when pointing me to the right direction.

Here is the source code:

//
#include <stdio.h>      // printf()
#include <sys/types.h>  // socket data types
#include <sys/socket.h> // socket(), connect(), send(), recv()
#include <arpa/inet.h>  // sockaddr_in, inet_addr()
#include <stdlib.h>     // free()
#include <unistd.h>     // close()

int *ssh(char *host, int port, char *user, char *pass);

int main(void)
{
// create socket
int *ssh_socket = ssh("127.0.0.1", 22, "root", "password");

// close and free
close(*ssh_socket);
free(ssh_socket);

return 0;
}

int *ssh(char *host, int port, char *user, char *pass)
{
int *sock = calloc(sizeof(int), 1);
struct sockaddr_in addr = {.sin_family=AF_INET, \
                           .sin_port=htons(port), \
                           .sin_addr.s_addr=inet_addr(host)};

*sock=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // create socket
connect(*sock, (struct sockaddr *)&addr, sizeof(addr)); // init connection

// here is the problem
// how do I authenticate on this socket?

return sock;
}


问:
Accessing COM10 or greater port in C#
I am using Visual Studio 2010 and programing in C# (.NET 3.5).

I want to write/read data from COM10.

Here is the simple code for that:

```<code>static void Main(string[] args)
{
    String Portname = String.Empty;

    /* List out all COM ports present on the computer. */
    foreach (string ports in SerialPort.GetPortNames())
    {
        Console.WriteLine(ports);
        /* If COM10 exists, copy the name for further use. */
        if (ports == "COM10")
        {
            Portname = ports; //I also tried this: "\\.\\COM10";
        }
    }
    /* If COM10 not found, return */
    if (Portname == String.Empty)
    {
        Console.WriteLine("Exiting");
        return;
    }

    SerialPort Port = new SerialPort(Portname,
                                     9600,          // Baudrate
                                     Parity.None,   //Parity
                                     8,             //DataBits
                                     StopBits.One); //Stop Bits

    Port.Open();

    for (int count = 0; count < 5; count++)
    {
        Port.WriteLine("\nHello");
    }
    Port.Close();

    while (true);
}
</code>```

Whenever I use Portname as "COM10" in SerialPort Port = new SerialPort(Portname,9600,.....);, it gives an error as

The port 'COM10' does not exist

On Port.Open(), it should not even reach to command Port.Open() if COM10 doesn't exist.

Another way, I tried Portname as "\.\COM10". It gives an error as

The given port name does not start with COM/com or does not resolve to a valid serial port.

This happens with any port number greater than COM9.

Is there a way out?

答:
For port smaller or equal to 9: new SerialPort("COM9")

For port greater than 9: new SerialPort("\\\\.\\COM10")

I tested the use of the property serialArduino.PortName = ... for ports greater than 9, but this was always leading to errors, so I used the constructor new SerialPort().

Title: Accessing COM10 or greater port in C#

Body:
I am using Visual Studio 2010 and programing in C# (.NET 3.5).

I want to write/read data from COM10.

Here is the simple code for that:

static void Main(string[] args)
{
    String Portname = String.Empty;

    /* List out all COM ports present on the computer. */
    foreach (string ports in SerialPort.GetPortNames())
    {
        Console.WriteLine(ports);
        /* If COM10 exists, copy the name for further use. */
        if (ports == "COM10")
        {
            Portname = ports; //I also tried this: "\\.\\COM10";
        }
    }
    /* If COM10 not found, return */
    if (Portname == String.Empty)
    {
        Console.WriteLine("Exiting");
        return;
    }

    SerialPort Port = new SerialPort(Portname,
                                     9600,          // Baudrate
                                     Parity.None,   //Parity
                                     8,             //DataBits
                                     StopBits.One); //Stop Bits

    Port.Open();

    for (int count = 0; count < 5; count++)
    {
        Port.WriteLine("\nHello");
    }
    Port.Close();

    while (true);
}

Whenever I use Portname as "COM10" in SerialPort Port = new SerialPort(Portname,9600,.....);, it gives an error as

The port 'COM10' does not exist

On Port.Open(), it should not even reach to command Port.Open() if COM10 doesn't exist.

Another way, I tried Portname as "\.\COM10". It gives an error as

The given port name does not start with COM/com or does not resolve to a valid serial port.

This happens with any port number greater than COM9.

Is there a way out?


问:
Can't connect Kubernetes endpoints IPs with created as an headless service
Created a headless service:

myapp-service-headless.yaml

```<code>apiVersion: v1
kind: Service
metadata:
  name: myapp-service-headless
spec:
  ports:
    - port: 8000
  selector:
    app: myapp
  clusterIP: None
</code>```

After create it to Kubernetes cluster, check its service status:

```<code>$ kubectl create -f myapp-service-headless.yaml
$ kubectl describe service myapp-service-headless
Name:              myapp-service-headless
Namespace:         default
Labels:            <none>
Annotations:       <none>
Selector:          app=myapp
Type:              ClusterIP
IP:                None
Port:              <unset>  8000/TCP
TargetPort:        8000/TCP
Endpoints:         172.17.0.11:8000,172.17.0.9:8000
Session Affinity:  None
Events:            <none>
</code>```

Try to connect 172.17.0.11:8000 or 172.17.0.9:8000, pending and no result.

Here using kube-dns: myapp-service-headless.default.svc.cluster.local in the application. Now it's in the container of pods.

So how to connect to these applications from other application via API? Which IP can been used?

答:
Did you expose your container port inside your Endpoint (Pod)?

From what i knew, the headless service can be used to generate entries in kube-dns based on how you configure the Service, as discussed in this doc.

However, you can create another Service with type: NodePort that selects your backend Pods, and expose them on a NodePort/LB.

Body:
Created a headless service:

myapp-service-headless.yaml

apiVersion: v1
kind: Service
metadata:
  name: myapp-service-headless
spec:
  ports:
    - port: 8000
  selector:
    app: myapp
  clusterIP: None

After create it to Kubernetes cluster, check its service status:

$ kubectl create -f myapp-service-headless.yaml
$ kubectl describe service myapp-service-headless
Name:              myapp-service-headless
Namespace:         default
Labels:            <none>
Annotations:       <none>
Selector:          app=myapp
Type:              ClusterIP
IP:                None
Port:              <unset>  8000/TCP
TargetPort:        8000/TCP
Endpoints:         172.17.0.11:8000,172.17.0.9:8000
Session Affinity:  None
Events:            <none>

Try to connect 172.17.0.11:8000 or 172.17.0.9:8000, pending and no result.

Here using kube-dns: myapp-service-headless.default.svc.cluster.local in the application. Now it's in the container of pods.

So how to connect to these applications from other application via API? Which IP can been used?


问:
RxJava - very long delay
I need to use delay operator of RxJava. Can anyone explain how it works? Does the thread sleep during delay? How exact the delay is? I need to emit item almost after 1 day (24 hours delay) in worst case.</p>

答:
Using the delay operator we delay the creation of the pipeline from lazy to eager.
But once start emitting the delay operator does not affect the items emitted

```<code>@Test
public void delayCreation() {
    long start = System.currentTimeMillis();
    Subscription subscription = Observable.just("hello reactive world")
            .delay(200, TimeUnit.MICROSECONDS)
            .subscribe(n -> System.out.println("time:" + (System.currentTimeMillis() - start)));
    new TestSubscriber((Observer) subscription).awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
}
</code>```

You can see more examples of delay here https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/utils/ObservableDelay.java

Title: RxJava - very long delay

Body:
Using the delay operator we delay the creation of the pipeline from lazy to eager.
But once start emitting the delay operator does not affect the items emitted

@Test
public void delayCreation() {
    long start = System.currentTimeMillis();
    Subscription subscription = Observable.just("hello reactive world")
            .delay(200, TimeUnit.MICROSECONDS)
            .subscribe(n -> System.out.println("time:" + (System.currentTimeMillis() - start)));
    new TestSubscriber((Observer) subscription).awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
}

You can see more examples of delay here https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/utils/ObservableDelay.java


问:
knockout.js validation on observableArray to require all items (no empty fields)
I have written the following example of using knockout.

HTML

```<code><script id="customMessageTemplate" type="text/html">
    <em class="customMessage" data-bind='validationMessage: field'></em>
</script>
<fieldset>
    <legend>User: <span data-bind='text: errors().length'></span> errors</legend>
    <label>First name: <input data-bind='value: firstName'/></label>
    <label>Last name: <input data-bind='value: lastName'/></label>

    <table>
    <thead>
        <tr><th>Value</th></tr>
    </thead>
    <tbody data-bind="foreach: captcha">
        <tr>
            <td><input data-bind="value: value" type="test" /></td>
        </tr>
    </tbody>
</table>

<button type="button" data-bind='click: submit'>Submit</button>
</code>```

Knockout

```<code>ko.validation.rules.pattern.message = 'Invalid.';

ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null
});

var captcha = function (val) {
    return val == 11;
};

var mustEqual = function (val, other) {
    return val == other();
};

var viewModel = {
    firstName: ko.observable().extend({ required: true }),
    lastName: ko.observable().extend({ required: true }),
    captcha: ko.observableArray([{value: "test"}]),

    submit: function () {
        if (viewModel.errors().length == 0) {
            alert('Thank you.');
        } else {
            alert('Please check your submission.');
            viewModel.errors.showAllMessages();
        }
    }
};

viewModel.errors = ko.validation.group(viewModel);

ko.applyBindings(viewModel);
</code>```

What should I add to observableArray to require all items in this array the same way like usual observable object reffrering to input fields FirstName and LastName in presented example?

答:
I'm not sure if this is what you are expecting. If you want to add validation to each object of an observableArray, you can do something like this:

Create a captchaViewModel function and add the required validation to the value property

```<code>var captchaViewModel = function(val) {
  this.value = ko.observable(val).extend({
    required: true
  });
 // other properties if any
}
</code>```

Then change your viewModel to:

```<code>var viewModel = {
  firstName: ko.observable().extend({ required: true }),
  lastName: ko.observable().extend({ required: true }),
  captcha: ko.observableArray([new captchaViewModel("test")]),

  submit: function() {
    if (viewModel.errors().length == 0) {
      alert('Thank you.');
    } else {
      alert('Please check your submission.');
      viewModel.errors.showAllMessages();
    }
  }
};
</code>```

You also need to add grouping property to the configuration and set deep: true.

```<code>ko.validation.configure({
   .......
   .......
  // "deep" indicates whether to walk the ViewModel (or object) recursively,
  // or only walk first-level properties
  grouping: { deep: true }
});
</code>```

Here's a fiddle for testing

Body:
I have written the following example of using knockout.

HTML

<fieldset>
    <legend>User:  errors</legend>
    First name: <input data-bind='value: firstName'/>
    Last name: <input data-bind='value: lastName'/>

Value

            <input data-bind="value: value" type="test" />

<button type="button" data-bind='click: submit'>Submit</button>

Knockout

ko.validation.rules.pattern.message = 'Invalid.';

ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null
});

var captcha = function (val) {
    return val == 11;
};

var mustEqual = function (val, other) {
    return val == other();
};

var viewModel = {
    firstName: ko.observable().extend({ required: true }),
    lastName: ko.observable().extend({ required: true }),
    captcha: ko.observableArray([{value: "test"}]),

    submit: function () {
        if (viewModel.errors().length == 0) {
            alert('Thank you.');
        } else {
            alert('Please check your submission.');
            viewModel.errors.showAllMessages();
        }
    }
};

viewModel.errors = ko.validation.group(viewModel);

ko.applyBindings(viewModel);

What should I add to observableArray to require all items in this array the same way like usual observable object reffrering to input fields FirstName and LastName in presented example?

Body:
I'm not sure if this is what you are expecting. If you want to add validation to each object of an observableArray, you can do something like this:

Create a captchaViewModel function and add the required validation to the value property

var captchaViewModel = function(val) {
  this.value = ko.observable(val).extend({
    required: true
  });
 // other properties if any
}

Then change your viewModel to:

var viewModel = {
  firstName: ko.observable().extend({ required: true }),
  lastName: ko.observable().extend({ required: true }),
  captcha: ko.observableArray([new captchaViewModel("test")]),

  submit: function() {
    if (viewModel.errors().length == 0) {
      alert('Thank you.');
    } else {
      alert('Please check your submission.');
      viewModel.errors.showAllMessages();
    }
  }
};

You also need to add grouping property to the configuration and set deep: true.

ko.validation.configure({
   .......
   .......
  // "deep" indicates whether to walk the ViewModel (or object) recursively,
  // or only walk first-level properties
  grouping: { deep: true }
});

Here's a fiddle for testing


问:
How to configure my solution to show all projects collapsed on Visual Studio?
Every time I check out my solution from the SCM I have to collapse manually each project in my solution to get a good overview of it.

I know that the collapsed settings are stored in a .suo file, which is binary. I don't want to commit this file to the SCM, instead I am looking for a xml tag that I could put in the .sln file so when I open it all projects are collapsed.

How to do that?

答:
Install Productivity Power Tools and use Solution Navigator instead of Solution Explorer:

Solution Navigator is a new tool window that acts like an enhanced Solution Explorer.  With it, you can:

```<code>* Expand code files to navigate to its classes, expand classes to navigate to their members, and so on (C# and VB only)
* Search your solution, all the way down to class members
* Filter your solution or projects to see just opened files, unsaved files, and so on
* View related information about classes and members (such as references or callers/callees for C#)
* Preview images by hovering over them, or preview rich information by hovering over code items
* We've also added support for multiple selection and drag & drop. (New!)
</code>```

It also haves a collapse all button.

Body:
Install Productivity Power Tools and use Solution Navigator instead of Solution Explorer:

Solution Navigator is a new tool window that acts like an enhanced Solution Explorer.  With it, you can:

* Expand code files to navigate to its classes, expand classes to navigate to their members, and so on (C# and VB only)
* Search your solution, all the way down to class members
* Filter your solution or projects to see just opened files, unsaved files, and so on
* View related information about classes and members (such as references or callers/callees for C#)
* Preview images by hovering over them, or preview rich information by hovering over code items
* We've also added support for multiple selection and drag & drop. (New!)

It also haves a collapse all button.


问:
Writing JSON object to a JSON file with fs.writeFileSync
I am trying to write a JSON object to a JSON file. The code executes without errors, but instead of the content of the object been written, all that gets written into the JSON file is:

```<code>[object Object]
</code>```

This is the code that actually does the writing:

```<code>fs.writeFileSync('../data/phraseFreqs.json', output)
</code>```

'output' is a JSON object, and the file already exists. Please let me know if more information is required.

答:
Make the json human readable by passing a third argument to stringify:

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output, null, 4));
```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a JSON object to a JSON file. The code executes without errors, but instead of the content of the object been written, all that gets written into the JSON file is:

[object Object]

This is the code that actually does the writing:

fs.writeFileSync('../data/phraseFreqs.json', output)

'output' is a JSON object, and the file already exists. Please let me know if more information is required.


问:
Cannot convert String array to Int array from core data and sum it in Swift 4
I have 2 question. First, I can't convert String array to Int array from core data

```<code>let sum = recordFilter.map{$0.amount!.dropFirst()} //["9.99", "6.58"]
let intSum = sum.map({Int($0)})  //[nil, nil]
</code>```

My array format:

```<code>[<Record: 0x600000099fa0> (entity: Record; id: 0xd0000000003c0000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p15> ; data: {
    accountbook = "first book";
    amount = "\U00a59.99";
    assest = nil;
    category = "\U6295\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 15;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
}), ...})]
</code>```

Second, I want to sum it by .reduce but I got Cannot invoke 'reduce' with an argument list of type '(Int, _)' How to fix it?

```<code>let sum = recordFilter.map{$0.amount!.dropFirst()}.reduce(0, +)
let intSum = sum.map({Int($0)}).reduce(0, +)
//Cannot invoke 'reduce' with an argument list of type '(Int, _)'
</code>```

答:
You should annotate explicit types for your variables to check if you are coding what you think you are. My guess is you are used to dynamic languages; it doesn't work that way here.

recordFilter.map { ... } creates a String, so reduce needs a pair of parameters of types T and (T, String) -> T, respectively. With T == Int, it's looking for +: (Int, String) -> Int which does not exist.

Note that if you fix that, sum is either String or Int (not sure what you want), to neither of which applying map does what you want it to do, by my estimation.

Body:
I have 2 question. First, I can't convert String array to Int array from core data

let sum = recordFilter.map{$0.amount!.dropFirst()} //["9.99", "6.58"]
let intSum = sum.map({Int($0)})  //[nil, nil]

My array format:

[<Record: 0x600000099fa0> (entity: Record; id: 0xd0000000003c0000 <x-coredata://913F25A5-B2C9-4646-9091-5EFE7F906908/Record/p15> ; data: {
    accountbook = "first book";
    amount = "\U00a59.99";
    assest = nil;
    category = "\U6295\U8d44";
    createdAt = "2017-11-16 16:00:00 +0000";
    date = nil;
    id = 15;
    recordtype = "\U6536\U5165";
    remark = "";
    toAccBook = nil;
}), ...})]

Second, I want to sum it by .reduce but I got Cannot invoke 'reduce' with an argument list of type '(Int, _)' How to fix it?

let sum = recordFilter.map{$0.amount!.dropFirst()}.reduce(0, +)
let intSum = sum.map({Int($0)}).reduce(0, +)
//Cannot invoke 'reduce' with an argument list of type '(Int, _)'


问:
How to create round button with text inside
How to create round button with text or char inside.
It should look like this: It should look like this, image below:

img example

So far I made this, but it's not so round:

```<code>import React, { Component } from 'react';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
import { Constants } from 'expo';
import Icon from 'react-native-vector-icons/FontAwesome'; // 4.4.2

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={() => null}>
                <Icon
                  name="chevron-left"
                  icon={{ name: 'rss', type: 'font-awesome' }}
                  style={styles.button}
                  size={25}
                />
              </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
  button: {
    padding: 25,
    backgroundColor: 'black',
    color: 'white',
    borderRadius: 50,
  },
});
</code>```

答:
```<code><TouchableOpacity
  style={{ borderWidth:1,
    borderColor:'rgba(0,0,0,0.2)',
    alignItems:'center',
    justifyContent:'center',
    width:100,
    height:100,
    backgroundColor:'#fff',
    borderRadius:100,
  }}
  >
  <Icon name={"chevron-right"}
    size={30}
    color="#01a699" />
</TouchableOpacity>
</code>```

Body:
How to create round button with text or char inside.
It should look like this: It should look like this, image below:

img example

So far I made this, but it's not so round:

import React, { Component } from 'react';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
import { Constants } from 'expo';
import Icon from 'react-native-vector-icons/FontAwesome'; // 4.4.2

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={() => null}>
                <Icon
                  name="chevron-left"
                  icon={{ name: 'rss', type: 'font-awesome' }}
                  style={styles.button}
                  size={25}
                />
              </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
  button: {
    padding: 25,
    backgroundColor: 'black',
    color: 'white',
    borderRadius: 50,
  },
});


问:
Apache Isis apend HTML tag to VM (JAXB)
I want to add some HTML tags to my View Module (JAXB), but I can't find any solution. e.g I want to display an iframe or add some div tags.

What I can add to my VM is property as bellow.

```<code><cpt:property id="fieldName" cssClass="abc-class"/>
</code>```

How can I create another tags similar to above, e.g <cpt:iframe src="http://examle.com" /> into my layout.xml.

Another problem is cssClass on tag above doesn't work.

If I can add some HTML tag, I will be able to make my UI much more better.

答: My problems solve by using property using org.apache.isis.applib.value.Markup

Title: Apache Isis apend HTML tag to VM (JAXB)

Body:
I want to add some HTML tags to my View Module (JAXB), but I can't find any solution. e.g I want to display an iframe or add some div tags.

What I can add to my VM is property as bellow.

<cpt:property id="fieldName" cssClass="abc-class"/>

How can I create another tags similar to above, e.g <cpt:iframe src="http://examle.com" /> into my layout.xml.

Another problem is cssClass on tag above doesn't work.

If I can add some HTML tag, I will be able to make my UI much more better.


问:
custom validation markup in Rails(3)
I'm trying to accomplish the following mark-up for all my form elements

```<code><div class="input-container">
  <label>Topic Title</label>
  <div class="input-holder">
    <input type="text" />
  </div>
</div>

<div class="textarea-container">
  <label>Post</label>
  <div class="textarea-holder">
    <textarea></textarea>
  </div>
</div>
</code>```

invalid fields mark-up:

```<code><div class="input-container alert">
  <label>Topic Title</label>
  <div class="input-holder">
    <input type="text" />
  </div>
</div>
<div class="textarea-container alert">
  <label>Post</label>
  <div class="textarea-holder">
    <textarea></textarea>
  </div>
</div>
</code>```

here's my current haml markup:

```<code>.input-container
  = f.label :title, 'Topic Title'
  .input-holder
    = f.text_field :title
.textarea-container
  = f.label :body, 'Post'
  .textarea-holder
    = f.text_area(:body, :size => "60x10")
</code>```

Now what would I need to do if I want the container divs to have the alert class when a field in my form is invalid?

答:
I want to do the same thing but unfortunately haven't figured out a clean way to handle it.

You can override ActionView::Base.field_error_proc, but that doesn't help with the enclosing elements.

It can be done manually by checking errors on each field ('post.errors['body'].nil?') and outputting your alert class conditionally.

The next step could be extracting the logic into a view helper, and perhaps some further abstraction after that.

But it would still be nice to do this in a more automated, Rails-y fashion.

Title: custom validation markup in Rails(3)

Body:
I'm trying to accomplish the following mark-up for all my form elements

  Topic Title

    <input type="text" />

  Post

    <textarea></textarea>

invalid fields mark-up:

  Topic Title

    <input type="text" />

  Post

    <textarea></textarea>

here's my current haml markup:

.input-container
  = f.label :title, 'Topic Title'
  .input-holder
    = f.text_field :title
.textarea-container
  = f.label :body, 'Post'
  .textarea-holder
    = f.text_area(:body, :size => "60x10")

Now what would I need to do if I want the container divs to have the alert class when a field in my form is invalid?


问:
NodeJS/ExpressJS : proxy an HTTP video stream (from VLC)
With VLC 2.2.1 I create an HTTP stream of my webcam hosted by a computer named server.

On another computer, client, if I open vlc, and open the network stream http://server:8080 I can see the webcam video perfectly.

A wireshark capture of the HTTP stream look like the following :

```<code>GET / HTTP/1.1
Host: server:8080
User-Agent: VLC/2.2.0-rc2 LibVLC/2.2.0-rc2
Range: bytes=0-
Connection: close
Icy-MetaData: 1

HTTP/1.0 200 OK
Content-type: application/octet-stream
Cache-Control: no-cache

FLV.......................
onMetaData.......duration...........width.@.........height.@~.......
videodatarate.@.@.......videocodecid.@.........encoder..
Lavf56.1.0..filesize....
etc...
</code>```

On the client computer, I have an API running under NodeJS v5 & Express v3 and I'd like to have an url like : http://client/video that act as a proxy to http://server:8080 so the users can only see one endpoint.

I saw few npm module claiming to act as "proxy" but due to the special nature of the content (live video stream) I'm not sure of what I should do.

答:
```<code>var express = require('express')
var fetch = require('node-fetch')

var app = express()

app.get('/video', (req, res) => {
  fetch('http://server:8080')
    .then(r => r.body)
    .then(s => {
      s.pipe(res)
    })
    .catch(e => {
      res.status(500).send('Error.')
    })
})

app.listen(80)
</code>```

to open up port 80, you'll need to be root, so run with sudo

Body:
With VLC 2.2.1 I create an HTTP stream of my webcam hosted by a computer named server.

On another computer, client, if I open vlc, and open the network stream http://server:8080 I can see the webcam video perfectly.

A wireshark capture of the HTTP stream look like the following :

GET / HTTP/1.1
Host: server:8080
User-Agent: VLC/2.2.0-rc2 LibVLC/2.2.0-rc2
Range: bytes=0-
Connection: close
Icy-MetaData: 1

HTTP/1.0 200 OK
Content-type: application/octet-stream
Cache-Control: no-cache

FLV.......................
onMetaData.......duration...........width.@.........height.@~.......
videodatarate.@.@.......videocodecid.@.........encoder..
Lavf56.1.0..filesize....
etc...

On the client computer, I have an API running under NodeJS v5 & Express v3 and I'd like to have an url like : http://client/video that act as a proxy to http://server:8080 so the users can only see one endpoint.

I saw few npm module claiming to act as "proxy" but due to the special nature of the content (live video stream) I'm not sure of what I should do.

Body:
var express = require('express')
var fetch = require('node-fetch')

var app = express()

app.get('/video', (req, res) => {
  fetch('http://server:8080')
    .then(r => r.body)
    .then(s => {
      s.pipe(res)
    })
    .catch(e => {
      res.status(500).send('Error.')
    })
})

app.listen(80)

to open up port 80, you'll need to be root, so run with sudo


问:
Error:Execution failed for task ':app:transformClassesWithAndroidGradleClassShrinkerForDebug'

Problem

When I try to build my project I get this error

Error:Execution failed for task
  ':app:transformClassesWithAndroidGradleClassShrinkerForDebug'.

Warnings found during shrinking, please use -dontwarn or -ignorewarnings to suppress them.

My files

app build.gradle

```<code>apply plugin: 'com.android.application'
android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"

    dexOptions {
        maxProcessCount = 2
        javaMaxHeapSize = "2g"
    }

    dataBinding {
        enabled = true
    }

    packagingOptions {
        exclude 'META-INF/rxjava.properties'
        exclude 'META-INF/SearchFilter.properties'
        exclude 'META-INF/NOTICE' // will not include NOTICE file
        exclude 'META-INF/LICENSE' // will not include LICENSE file
        // as noted by @Vishnuvathsan you may also need to include
        // variations on the file name. It depends on your dependencies.
        // Some other common variations on notice and license file names
        exclude 'META-INF/notice'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license'
        exclude 'META-INF/license.txt'
    }

    defaultConfig {
        applicationId "com.mt.moviesiwanttowatch"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 4
        versionName "1.2"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            minifyEnabled true
            useProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    //Optional: see how to use the utility.
    implementation files('libs/YouTubeAndroidPlayerApi.jar')
    implementation 'com.android.support:appcompat-v7:26.0.0-beta2'
    implementation "com.android.support:support-v13:26.0.0-beta2"
    implementation 'com.android.support:design:26.0.0-beta2'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0-beta1'
    implementation 'com.android.support:recyclerview-v7:26.0.0-beta2'
    implementation 'com.android.support:cardview-v7:26.0.0-beta2'
    implementation 'com.google.android.gms:play-services-analytics:11.0.2'
    implementation 'com.allattentionhere:fabulousfilter:0.0.2'
    implementation 'com.nightonke:boommenu:2.1.0'
    implementation 'com.github.Commit451:QuickActionView:2.0.0'
    implementation 'com.android.volley:volley:1.0.0'
    implementation 'com.nononsenseapps:filepicker:4.1.0'
    implementation 'net.simonvt.schematic:schematic:0.7.0'
    implementation 'io.reactivex:rxandroid:1.2.1'
    implementation 'io.reactivex:rxjava:1.3.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.1'
    implementation 'com.ramotion.cardslider:card-slider:0.1.0'

    implementation 'org.jsoup:jsoup:1.10.3'
    implementation 'com.google.code.gson:gson:2.8.1'
    implementation 'com.squareup.leakcanary:leakcanary-android:1.5.1'
    implementation "net.dean.jraw:JRAW:0.9.0"
    implementation 'com.gordonwong:material-sheet-fab:1.2.1'
    implementation 'com.github.bumptech.glide:glide:4.0.0-RC1'
    implementation('com.google.android:flexbox:0.3.0') {
        exclude group: 'com.android.support'
    }
    implementation 'me.drozdzynski.library.steppers:steppers:0.4.0-SNAPSHOT'
    implementation 'com.ogaclejapan.smarttablayout:library:1.6.1@aar'
    implementation 'com.ogaclejapan.smarttablayout:utils-v4:1.6.1@aar'
    implementation 'com.afollestad.material-dialogs:core:0.9.4.5'
    implementation 'com.android.support:multidex:1.0.1'
    implementation 'com.github.jetradarmobile.desertplaceholder:desertplaceholder:1.2.3'
    implementation 'com.github.rubensousa:gravitysnaphelper:1.2'
    annotationProcessor 'com.android.databinding:compiler:2.3.3'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC1'
    annotationProcessor 'net.simonvt.schematic:schematic-compiler:0.7.0'
}
</code>```

project build.gradle:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha6'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com"}
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

and proguard-rules.pro

```<code># Add project specific ProGuard rules here.
# By defaulto, the flags in this file are appended to flags specified
# in C:\Users\CM\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# Add any project specific keep options here:

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

-keep class io.codetail.animation.arcanimator.** { *; }
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.AppGlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}
</code>```

Question

How do I modify my files to fix this problem ?

Body:
Problem

When I try to build my project I get this error

Error:Execution failed for task
  ':app:transformClassesWithAndroidGradleClassShrinkerForDebug'.

Warnings found during shrinking, please use -dontwarn or -ignorewarnings to suppress them.

My files

app build.gradle

apply plugin: 'com.android.application'
android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"

    dexOptions {
        maxProcessCount = 2
        javaMaxHeapSize = "2g"
    }

    dataBinding {
        enabled = true
    }

    packagingOptions {
        exclude 'META-INF/rxjava.properties'
        exclude 'META-INF/SearchFilter.properties'
        exclude 'META-INF/NOTICE' // will not include NOTICE file
        exclude 'META-INF/LICENSE' // will not include LICENSE file
        // as noted by @Vishnuvathsan you may also need to include
        // variations on the file name. It depends on your dependencies.
        // Some other common variations on notice and license file names
        exclude 'META-INF/notice'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license'
        exclude 'META-INF/license.txt'
    }

    defaultConfig {
        applicationId "com.mt.moviesiwanttowatch"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 4
        versionName "1.2"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            minifyEnabled true
            useProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    //Optional: see how to use the utility.
    implementation files('libs/YouTubeAndroidPlayerApi.jar')
    implementation 'com.android.support:appcompat-v7:26.0.0-beta2'
    implementation "com.android.support:support-v13:26.0.0-beta2"
    implementation 'com.android.support:design:26.0.0-beta2'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0-beta1'
    implementation 'com.android.support:recyclerview-v7:26.0.0-beta2'
    implementation 'com.android.support:cardview-v7:26.0.0-beta2'
    implementation 'com.google.android.gms:play-services-analytics:11.0.2'
    implementation 'com.allattentionhere:fabulousfilter:0.0.2'
    implementation 'com.nightonke:boommenu:2.1.0'
    implementation 'com.github.Commit451:QuickActionView:2.0.0'
    implementation 'com.android.volley:volley:1.0.0'
    implementation 'com.nononsenseapps:filepicker:4.1.0'
    implementation 'net.simonvt.schematic:schematic:0.7.0'
    implementation 'io.reactivex:rxandroid:1.2.1'
    implementation 'io.reactivex:rxjava:1.3.0'
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.1'
    implementation 'com.ramotion.cardslider:card-slider:0.1.0'

    implementation 'org.jsoup:jsoup:1.10.3'
    implementation 'com.google.code.gson:gson:2.8.1'
    implementation 'com.squareup.leakcanary:leakcanary-android:1.5.1'
    implementation "net.dean.jraw:JRAW:0.9.0"
    implementation 'com.gordonwong:material-sheet-fab:1.2.1'
    implementation 'com.github.bumptech.glide:glide:4.0.0-RC1'
    implementation('com.google.android:flexbox:0.3.0') {
        exclude group: 'com.android.support'
    }
    implementation 'me.drozdzynski.library.steppers:steppers:0.4.0-SNAPSHOT'
    implementation 'com.ogaclejapan.smarttablayout:library:1.6.1@aar'
    implementation 'com.ogaclejapan.smarttablayout:utils-v4:1.6.1@aar'
    implementation 'com.afollestad.material-dialogs:core:0.9.4.5'
    implementation 'com.android.support:multidex:1.0.1'
    implementation 'com.github.jetradarmobile.desertplaceholder:desertplaceholder:1.2.3'
    implementation 'com.github.rubensousa:gravitysnaphelper:1.2'
    annotationProcessor 'com.android.databinding:compiler:2.3.3'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC1'
    annotationProcessor 'net.simonvt.schematic:schematic-compiler:0.7.0'
}

project build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha6'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com"}
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and proguard-rules.pro

# Add project specific ProGuard rules here.
# By defaulto, the flags in this file are appended to flags specified
# in C:\Users\CM\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# Add any project specific keep options here:

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
#   public *;
#}

-keep class io.codetail.animation.arcanimator.** { *; }
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public class * extends com.bumptech.glide.AppGlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

Question

How do I modify my files to fix this problem ?

Body: change buildTypes->debug->minifyEnabled=false


问:
SFINAE based on type name
In my search, I've found ways to chose template expansions based on existence of member functions, if a type is integral etc. but what I am trying to do is to have something like SFINAE based on type name. Look at the example taken from another question:

```<code>template<typename T>
std::enable_if_t<std::is_integral<T>::value> f(T t){
    //integral version
}
</code>```

This let's me have a selection based on if type T is integral or not. What I want to do is, let's say I have couple of classes that I defined; gl_renderable_t, vulkan_renderable_t etc. I want to have something like;

```<code>template<typename T>
std::enable_if_t<!T.has_typename(gl_renderable_t)!::value> f(T t){
    // call gl render functions
}

template<typename T>
std::enable_if_t<!T.has_typename(vulkan_renderable_t)!::value> f(T t){
    // call vulkan render functions
}
</code>```

I want to use SFINAE based on typename basically. This seems it should be easy or at least possible given all the crazy things people do with SFINAE but I could not figure out how to do it.

答:
You can use std::is_same<T, U> for this:

```<code>template <typename T>
std::enable_if_t<std::is_same_v<gl_renderable_t, T>> f(T t);
</code>```

Note: std::is_same works by having a base template accepting T, U and a partial specialisation for T, T requiring identical types. The specialisation provides the true value and the base has the false value:

```<code>template<class T, class U>
struct is_same : std::false_type {};

template<class T>
struct is_same<T, T> : std::true_type {};
</code>```

Title: SFINAE based on type name

Body:
In my search, I've found ways to chose template expansions based on existence of member functions, if a type is integral etc. but what I am trying to do is to have something like SFINAE based on type name. Look at the example taken from another question:

template<typename T>
std::enable_if_t<std::is_integral<T>::value> f(T t){
    //integral version
}

This let's me have a selection based on if type T is integral or not. What I want to do is, let's say I have couple of classes that I defined; gl_renderable_t, vulkan_renderable_t etc. I want to have something like;

template<typename T>
std::enable_if_t<!T.has_typename(gl_renderable_t)!::value> f(T t){
    // call gl render functions
}

template<typename T>
std::enable_if_t<!T.has_typename(vulkan_renderable_t)!::value> f(T t){
    // call vulkan render functions
}

I want to use SFINAE based on typename basically. This seems it should be easy or at least possible given all the crazy things people do with SFINAE but I could not figure out how to do it.

Body:
You can use std::is_same<T, U> for this:

template <typename T>
std::enable_if_t<std::is_same_v<gl_renderable_t, T>> f(T t);

Note: std::is_same works by having a base template accepting T, U and a partial specialisation for T, T requiring identical types. The specialisation provides the true value and the base has the false value:

template<class T, class U>
struct is_same : std::false_type {};

template<class T>
struct is_same<T, T> : std::true_type {};


问:
Loop Through jQuery Elements Separately and Animate on Page Scroll
I've managed to get a simple stat counter running up from zero to a given value where it's only activated on page scroll, but it's not exactly as I was aiming for.

The problem is, all of the ".counter" elements are firing off at the same time as soon as the first element comes into view, as opposed to waiting until each individual element is actually visible on screen. So as soon at the window hits the containing div, all of them go off at once.

I'd like to have each individual .counter wait until it's fully visible before it fires off.

Here's what I've got so far:

HTML:

```<code><p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<div id="stats">
  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="400"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="350"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="12"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="97"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="899"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="4"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="0"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="6"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>
</div>
</code>```

And the jQuery...

```<code>    (function($) {

  $(function() {

    var $counters = $('.counter'); //contains all elements of counter class

    var $window = $(window);

    $window.on('scroll', function(e) {
      $counters.each(function(i, elem) { //loop through each element
        if ($(this).hasClass('counted')) // check if already animated
          return;
        animateCounter($(this));
      });
    });
  });

  function animateCounter(elem) {
    var winTop = $(window).scrollTop(); // calculate distance from top of window
    var winBottom = winTop + $(window).height();
    var elemTop = $(elem).offset().top; // element distance from top of page
    var elemBottom = elemTop + $(elem).height();

    if ((elemBottom <= winBottom) && (elemTop >= winTop)) {
      $('.counter').each(function() {
        var $this = $(this);
        jQuery({
          Counter: 0
        }).animate({
          Counter: $this.attr('count')
        }, {
          duration: 3000,
          step: function() {
            $this.text(Math.ceil(this.Counter));
          }
        });
        $this.removeClass('counter').addClass('counted');
      });
    }
  }
})(jQuery);
</code>```

Fiddle here:
https://jsfiddle.net/ahfL4jxr/11/

Thanks in advance.

答:
there was an error in your javascript in animateCounter() function, you did an unnecessary foreach because in the function you already passed the element you need to animate when you call it.

(function($) {

  $(function() {

    var $counters = $('.counter'); //contains all elements of counter class

    var $window = $(window);

    $window.on('scroll', function(e) {
      $counters.each(function(i, elem) { //loop through each element
        if ($(this).hasClass('counted')) // check if already animated
          return;
        animateCounter($(this));
      });
    });
  });

  function animateCounter(elem) {
    var winTop = $(window).scrollTop(); // calculate distance from top of window
    var winBottom = winTop + $(window).height();
    var elemTop = $(elem).offset().top; // element distance from top of page
    var elemBottom = elemTop + $(elem).height();

    if ((elemBottom <= winBottom) && (elemTop >= winTop)) {
      var $this = $(elem);
      jQuery({
        Counter: 0
      }).animate({
        Counter: $this.attr('count')
      }, {
        duration: 3000,
        step: function() {
          $this.text(Math.ceil(this.Counter));
        }
      });
      $this.removeClass('counter').addClass('counted');
    }
  }
})(jQuery);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#stats {
  font-size: 0;
}

#stats * {
  color: #000;
}

.single-stat {
  width: 45%;
  margin: 2.5%;
  display: inline-block;
  vertical-align: top;
  text-align: center;
}

.stat-container {
  position: relative;
}

.top-line {
  font-size: 30px;
  color: red;
}

.stat {
  font-size: 48px;
  margin: 0;
}

.bottom-line {
  font-size: 16px;
}

.animateBlock {
  display: inline-block;
  position: relative;
}

.animateBlock {
  opacity: 0;
}

.left.animated {
  transform: translateX(-40px);
}

.right.animated {
  transform: translateX(40px);
}

.top.animated {
  transform: translateY(-40px);
}

.bottom.animated {
  transform: translateY(40px);
}

.animated {
  animation: come-in 0.5s ease forwards;
}

@keyframes come-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
    transform: translateY(0);
    transform: translateX(0);
  }
}</code>```

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

```

Body:
I've managed to get a simple stat counter running up from zero to a given value where it's only activated on page scroll, but it's not exactly as I was aiming for.

The problem is, all of the ".counter" elements are firing off at the same time as soon as the first element comes into view, as opposed to waiting until each individual element is actually visible on screen. So as soon at the window hits the containing div, all of them go off at once.

I'd like to have each individual .counter wait until it's fully visible before it fires off.

Here's what I've got so far:

HTML:

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

And the jQuery...

    (function($) {

  $(function() {

    var $counters = $('.counter'); //contains all elements of counter class

    var $window = $(window);

    $window.on('scroll', function(e) {
      $counters.each(function(i, elem) { //loop through each element
        if ($(this).hasClass('counted')) // check if already animated
          return;
        animateCounter($(this));
      });
    });
  });

  function animateCounter(elem) {
    var winTop = $(window).scrollTop(); // calculate distance from top of window
    var winBottom = winTop + $(window).height();
    var elemTop = $(elem).offset().top; // element distance from top of page
    var elemBottom = elemTop + $(elem).height();

    if ((elemBottom <= winBottom) && (elemTop >= winTop)) {
      $('.counter').each(function() {
        var $this = $(this);
        jQuery({
          Counter: 0
        }).animate({
          Counter: $this.attr('count')
        }, {
          duration: 3000,
          step: function() {
            $this.text(Math.ceil(this.Counter));
          }
        });
        $this.removeClass('counter').addClass('counted');
      });
    }
  }
})(jQuery);

Fiddle here:
https://jsfiddle.net/ahfL4jxr/11/

Thanks in advance.

Body:
there was an error in your javascript in animateCounter() function, you did an unnecessary foreach because in the function you already passed the element you need to animate when you call it.

(function($) {

  $(function() {

    var $counters = $('.counter'); //contains all elements of counter class

    var $window = $(window);

    $window.on('scroll', function(e) {
      $counters.each(function(i, elem) { //loop through each element
        if ($(this).hasClass('counted')) // check if already animated
          return;
        animateCounter($(this));
      });
    });
  });

  function animateCounter(elem) {
    var winTop = $(window).scrollTop(); // calculate distance from top of window
    var winBottom = winTop + $(window).height();
    var elemTop = $(elem).offset().top; // element distance from top of page
    var elemBottom = elemTop + $(elem).height();

    if ((elemBottom <= winBottom) && (elemTop >= winTop)) {
      var $this = $(elem);
      jQuery({
        Counter: 0
      }).animate({
        Counter: $this.attr('count')
      }, {
        duration: 3000,
        step: function() {
          $this.text(Math.ceil(this.Counter));
        }
      });
      $this.removeClass('counter').addClass('counted');
    }
  }
})(jQuery);

#stats {
  font-size: 0;
}

#stats * {
  color: #000;
}

.single-stat {
  width: 45%;
  margin: 2.5%;
  display: inline-block;
  vertical-align: top;
  text-align: center;
}

.stat-container {
  position: relative;
}

.top-line {
  font-size: 30px;
  color: red;
}

.stat {
  font-size: 48px;
  margin: 0;
}

.bottom-line {
  font-size: 16px;
}

.animateBlock {
  display: inline-block;
  position: relative;
}

.animateBlock {
  opacity: 0;
}

.left.animated {
  transform: translateX(-40px);
}

.right.animated {
  transform: translateX(40px);
}

.top.animated {
  transform: translateY(-40px);
}

.bottom.animated {
  transform: translateY(40px);
}

.animated {
  animation: come-in 0.5s ease forwards;
}

@keyframes come-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
    transform: translateY(0);
    transform: translateX(0);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<div id="stats">
  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="400"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="350"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="12"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="97"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="899"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="4"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="0"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="6"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>
</div>


问:
How to create a rectangle with two rounded corners?
I need to create a rectangle view with two rounded corners using canvas.I used drawRoundRect but i am getting rectangle with four rounded corners.Please anyone suggest me a way that can be helpful in solving my problem.</p>

```<code> rect = new RectF(left, top, right, bottom);

 canvas.drawRoundRect(rect, 20, 20, facePaint);
</code>```

答:
Simply go to you drawable folder add new xml file and add below code:-

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

    <corners
      android:radius="20dp"/>
    <solid android:color="@color/green" />
</shape>
</code>```

After that set background of any view like this:-

```<code>android:background="@drawable/round_green"
</code>```

you can change color according to your choice.

Hope it will helps you.

Body:
I need to create a rectangle view with two rounded corners using canvas.I used drawRoundRect but i am getting rectangle with four rounded corners.Please anyone suggest me a way that can be helpful in solving my problem.

 rect = new RectF(left, top, right, bottom);

 canvas.drawRoundRect(rect, 20, 20, facePaint);

Body:
Simply go to you drawable folder add new xml file and add below code:-

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <corners
      android:radius="20dp"/>
    <solid android:color="@color/green" />
</shape>

After that set background of any view like this:-

android:background="@drawable/round_green"

you can change color according to your choice.

Hope it will helps you.


问:
What do I do to make the TextView (address+postcode) clickable & to open google maps?
```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
android:id="@+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="map" />

<TextView
android:id="@+id/postcode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="map" />

<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>

</LinearLayout>
</code>```

答:
Its very simple...

Just add onCLickListener on to the TextView..
in the function dont directly call the map activity.
but instaed firstly change the color of textview.
and then using Handler call postDelayed Method to call the Map Activity to have clicking effect

check the code below

```<code>Handler mHandler = new Handler();
final TextView myTextView = (TextView)findViewById(R.id.TextView01);
myTextView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

        // TODO Auto-generated method stub

                           myTextView.setTextColor(Color.red);
                           mHandler.postDelayed(new Runnable(){

                                public void run()
                                {
                                   // Here call your map activity
                                }
                             },200L);
        }
    });
</code>```

Hope this will help :)

Body:
Its very simple...

Just add onCLickListener on to the TextView..
in the function dont directly call the map activity.
but instaed firstly change the color of textview.
and then using Handler call postDelayed Method to call the Map Activity to have clicking effect

check the code below

Handler mHandler = new Handler();
final TextView myTextView = (TextView)findViewById(R.id.TextView01);
myTextView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

        // TODO Auto-generated method stub

                           myTextView.setTextColor(Color.red);
                           mHandler.postDelayed(new Runnable(){

                                public void run()
                                {
                                   // Here call your map activity
                                }
                             },200L);
        }
    });

Hope this will help :)


问:
How to get graph with transaction support from remote gremlin server?
I have next configuration: remote Gremlin server (TinkerPop 3.2.6) with Janus GraphDB

I have gremlin-console (with janus plugin) + conf in remote.yaml:

hosts: [10.1.3.2] # IP og gremlin-server host
port: 8182
serializer: { className: org.apache.tinkerpop.gremlin.driver.ser.GryoMessageSerializerV1d0, config: { serializeResultToString: true }}

So I want to make connection through gremlin-server (not to JanusGraph directly by graph = JanusGraphFactory.build().set("storage.backend", "cassandra").set("storage.hostname", "127.0.0.1").open();) and get graph which supports transactions?

Is it possible? Because as I see all TinkerFactory graphs do not support transactions

答:
As I understood to use the Janus graph through the gremlin server you should:

Define ip&port in the config file of the gremlin-console:

```<code>conf/remote.yaml
</code>```

Connect by Gremlin-console to the gremlin server:

```<code>: remote connect tinkerpop.server conf/remote.yaml
==> Configured localhost/10.1.23.113: 8182
</code>```

...and work in remote mode (using :> or :remote console), i.e. send ALL commands (or @script) to the gremlin-server.

```<code>:> graph.addVertex(...)
</code>```

or

```<code>:remote console
==>All scripts will now be sent to Gremlin Server - [10.1.2.222/10.1.2.222:818]
graph.addVertex(...)
</code>```

You don't need to define variables for the graph and the trawersal, but rather used

```<code>graph. - for the graph
g. - for the traversal
</code>```

In this case, you can uses all graph features that are provided by the JanusGraphDB.

Body:
As I understood to use the Janus graph through the gremlin server you should:

Define ip&port in the config file of the gremlin-console:

conf/remote.yaml

Connect by Gremlin-console to the gremlin server:

: remote connect tinkerpop.server conf/remote.yaml
==> Configured localhost/10.1.23.113: 8182

...and work in remote mode (using :> or :remote console), i.e. send ALL commands (or @script) to the gremlin-server.

:> graph.addVertex(...)

or

:remote console
==>All scripts will now be sent to Gremlin Server - [10.1.2.222/10.1.2.222:818]
graph.addVertex(...)

You don't need to define variables for the graph and the trawersal, but rather used

graph. - for the graph
g. - for the traversal

In this case, you can uses all graph features that are provided by the JanusGraphDB.


问:
what is the SQL query to get all dates list from specific date to today date
I need to get all dates from 01-01-2016 to todays date.

Example:

```<code>01-01-2016
02-01-2016
03-01-2016
.
.
.
01-02-2016
.
.
.
17-11-2017
</code>```

Any help would be appreciated.

答:
you can make use of common table expression for achieving this and it is one of the fastest way to do it</p>

```<code>;WITH cte
 as
(
  SELECT CONVERT(DATE,'01-01-2016') as DateCol
  UNION ALL
  SELECT CONVERT(DATE,DATEADD(DAY,1,DateCol))  FROM CTE
  WHERE DATEADD(DAY,1,DateCol) <= '11-17-2017'
 )

SELECT * FROM CTE
OPTION (maxrecursion 0)
</code>```

Body:
I need to get all dates from 01-01-2016 to todays date.

Example:

01-01-2016
02-01-2016
03-01-2016
.
.
.
01-02-2016
.
.
.
17-11-2017

Any help would be appreciated.

Body:
you can make use of common table expression for achieving this and it is one of the fastest way to do it

;WITH cte
 as
(
  SELECT CONVERT(DATE,'01-01-2016') as DateCol
  UNION ALL
  SELECT CONVERT(DATE,DATEADD(DAY,1,DateCol))  FROM CTE
  WHERE DATEADD(DAY,1,DateCol) <= '11-17-2017'
 )

SELECT * FROM CTE
OPTION (maxrecursion 0)


答:
The problem with your code was that you were correctly checking the scrolling distance, but applying the animation to all of your counters.

 (function($) {

   $(function() {

     var $counters = $('.counter'); //contains all elements of counter class

     var $window = $(window);

     $window.on('scroll', function(e) {
       $counters.each(function(i, elem) { //loop through each element
         if ($(this).hasClass('counted')) // check if already animated
           return;
         animateCounter($(this));
       });
     });
   });

   function animateCounter(elem) {
     var winTop = $(window).scrollTop(); // calculate distance from top of window
     var winBottom = winTop + $(window).height();
     var elemTop = $(elem).offset().top; // element distance from top of page
     var elemBottom = elemTop + $(elem).height();

     if ((elemBottom <= winBottom) && (elemTop >= winTop)) {
         var $this = elem;
         jQuery({
           Counter: 0
         }).animate({
           Counter: $this.attr('count')
         }, {
           duration: 3000,
           step: function() {
             $this.text(Math.ceil(this.Counter));
           }
         });
         $this.removeClass('counter').addClass('counted');

     }
   }
 })(jQuery);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#stats {
  font-size: 0;
}

#stats * {
  color: #000;
}

.single-stat {
  width: 45%;
  margin: 2.5%;
  display: inline-block;
  vertical-align: top;
  text-align: center;
}

.stat-container {
  position: relative;
}

.top-line {
  font-size: 30px;
  color: red;
}

.stat {
  font-size: 48px;
  margin: 0;
}

.bottom-line {
  font-size: 16px;
}

.animateBlock {
  display: inline-block;
  position: relative;
}

.animateBlock {
  opacity: 0;
}

.left.animated {
  transform: translateX(-40px);
}

.right.animated {
  transform: translateX(40px);
}

.top.animated {
  transform: translateY(-40px);
}

.bottom.animated {
  transform: translateY(40px);
}

.animated {
  animation: come-in 0.5s ease forwards;
}

@keyframes come-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
    transform: translateY(0);
    transform: translateX(0);
  }
}</code>```

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

title

bottom line

```

https://jsfiddle.net/cndbqeck/

Title: Loop Through jQuery Elements Separately and Animate on Page Scroll

Body:
The problem with your code was that you were correctly checking the scrolling distance, but applying the animation to all of your counters.

 (function($) {

   $(function() {

     var $counters = $('.counter'); //contains all elements of counter class

     var $window = $(window);

     $window.on('scroll', function(e) {
       $counters.each(function(i, elem) { //loop through each element
         if ($(this).hasClass('counted')) // check if already animated
           return;
         animateCounter($(this));
       });
     });
   });

   function animateCounter(elem) {
     var winTop = $(window).scrollTop(); // calculate distance from top of window
     var winBottom = winTop + $(window).height();
     var elemTop = $(elem).offset().top; // element distance from top of page
     var elemBottom = elemTop + $(elem).height();

     if ((elemBottom <= winBottom) && (elemTop >= winTop)) {
         var $this = elem;
         jQuery({
           Counter: 0
         }).animate({
           Counter: $this.attr('count')
         }, {
           duration: 3000,
           step: function() {
             $this.text(Math.ceil(this.Counter));
           }
         });
         $this.removeClass('counter').addClass('counted');

     }
   }
 })(jQuery);

#stats {
  font-size: 0;
}

#stats * {
  color: #000;
}

.single-stat {
  width: 45%;
  margin: 2.5%;
  display: inline-block;
  vertical-align: top;
  text-align: center;
}

.stat-container {
  position: relative;
}

.top-line {
  font-size: 30px;
  color: red;
}

.stat {
  font-size: 48px;
  margin: 0;
}

.bottom-line {
  font-size: 16px;
}

.animateBlock {
  display: inline-block;
  position: relative;
}

.animateBlock {
  opacity: 0;
}

.left.animated {
  transform: translateX(-40px);
}

.right.animated {
  transform: translateX(40px);
}

.top.animated {
  transform: translateY(-40px);
}

.bottom.animated {
  transform: translateY(40px);
}

.animated {
  animation: come-in 0.5s ease forwards;
}

@keyframes come-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
    transform: translateY(0);
    transform: translateX(0);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<div id="stats">
  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="400"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="350"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="12"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="97"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="899"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="4"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="0"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>

  <div class="single-stat">
    <h6 class="top-line">title</h6>
    <div class="stat-container">
      <h6 class="stat"><span class="counter" count="6"></span></h6>
    </div>
    <h6 class="bottom-line">bottom line</h6>
  </div>
</div>

https://jsfiddle.net/cndbqeck/


问:
Lumen unit test post request
I'm having trouble setting up a unit test in which I receive a POST request in the API.
I have a relationship on the table that should link to the user who created the POST request. And in the API I link the correct user like this:
$record->user()->associate($req->user());

It works great, but I can't seem to write a unit test that works.

My unit test looks like this

```<code>$user = factory('App\User')->create();
$item = factory('App\Item')->create();
$response = $this->actingAs($user, 'api')->post('/route', $item);

$this->assertEquals(200, $response->status());
</code>```

What am I doing wrong here?

答:
The problem was that I created the item in the database before making the API call.

$item = factory('App\Item')->create();
should have been $item = factory('App\Item')->make();
and
$response = $this->actingAs($user, 'api')->post('/route', $item);
should have been $response = $this->actingAs($user, 'api')->post('/route', $item->toArray());

Title: Lumen unit test post request

Body:
I'm having trouble setting up a unit test in which I receive a POST request in the API.
I have a relationship on the table that should link to the user who created the POST request. And in the API I link the correct user like this:
$record->user()->associate($req->user());

It works great, but I can't seem to write a unit test that works.

My unit test looks like this

$user = factory('App\User')->create();
$item = factory('App\Item')->create();
$response = $this->actingAs($user, 'api')->post('/route', $item);

$this->assertEquals(200, $response->status());

What am I doing wrong here?


问:
How to manipulate TEXT, NTEXT data from sql server trigger
i hard that TEXT, NTEXT data can not be manipulated from sql server trigger. is it true. if not then please explain how could i manipulate  TEXT, NTEXT data from sql server trigger.
thanks</p>

答:
Don't use text or ntext. Use nvarchar(max) or varchar(max)

Harsh, but they have been deprecated for a reason...

Edit, just remembered. You may be able to use INSTEAD OF triggers


问:
tcpdf on Lumen Class 'PDF' not found
I created a new project with Lumen 5.4.7 and I added the TCPDF library from elibyy/tcpdf-laravel version 5.4.2 (with Lumen support):

```<code>composer require elibyy/tcpdf-laravel "5.4.2"
</code>```

I enabled the Facades and Service Provider in bootstrap/app.php with

```<code>$app->withFacades();
$app->register(Elibyy\TCPDF\ServiceProvider::class);
</code>```

And I created a basic Controller:

```<code><?php

namespace App\Http\Controllers;
use \PDF;

class PdfController extends Controller
{
    /**
     * Create a test PDF file.
     *
     * @return void
     */
    public function createTestPdf()
    {
      PDF::SetTitle('Hello World');
      PDF::AddPage();
      PDF::Write(0, 'Hello World');
      PDF::Output('hello_world.pdf');

      echo "Fatto!";
    }
}
</code>```

with a basic route:

```<code>$app->get('pdf', 'PdfController@createTestPdf');
</code>```

But when I try to access to /pdf I get the following error:

```<code>Fatal error: Class 'PDF' not found in /Users/m/Documents/Projects/lumen-pdf/app/Http/Controllers/PdfController.php on line 15

(1/1) FatalErrorException
Class 'PDF' not found
in PdfController.php (line 15)
at Application->handleShutdown()
in RegistersExceptionHandlers.php (line 54)
at Application->Laravel\Lumen\Concerns\{closure}()
</code>```

Could you help me please?

答:
I solved my problem.

One line was missing into bootstrap/app.php to add a new class_alias for Elibyy\TCPDF\Facades\TCPDF to PDF:

```<code>class_alias('Elibyy\TCPDF\Facades\TCPDF', 'PDF');
</code>```

Thanks!

Title: tcpdf on Lumen Class 'PDF' not found

Body:
I created a new project with Lumen 5.4.7 and I added the TCPDF library from elibyy/tcpdf-laravel version 5.4.2 (with Lumen support):

composer require elibyy/tcpdf-laravel "5.4.2"

I enabled the Facades and Service Provider in bootstrap/app.php with

$app->withFacades();
$app->register(Elibyy\TCPDF\ServiceProvider::class);

And I created a basic Controller:

<?php

namespace App\Http\Controllers;
use \PDF;

class PdfController extends Controller
{
    /**
     * Create a test PDF file.
     *
     * @return void
     */
    public function createTestPdf()
    {
      PDF::SetTitle('Hello World');
      PDF::AddPage();
      PDF::Write(0, 'Hello World');
      PDF::Output('hello_world.pdf');

      echo "Fatto!";
    }
}

with a basic route:

$app->get('pdf', 'PdfController@createTestPdf');

But when I try to access to /pdf I get the following error:

Fatal error: Class 'PDF' not found in /Users/m/Documents/Projects/lumen-pdf/app/Http/Controllers/PdfController.php on line 15

(1/1) FatalErrorException
Class 'PDF' not found
in PdfController.php (line 15)
at Application->handleShutdown()
in RegistersExceptionHandlers.php (line 54)
at Application->Laravel\Lumen\Concerns\{closure}()

Could you help me please?

Body:
I solved my problem.

One line was missing into bootstrap/app.php to add a new class_alias for Elibyy\TCPDF\Facades\TCPDF to PDF:

class_alias('Elibyy\TCPDF\Facades\TCPDF', 'PDF');

Thanks!


问:
Python: Search for DateTime inside a Dictionary that is Less than a certain DateTime
If I have the following data:

```<code>>data1 = ({'StartDT':'2017-01-01 04:54:00'},{'EndDT':'2017-01-01 08:56:00'},{'Code':'1234'})

>data2 = ({'StartDT':'2017-01-01 05:54:00'},{'EndDT':'2017-01-01 07:45:00'},{'Code':'1234'})
</code>```

Question 1 = In Python, what do you think is the best data structure for this?

Question 2 = My goal is to search for data(n) which has a StartDT which is less than a certain DateTime (example: '2017-01-01 06:30:00), and whose EndDT is greater than that certain DateTime.

Thanks for the help!

答:
Q1

I think the best structure here is to use Class. For example,
def class TimePeriod():

```<code>def TimePeriod():
  def __init__(self, start_dt, end_dt, code):
    self.start_dt = start_dt
    self.end_dt = end_dt
    self.code = code
</code>```

Of course, you can use ```dict`` instead of your custom class, but having custom objects here just gives you more clarity.</p>

<p><strong>Q2</strong></p>

<p>Any search in the unsorted array takes <code>O(n)</code> time. So your function might look like this</p>

```start_dt_val = datetime....
end_dt_val = datetime....

def predicate_less_than(element):
  # element is TimePeriod class
  return element.start_dt < start_dt_val and \
          element.end_dt > end_dt_val

def find_element_with_predicate(arr, predicate):
  for el in arr:
    if predicate(el):
      return el

t1 = TimePeriod(....)
...
tn = ...

arr = [t1, ..., tn]

el = find_element_with_predicate(arr, predicate_less_than)
```

el will be None if no element would be found.

Body:
If I have the following data:

>data1 = ({'StartDT':'2017-01-01 04:54:00'},{'EndDT':'2017-01-01 08:56:00'},{'Code':'1234'})

>data2 = ({'StartDT':'2017-01-01 05:54:00'},{'EndDT':'2017-01-01 07:45:00'},{'Code':'1234'})

Question 1 = In Python, what do you think is the best data structure for this?

Question 2 = My goal is to search for data(n) which has a StartDT which is less than a certain DateTime (example: '2017-01-01 06:30:00), and whose EndDT is greater than that certain DateTime.

Thanks for the help!

Body:
Q1

I think the best structure here is to use Class. For example,
def class TimePeriod():

def TimePeriod():
  def __init__(self, start_dt, end_dt, code):
    self.start_dt = start_dt
    self.end_dt = end_dt
    self.code = code

Of course, you can use ```dict`` instead of your custom class, but having custom objects here just gives you more clarity.

Q2

Any search in the unsorted array takes O(n) time. So your function might look like this

start_dt_val = datetime....
end_dt_val = datetime....

def predicate_less_than(element):
  # element is TimePeriod class
  return element.start_dt < start_dt_val and \
          element.end_dt > end_dt_val

def find_element_with_predicate(arr, predicate):
  for el in arr:
    if predicate(el):
      return el

t1 = TimePeriod(....)
...
tn = ...

arr = [t1, ..., tn]

el = find_element_with_predicate(arr, predicate_less_than)

el will be None if no element would be found.


问:
How many intersects are in the table?
```<code>longitude | latitude
----------+---------
1         | 2
2         | 3
4         | 5
2         | 3
5         | 6
1         | 2
</code>```

How can I find how many intersects points are on the table? In this case 1,2 e 2,3

SELECT ST_Intersects

答:
E.g:</p>

```<code>select longitude, latidude, count(0) intersects from
 table_name group by  longitude, latidude having count(0) > 1
</code>```

Title: How many intersects are in the table?

Body:
longitude | latitude
----------+---------
1         | 2
2         | 3
4         | 5
2         | 3
5         | 6
1         | 2

How can I find how many intersects points are on the table? In this case 1,2 e 2,3

SELECT ST_Intersects

Body:
E.g:

select longitude, latidude, count(0) intersects from
 table_name group by  longitude, latidude having count(0) > 1


问:
What does it mean in C : #define ABC(a,b) {#a, a, b}
What does it mean in C :  #define ABC(a,b) {#a, a, b} ?

I understand that ABC is a Macro with parameters (a,b).

But what does it mean {#a, a, b} and especially what does mean "#a" in such case?

答:
This is used to do stringification. From manual.

Sometimes you may want to convert a macro argument into a string
  constant. Parameters are not replaced inside string constants, but you
  can use the # preprocessing operator instead. When a macro parameter
  is used with a leading #, the preprocessor replaces it with the
  literal text of the actual argument, converted to a string constant.
  Unlike normal parameter replacement, the argument is not
  macro-expanded first. This is called stringification.

There is an example in the manual itself which clears the idea.

```<code>#define WARN_IF(EXP) \
do { if (EXP) \
        fprintf (stderr, "Warning: " #EXP "\n"); } \
while (0)
WARN_IF (x == 0);
 (expanded to)==> do { if (x == 0)
           fprintf (stderr, "Warning: " "x == 0" "\n"); } while (0);
</code>```

Body:
This is used to do stringification. From manual.

Sometimes you may want to convert a macro argument into a string
  constant. Parameters are not replaced inside string constants, but you
  can use the # preprocessing operator instead. When a macro parameter
  is used with a leading #, the preprocessor replaces it with the
  literal text of the actual argument, converted to a string constant.
  Unlike normal parameter replacement, the argument is not
  macro-expanded first. This is called stringification.

There is an example in the manual itself which clears the idea.

#define WARN_IF(EXP) \
do { if (EXP) \
        fprintf (stderr, "Warning: " #EXP "\n"); } \
while (0)
WARN_IF (x == 0);
 (expanded to)==> do { if (x == 0)
           fprintf (stderr, "Warning: " "x == 0" "\n"); } while (0);