问:
How to empty an array of objects with some function of the JAVA SDK?
I need some function of the JAVA SDK to empty an array of objects, one way I implemented is to go through a for the array and put all its values to NULL, but if they know of some predefined function that does this work I would be grateful to the Community and especially the one who gave me the answer. regards</p>

答: You may use Arrays.fill(myArray, null) assuming myArray is your array you like to set all values to null.


来源: stackexchange

答: I had this issue and I had to edit the "name" package.json to match the name of the app on heroku. This is why it is recommended that you use the same name of the app when you run "meteor create" when you create the app via Heroku (either command line or in the Heroku Console)</p>

ContentLicense: CC BY-SA 3.0

Title: Heroku errors with Meteor 1.4.1.1

Body:
I was following this guide in order to deploy my app. There are no errors with my push, however when I open the app on my heroku dashboard I am met with an application error page.

This is what the logs show:

2016-09-28T16:05:56.493404+00:00 heroku[web.1]: Starting process with command `npm start`
2016-09-28T16:05:58.915131+00:00 app[web.1]:
2016-09-28T16:05:58.915154+00:00 app[web.1]: > TTR@ start /app
2016-09-28T16:05:58.915155+00:00 app[web.1]: > meteor run
2016-09-28T16:05:58.915155+00:00 app[web.1]:
2016-09-28T16:05:58.920402+00:00 app[web.1]: sh: 1: meteor: not found
2016-09-28T16:05:58.928190+00:00 app[web.1]:
2016-09-28T16:05:58.938161+00:00 app[web.1]: npm ERR! Linux 3.13.0-93-generic
2016-09-28T16:05:58.938683+00:00 app[web.1]: npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
2016-09-28T16:05:58.939001+00:00 app[web.1]: npm ERR! node v5.11.1
2016-09-28T16:05:58.939801+00:00 app[web.1]: npm ERR! npm  v3.8.6
2016-09-28T16:05:58.940297+00:00 app[web.1]: npm ERR! file sh
2016-09-28T16:05:58.940554+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2016-09-28T16:05:58.940702+00:00 app[web.1]: npm ERR! errno ENOENT
2016-09-28T16:05:58.940855+00:00 app[web.1]: npm ERR! syscall spawn
2016-09-28T16:05:58.941055+00:00 app[web.1]: npm ERR! TTR@ start: `meteor run`
2016-09-28T16:05:58.941269+00:00 app[web.1]: npm ERR! spawn ENOENT
2016-09-28T16:05:58.941504+00:00 app[web.1]: npm ERR!
2016-09-28T16:05:58.941722+00:00 app[web.1]: npm ERR! Failed at the TTR@ start script 'meteor run'.
2016-09-28T16:05:58.941941+00:00 app[web.1]: npm ERR! Make sure you have the latest version of node.js and npm installed.
2016-09-28T16:05:58.942090+00:00 app[web.1]: npm ERR! If you do, this is most likely a problem with the TTR package,
2016-09-28T16:05:58.942204+00:00 app[web.1]: npm ERR! not with npm itself.
2016-09-28T16:05:58.942309+00:00 app[web.1]: npm ERR! Tell the author that this fails on your system:
2016-09-28T16:05:58.942414+00:00 app[web.1]: npm ERR!     meteor run
2016-09-28T16:05:58.942519+00:00 app[web.1]: npm ERR! You can get information on how to open an issue for this project with:
2016-09-28T16:05:58.942625+00:00 app[web.1]: npm ERR!     npm bugs TTR
2016-09-28T16:05:58.942728+00:00 app[web.1]: npm ERR! Or if that isn't available, you can get their info via:
2016-09-28T16:05:58.942985+00:00 app[web.1]: npm ERR!     npm owner ls TTR
2016-09-28T16:05:58.943094+00:00 app[web.1]: npm ERR! There is likely additional logging output above.
2016-09-28T16:05:58.946745+00:00 app[web.1]:
2016-09-28T16:05:58.947021+00:00 app[web.1]: npm ERR! Please include the following file with any support request:
2016-09-28T16:05:58.947129+00:00 app[web.1]: npm ERR!     /app/npm-debug.log
2016-09-28T16:05:59.015852+00:00 heroku[web.1]: State changed from starting to crashed
2016-09-28T16:05:59.001860+00:00 heroku[web.1]: Process exited with status 1

I have tried both the https://github.com/AdmitHub/meteor-buildpack-horse.git and https://github.com/jordansissel/heroku-buildpack-meteor.git buildpacks. Any ideas what I could try to get this running?


问:
Change my function async: false to async: true with JQuery and Ajax
I have made a fonction in a javascript class which goes to a php file and return an information from the database.

This function works really well but I try to have the propriety async: true, but my function don't work with this propriety. (I have this warning msg : L’utilisation d’XMLHttpRequest de façon synchrone sur le fil d’exécution principal est obsolète à cause de son impact négatif sur la navigation de l’utilisateur final.)

Do you have any idea, how can I make it work ? A friend told me to try with "Callback" but I don't know how it works.

```<code>    getInfoFromDB: function() {
        var info;
        $.ajax({
            url: "./fonctions/ajax/members.php",
            type: "POST",
            dataType: 'html',
            success: function(data) {
                info = data;
            },
            async: false,

        });
        return info;
    }
</code>```

答:
You have to change your getInfoFromDB() to return something other than info. For example, you might return a Promise instead. If you just return the return value of $.ajax(), you will get a Promise-like thing resolving to data.

```<code>getInfoFromDB: function() {
    return $.ajax({
        url: "./fonctions/ajax/members.php",
        type: "POST",
        dataType: 'html',
    });
}
</code>```

But then you have to update everywhere that calls getInfoFromDB() to support async behavior. For example:

```<code>myObject.getInfoFromDB().then(function (info) {
    doSomethingWith(info);
});
</code>```

From the documentation for jQuery.ajax():

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).

Body:
I have made a fonction in a javascript class which goes to a php file and return an information from the database.

This function works really well but I try to have the propriety async: true, but my function don't work with this propriety. (I have this warning msg : L’utilisation d’XMLHttpRequest de façon synchrone sur le fil d’exécution principal est obsolète à cause de son impact négatif sur la navigation de l’utilisateur final.)

Do you have any idea, how can I make it work ? A friend told me to try with "Callback" but I don't know how it works.

    getInfoFromDB: function() {
        var info;
        $.ajax({
            url: "./fonctions/ajax/members.php",
            type: "POST",
            dataType: 'html',
            success: function(data) {
                info = data;
            },
            async: false,

        });
        return info;
    }

Body:
You have to change your getInfoFromDB() to return something other than info. For example, you might return a Promise instead. If you just return the return value of $.ajax(), you will get a Promise-like thing resolving to data.

getInfoFromDB: function() {
    return $.ajax({
        url: "./fonctions/ajax/members.php",
        type: "POST",
        dataType: 'html',
    });
}

But then you have to update everywhere that calls getInfoFromDB() to support async behavior. For example:

myObject.getInfoFromDB().then(function (info) {
    doSomethingWith(info);
});

From the documentation for jQuery.ajax():

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).


问:
Display all available tags in aem
I am trying to make a component that prints all available tags in crx but I am getting a null pointer exception. I created the following interface

package com.aem.community.core.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public interface ListTags {
 Map listAllTags();
}```
</div>
</div>

 and the implemenataion</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>package com.aem.community.core.services.Impl;

import java.util.Iterator;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Session;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aem.community.core.services.ListTags;
import com.aem.community.core.services.SearchService;
import com.day.cq.tagging.Tag;
import java.util.HashMap;
import java.util.Map;

@Component
@Service
public class ListTagsImpl implements ListTags {
  protected final Logger log = LoggerFactory.getLogger(this.getClass());

  private Session session;

  @Reference
  private ResourceResolver resourceResolver;

  @Override
  public Map listAllTags() {
    try {
      Map<String, String> myHashMap = null;
      Resource tagResource = resourceResolver.getResource("/etc/tags");

      if (tagResource!= null) {
        Iterable<Resource> children = tagResource.getChildren();
        Iterator<Resource> itr = children.iterator();
        while (itr.hasNext()) {
          Resource item = itr.next();
          Tag tag = item.adaptTo(Tag.class);
          if (tag != null) {
            Iterator<Tag> childitr = tag.listAllSubTags();
            while (childitr.hasNext()) {
              Tag childitem = childitr.next();
              myHashMap.put((String)tag.getName, ((String)childitem.getName());
            }
          }
        }
      }
      session.logout();
      return myHashMap;
    }
    catch(Exception e) {
      log.info(e.getMessage());
    }
    return null;
  }
}</code>```

And the code in the crx as follows

<%@include file="/libs/foundation/global.jsp"%>
<%@page import="java.util.*, com.day.cq.tagging.* " %>
<%@page import="com.aem.community.core.services.*" %>
<%@page import="com.aem.community.core.services.Impl.*" %>
<%
try {
  com.aem.community.core.services.ListTags taglist = sling.getService(com.aem.community.core.services.ListTags.class);

  Map tagnames = taglist.listAllTags();
  out.print(tagnames);
} catch(Exception e) {
  out.print(e);
}
%>```

But I am unable to fetch the values returned in the map by the service to the jsp of the component. I am getting a  java.lang.NullPointerException

答:
This is because you're trying to inject ResourceResolver to OSGI Service. You can't do this:

```<code>@Reference
private ResourceResolver resourceResolver;
</code>```

Probably it's throwing NullPointerException where you use the resource resolver. There are couple of ways to get resource resolver in OSGI service but you can refer to http://www.one-inside.com/aem6-1-resourceresolver-access-in-services/ or http://scrupulo.com/posts/blog/view/5-tips-on-the-sling-resource-resolver

ContentLicense: CC BY-SA 4.0

Title: Display all available tags in aem

Body:
I am trying to make a component that prints all available tags in crx but I am getting a null pointer exception. I created the following interface

package com.aem.community.core.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public interface ListTags {
 Map listAllTags();
}

 and the implemenataion

package com.aem.community.core.services.Impl;

import java.util.Iterator;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Session;

import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aem.community.core.services.ListTags;
import com.aem.community.core.services.SearchService;
import com.day.cq.tagging.Tag;
import java.util.HashMap;
import java.util.Map;

@Component
@Service
public class ListTagsImpl implements ListTags {
  protected final Logger log = LoggerFactory.getLogger(this.getClass());

  private Session session;

  @Reference
  private ResourceResolver resourceResolver;

  @Override
  public Map listAllTags() {
    try {
      Map<String, String> myHashMap = null;
      Resource tagResource = resourceResolver.getResource("/etc/tags");

      if (tagResource!= null) {
        Iterable<Resource> children = tagResource.getChildren();
        Iterator<Resource> itr = children.iterator();
        while (itr.hasNext()) {
          Resource item = itr.next();
          Tag tag = item.adaptTo(Tag.class);
          if (tag != null) {
            Iterator<Tag> childitr = tag.listAllSubTags();
            while (childitr.hasNext()) {
              Tag childitem = childitr.next();
              myHashMap.put((String)tag.getName, ((String)childitem.getName());
            }
          }
        }
      }
      session.logout();
      return myHashMap;
    }
    catch(Exception e) {
      log.info(e.getMessage());
    }
    return null;
  }
}

And the code in the crx as follows

<%@include file="/libs/foundation/global.jsp"%>
<%@page import="java.util.*, com.day.cq.tagging.* " %>
<%@page import="com.aem.community.core.services.*" %>
<%@page import="com.aem.community.core.services.Impl.*" %>
<%
try {
  com.aem.community.core.services.ListTags taglist = sling.getService(com.aem.community.core.services.ListTags.class);

  Map tagnames = taglist.listAllTags();
  out.print(tagnames);
} catch(Exception e) {
  out.print(e);
}
%>

But I am unable to fetch the values returned in the map by the service to the jsp of the component. I am getting a  java.lang.NullPointerException

Body:
This is because you're trying to inject ResourceResolver to OSGI Service. You can't do this:

@Reference
private ResourceResolver resourceResolver;

Probably it's throwing NullPointerException where you use the resource resolver. There are couple of ways to get resource resolver in OSGI service but you can refer to http://www.one-inside.com/aem6-1-resourceresolver-access-in-services/ or http://scrupulo.com/posts/blog/view/5-tips-on-the-sling-resource-resolver


问:
Mercurial build on push
I'd like for a build to be done (on the server) each time a push is made to our central Mercurial repository.
Builds are usually kicked off on our build server by running a Visual Build file either manually or via a scheduled task.

What are the ways of achieving this?

Simple, low impact solutions are preferred.

答:
You need to handle repository events with hooks.

So, after commit event you need to run a script that will perform your build accordingly.

ContentLicense: CC BY-SA 2.5

Title: Mercurial build on push


问:
C# Find clients then create socket connection
I have been experimenting with some code to find other computer's on my network running my app. Firstly I broadcast and listen for those broadcasts. After that I am a little lost on the next step. Once Computer A knows the ip address of Computer B because of the broadcast how do I put Computer B in a state to accept socket connections. Then how does Computer A begin that connection?

Also I have tried doing the broadcasting with Multicast and cannot get that to work. If anyone has extra time could they show that as well.

Starting Listener and Sender:

```<code>private static void StartServer()
    {
        Task.Factory.StartNew(async () =>
        {
            await StartListeningAsync();
        });

    }

    private static void StartClient()
    {
        Task.Factory.StartNew(async () =>
        {
            await StartSendingAsync();
        });

    }
</code>```

Those inner methods:

```<code>    private static async Task StartSendingAsync()
    {

        try
        {
            using (UdpClient _broadcaster = new UdpClient())
            {
                var ipHost = Dns.GetHostEntry("");
                var ipAddr = ipHost.AddressList[ipHost.AddressList.Count() - 1];

                IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, PORT);
                var ipAddress = Encoding.ASCII.GetBytes(ipAddr.ToString());
                for (int x = 0; x < 10; x++)
                {
                    _broadcaster.Send(ipAddress, ipAddress.Count(), ip);
                    await Task.Delay(TimeSpan.FromSeconds(6));
                }
            }
        }
        catch (Exception ex)
        {

        }

    }

    private static async Task StartListeningAsync()
    {

        while (true)
        {
            using (UdpClient _listener = new UdpClient(PORT))
            {
                try
                {
                    IPEndPoint ip = new IPEndPoint(IPAddress.Any, PORT);
                    var incoming = await _listener.ReceiveAsync();
                    NewPing(incoming.Buffer, incoming.RemoteEndPoint);
                    await Task.Delay(TimeSpan.FromSeconds(10));
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode == SocketError.TimedOut)
                    {
                        //Time out that's fine
                    }
                }

            }
        }

    }
</code>```

What happens when the listener hears a broadcast:

```<code>private static void NewPing(byte[] incoming, IPEndPoint rem)
    {

        Console.WriteLine($"New ping from {rem.ToString()}, attempting to connect!");

        //What should happen here now that one of the computer's know the other exists?
        //Start some kind of Socket Accepting method?

    }
</code>```

答:
If I understand correctly, you want a machine to send out a UDP broadcast, and then establish a TCP connection between the two?

I'd perform the following steps:

B is listening for UDP broadcasts

A wants a TCP connection with B, so

A starts listening for incoming TCP connections

A sends out a broadcast saying "I'm listening"

B receives the broadcast and attempts to connect to A

I've created two sample console applications, one server, one client:

Server:

```<code>using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, 11220));
        listener.Start();
        listener.AcceptSocketAsync().ContinueWith((t) => HandleClient(t.Result));
        Console.WriteLine($"Listening for TCP connections at port 11220...");

        using (UdpClient broadcaster = new UdpClient(AddressFamily.InterNetwork))
        {
            broadcaster.EnableBroadcast = true;
            Console.WriteLine("Broadcasting...");
            broadcaster.Send(new byte[] { 1, 2, 3 }, 3, new IPEndPoint(IPAddress.Broadcast, 11221));
        }

        while (Console.ReadKey(true).Key != ConsoleKey.Q)
        {
            Console.WriteLine("Press 'Q' to quit");
        }
    }

    static void HandleClient(Socket socket)
    {
        Console.WriteLine($"TCP connection accepted ({socket.RemoteEndPoint})!");
    }
}
</code>```

Client:

```<code>using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        using (UdpClient client = new UdpClient(11221, AddressFamily.InterNetwork))
        {
            Console.WriteLine("Waiting for broadcast...");
            client.EnableBroadcast = true;
            client.ReceiveAsync().ContinueWith((t) => HandleBroadcast(t.Result)).Wait();
        }

        Console.WriteLine("Press any key to continue");
        Console.ReadKey(true);
    }

    static void HandleBroadcast(UdpReceiveResult result)
    {
        Console.WriteLine($"Received broadcast from {result.RemoteEndPoint}, attempting to connect via TCP");
        Socket socket = new Socket(result.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect(new IPEndPoint(result.RemoteEndPoint.Address, 11220));
    }
}
</code>```

First start the client, then the server. The data sent in the broadcast is just dummy data, but you could include some information like the TCP port number the server is listening at.

PS. Remember that this is just a proof of concept.

Body:
I have been experimenting with some code to find other computer's on my network running my app. Firstly I broadcast and listen for those broadcasts. After that I am a little lost on the next step. Once Computer A knows the ip address of Computer B because of the broadcast how do I put Computer B in a state to accept socket connections. Then how does Computer A begin that connection?

Also I have tried doing the broadcasting with Multicast and cannot get that to work. If anyone has extra time could they show that as well.

Starting Listener and Sender:

private static void StartServer()
    {
        Task.Factory.StartNew(async () =>
        {
            await StartListeningAsync();
        });

    }

    private static void StartClient()
    {
        Task.Factory.StartNew(async () =>
        {
            await StartSendingAsync();
        });

    }

Those inner methods:

    private static async Task StartSendingAsync()
    {

        try
        {
            using (UdpClient _broadcaster = new UdpClient())
            {
                var ipHost = Dns.GetHostEntry("");
                var ipAddr = ipHost.AddressList[ipHost.AddressList.Count() - 1];

                IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, PORT);
                var ipAddress = Encoding.ASCII.GetBytes(ipAddr.ToString());
                for (int x = 0; x < 10; x++)
                {
                    _broadcaster.Send(ipAddress, ipAddress.Count(), ip);
                    await Task.Delay(TimeSpan.FromSeconds(6));
                }
            }
        }
        catch (Exception ex)
        {

        }

    }

    private static async Task StartListeningAsync()
    {

        while (true)
        {
            using (UdpClient _listener = new UdpClient(PORT))
            {
                try
                {
                    IPEndPoint ip = new IPEndPoint(IPAddress.Any, PORT);
                    var incoming = await _listener.ReceiveAsync();
                    NewPing(incoming.Buffer, incoming.RemoteEndPoint);
                    await Task.Delay(TimeSpan.FromSeconds(10));
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode == SocketError.TimedOut)
                    {
                        //Time out that's fine
                    }
                }

            }
        }

    }

What happens when the listener hears a broadcast:

private static void NewPing(byte[] incoming, IPEndPoint rem)
    {

        Console.WriteLine($"New ping from {rem.ToString()}, attempting to connect!");

        //What should happen here now that one of the computer's know the other exists?
        //Start some kind of Socket Accepting method?

    }

Body:
If I understand correctly, you want a machine to send out a UDP broadcast, and then establish a TCP connection between the two?

I'd perform the following steps:

B is listening for UDP broadcasts

A wants a TCP connection with B, so

A starts listening for incoming TCP connections

A sends out a broadcast saying "I'm listening"

B receives the broadcast and attempts to connect to A

I've created two sample console applications, one server, one client:

Server:

using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, 11220));
        listener.Start();
        listener.AcceptSocketAsync().ContinueWith((t) => HandleClient(t.Result));
        Console.WriteLine($"Listening for TCP connections at port 11220...");

        using (UdpClient broadcaster = new UdpClient(AddressFamily.InterNetwork))
        {
            broadcaster.EnableBroadcast = true;
            Console.WriteLine("Broadcasting...");
            broadcaster.Send(new byte[] { 1, 2, 3 }, 3, new IPEndPoint(IPAddress.Broadcast, 11221));
        }

        while (Console.ReadKey(true).Key != ConsoleKey.Q)
        {
            Console.WriteLine("Press 'Q' to quit");
        }
    }

    static void HandleClient(Socket socket)
    {
        Console.WriteLine($"TCP connection accepted ({socket.RemoteEndPoint})!");
    }
}

Client:

using System;
using System.Net;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        using (UdpClient client = new UdpClient(11221, AddressFamily.InterNetwork))
        {
            Console.WriteLine("Waiting for broadcast...");
            client.EnableBroadcast = true;
            client.ReceiveAsync().ContinueWith((t) => HandleBroadcast(t.Result)).Wait();
        }

        Console.WriteLine("Press any key to continue");
        Console.ReadKey(true);
    }

    static void HandleBroadcast(UdpReceiveResult result)
    {
        Console.WriteLine($"Received broadcast from {result.RemoteEndPoint}, attempting to connect via TCP");
        Socket socket = new Socket(result.RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect(new IPEndPoint(result.RemoteEndPoint.Address, 11220));
    }
}

First start the client, then the server. The data sent in the broadcast is just dummy data, but you could include some information like the TCP port number the server is listening at.

PS. Remember that this is just a proof of concept.


答:
You can use Arrays.fill(yourArray, null);

(Or)

There is another option, you can simply assign null to the reference

The first option is by far the best to depend on, as the second one can break your code if there are any further references to this object until and unless it gets garbage collected. The garbage collector will clean up any references left by the array.

Title: How to empty an array of objects with some function of the JAVA SDK?

Body: I need some function of the JAVA SDK to empty an array of objects, one way I implemented is to go through a for the array and put all its values to NULL, but if they know of some predefined function that does this work I would be grateful to the Community and especially the one who gave me the answer. regards


问:
Starting Mysql as root
I have started mysql on my test server as a root. I have added

```<code>user=root
</code>```

line in my.cnf
Since I want the test server to upgrade to production server, I will like to comment this line and restart.

Are there any side effects? data loss expected?

答:
To log in to MySQL as the root user, all I needed to do was:</p>

```<code>mysql -u root
</code>```

Title: Starting Mysql as root

Body:
I have started mysql on my test server as a root. I have added

user=root

line in my.cnf
Since I want the test server to upgrade to production server, I will like to comment this line and restart.

Are there any side effects? data loss expected?

Body:
To log in to MySQL as the root user, all I needed to do was:

mysql -u root


问:
MongoDB WiredTiger Storage Engine cacheSizeGB configure option
What's the minimum number of cacheSizeGB can I configure which configure option introduce by MongoDB 3.0.0 in WiredTiger Storage Engine?

Represent the number of cacheSizeGB must be integer? Can I configure it with floating number like 15.5?

I cannot find the detail from MongoDB official document.

答:
I know this is quite old, but as I fall on this question looking for an answer, here it is:

Changed in version 3.4: Values can range from 256MB to 10TB and can be a float. In addition, the default value has also changed.

default:
50% of RAM minus 1 GB, or
256 MB.
Avoid increasing the WiredTiger internal cache size above its default value.

If you run mongod in a container (e.g. lxc, cgroups, Docker, etc.) that does not have access to all of the RAM available in a system, you must set storage.wiredTiger.engineConfig.cacheSizeGB to a value less than the amount of RAM available in the container. The exact amount depends on the other processes running in the container.

source: https://docs.mongodb.com/manual/reference/configuration-options/#storage.wiredTiger.engineConfig.cacheSizeGB


问:
PyGame: Load tile image information just before blitting?
My project is a large map that can be panned around containing "info spots" that can be clicked. For now I use four large images, each spans 5000x5000 pixels (so total map size is 20'000x20'000 pixel). On my AMD Phenom 9950 Quad-Core with 8GB RAM and an NVIDIA GeForce 610 this takes a certain while to load while it's quite fast afterwards when panning the image. I tried tiling it up but there's no visible enhancement in loading speed as the image still has to be loaded completely before it's separated into tiles.

The only way to have some real improvement on speed and memory usage would be, to only load those parts of the map image that are actually shown.
Does PyGame offer any way of doing so? I'm thinking of a "theoretical" tile map which contains the needed x and y values of each tile (I group them a little, less to compute each frame) and a theoretical image information (like: which image and which position therein). Only when a tile comes near the visible part of the screen, its image information is loaded, otherwise it remains a number and string value.

Would this make any sense? Is there any way to achieve this?

答: The only way to accomplish this with Pygame would be to break the images themselves into smaller squares (say 250x250), and then, as the user pans, just get the current topleft x,y coordinates, as well as the screen size, and load any tiles that fit into that screen or around the buffer edge into memory, and clear out any others that are outside that range.  The math will be fairly straightforward unless you add support for rotation and/or zooming.  I would name the tiles after their location as a multiple of the square size (for example the tile at 500, 500 would be named 2-2.png).  This will make it very trivial to generate the tile name that you need to load at each location - take the current x/y coordinates, integer divide by 250, subtract the buffer tile amount, and then loop by your screen width integer divided by 250 plus 1 plus the buffer tile amount for each row.  Do that loop for each column.</p>


问:
iPhone: Using Alerts to Help Debugging
I've been building a rather complex system and there's come the time now where I want more concise debugging. I would like to display the contents of a variable (for this example an NSString called v_string) in a notification window (the kind of window that appear when you receive an SMS text).

Is there an easy way to just call an alert with a variable?

Thanks in Advance,

Dan

答: When you build the string to display in the alert window, simply append your variable's string represenation using stringByAppendingString.

Title: iPhone: Using Alerts to Help Debugging


问:
Appcelerator titanium - send sms
I am creating a mobile (iphone/android) application using appcelerator titanium. Is there any way I can make the app send sms to any given number with appcelerator titanium?</p>

答:
If you wish to just open the SMS app with your own information, you can use the following:

```<code>Ti.Platform.openURL("sms:01234567891&body=hey");
</code>```

Note both the number and body is optional.

Title: Appcelerator titanium - send sms

Body:
If you wish to just open the SMS app with your own information, you can use the following:

Ti.Platform.openURL("sms:01234567891&body=hey");

Note both the number and body is optional.


问:
modify the name of a subset of variables
I would like to modify the name of a subset of variables in a data-frame.

For example

foo <- data.frame(test.y=1:10, test.x=1:10)

How can I select all variables with ending ".y" and rename them for with ending ".z"?

Thanks in advance

答:
We can use sub

```<code>names(foo) <- make.unique(sub("\\.y$", ".x", names(foo)))
</code>```

Body:
We can use sub

names(foo) <- make.unique(sub("\\.y$", ".x", names(foo)))


问:
Finding whether or not group of cells has repeated values
I have a spreadsheet with a list of items by group. I need to find if there is any repeated values in each of these groups. These "repeated" values are not exact. The values are to be considered repeated if one group contains both item "123" and item "123i". Any numeric differences are fine, I am simply looking for the items within each group that may have the same numeric key, regardless of the fact that one may have an i and one may not.

In summary, how do I find repeated values within a specific group for only the first three characters of each cell? I have tried using variations of COUNTIF, and ISNUMBER(SEARCH, yet have not had any success yet.

Thanks.

```<code>B109
B109i
B111
B111i
B154
B156
B330
B350

B109i
B111i
B130i
B140i
B154i
B156i
B330
B350
</code>```

Above is an example of two groups. In the first group, B109 and B109i are repeated as well as B111 and B111i are repeated. The second group contains no repeats. Ideally the output would list the values (B109^B109i) in a cell next to the group that are repeated. The next best output would simply to list "yes" or "no" at the bottom of each group if there are repeated values.

答:
Try this:

```<code>Sub TestInStr()
Dim i As Long

'From row 1 to 10
For i = 1 To 10
    If ActiveWorkbook.Worksheets("Sheet1").Range("A" & i) <> "" Then
        'Referencing column A
        If InStr(ActiveWorkbook.Worksheets("Sheet1").Range("A" & i + 1), ActiveWorkbook.Worksheets("Sheet1").Range("A" & i)) Then
            ActiveWorkbook.Worksheets("Sheet1").Range("B" & i + 1).Value = ActiveWorkbook.Worksheets("Sheet1").Range("A" & i) & "^" & ActiveWorkbook.Worksheets("Sheet1").Range("A" & i + 1)
        End If
    End If
Next i
End Sub
</code>```

Before:

After:

Body:
I have a spreadsheet with a list of items by group. I need to find if there is any repeated values in each of these groups. These "repeated" values are not exact. The values are to be considered repeated if one group contains both item "123" and item "123i". Any numeric differences are fine, I am simply looking for the items within each group that may have the same numeric key, regardless of the fact that one may have an i and one may not.

In summary, how do I find repeated values within a specific group for only the first three characters of each cell? I have tried using variations of COUNTIF, and ISNUMBER(SEARCH, yet have not had any success yet.

Thanks.

B109
B109i
B111
B111i
B154
B156
B330
B350

B109i
B111i
B130i
B140i
B154i
B156i
B330
B350

Above is an example of two groups. In the first group, B109 and B109i are repeated as well as B111 and B111i are repeated. The second group contains no repeats. Ideally the output would list the values (B109^B109i) in a cell next to the group that are repeated. The next best output would simply to list "yes" or "no" at the bottom of each group if there are repeated values.

Body:
Try this:

Sub TestInStr()
Dim i As Long

'From row 1 to 10
For i = 1 To 10
    If ActiveWorkbook.Worksheets("Sheet1").Range("A" & i) <> "" Then
        'Referencing column A
        If InStr(ActiveWorkbook.Worksheets("Sheet1").Range("A" & i + 1), ActiveWorkbook.Worksheets("Sheet1").Range("A" & i)) Then
            ActiveWorkbook.Worksheets("Sheet1").Range("B" & i + 1).Value = ActiveWorkbook.Worksheets("Sheet1").Range("A" & i) & "^" & ActiveWorkbook.Worksheets("Sheet1").Range("A" & i + 1)
        End If
    End If
Next i
End Sub

Before:

After:


问:
javax.sound.sampled.Clip does not play
```<code>    public static void main(String[] args) {
        try{
            File file = new File("audiodata/test.wav");
            AudioInputStream ain = AudioSystem.getAudioInputStream(file);

            AudioFormat format = ain.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);

            Clip clip = (Clip) AudioSystem.getLine(info);
            clip.open(ain);

            clip.start();

        }catch(Exception e){
            e.printStackTrace();
        }
    }
</code>```

I have written this simple main method to play the sound file, but it does not work. There is no Exception thrown. The program ends and I cannot hear anything. I have no idea, what my mistake is. Also creating the Clip by AudioSystem.getClip(); does not change anything.

答:
The correct way to wait for a sound to finish playing is with a concurrency class like CountDownLatch, or with lower-level concurrency operations like wait/notify or Locks:</p>

```<code>Clip clip = (Clip) AudioSystem.getLine(info);

CountDownLatch doneLatch = new CountDownLatch(1);

clip.addLineListener(new LineListener() {
    @Override
    public void update(LineEvent event) {
        if (event.getType().equals(LineEvent.Type.STOP)) {
            doneLatch.countDown();
        }
    }
});

clip.open(ain);
clip.start();

doneLatch.await();
</code>```

Title: javax.sound.sampled.Clip does not play

Body:
    public static void main(String[] args) {
        try{
            File file = new File("audiodata/test.wav");
            AudioInputStream ain = AudioSystem.getAudioInputStream(file);

            AudioFormat format = ain.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, format);

            Clip clip = (Clip) AudioSystem.getLine(info);
            clip.open(ain);

            clip.start();

        }catch(Exception e){
            e.printStackTrace();
        }
    }

I have written this simple main method to play the sound file, but it does not work. There is no Exception thrown. The program ends and I cannot hear anything. I have no idea, what my mistake is. Also creating the Clip by AudioSystem.getClip(); does not change anything.

Body:
The correct way to wait for a sound to finish playing is with a concurrency class like CountDownLatch, or with lower-level concurrency operations like wait/notify or Locks:

Clip clip = (Clip) AudioSystem.getLine(info);

CountDownLatch doneLatch = new CountDownLatch(1);

clip.addLineListener(new LineListener() {
    @Override
    public void update(LineEvent event) {
        if (event.getType().equals(LineEvent.Type.STOP)) {
            doneLatch.countDown();
        }
    }
});

clip.open(ain);
clip.start();

doneLatch.await();


问:
How to assert this promise via jest?
I write a test with jest to test one of my middleware.

```<code>const asyncAll = (req, res, next) => {
    const queue = [
        service.exchangeLongTimeToken(req),
        service.retrieveUserInfo(req),
    ];
    Promise.all(queue).then((values) => {
        res.locals.auth = values[0];
        res.locals.user = values[1];
        next();
    }).catch((err) => {
        next(err)
    });
};
</code>```

The test file is like this:

```<code>const httpMocks = require('node-mocks-http');
const testData = require('../../testdata/data.json');

describe('Test asyncAll', () => {
    let spy1 = {};
    let spy2 = {};
    const mockNext = jest.fn();

    afterEach(() => {
        mockNext.mockReset();
        spy1.mockRestore();
        spy2.mockRestore();
    });

    test('Should call next() with no error when no error with 2 requests', () => {
        spy1 = jest.spyOn(service, 'exchangeLongTimeToken').mockImplementation((url) => {
            return Promise.resolve(testData.fbLongTimeToken);
        });

        spy2 = jest.spyOn(service, 'retrieveUserInfo').mockImplementation((url) => {
            return Promise.resolve(testData.fbUserInfo);
        });

        const request = httpMocks.createRequest();
        const response = httpMocks.createResponse();

        asyncAll(request, response, mockNext);

        expect(spy1).toBeCalled();
        expect(spy2).toBeCalled();
        expect(mockNext).toBeCalled();
        expect(mockNext).toBeCalledWith();
        expect(mockNext.mock.calls.length).toBe(1);
    });
}
</code>```

The error is like this:

Error: expect(jest.fn()).toBeCalled()

Expected mock function to have been called.

```<code>  at Object.<anonymous> (tests/backend/unit/fblogin/asyncAll.test.js:39:26)
</code>```

Which reflects the line:

```<code>expect(mockNext).toBeCalled();
</code>```

Why it doesn't get called?
I read the documents about jest, it says I need to return the promise in order to test the value. But the asyncAll() doesn't return a promise, instead, it consumes a promise, how to deal with this?

答:
You have to notify Jest about the promises you create in the test, have a look at the docs on this topic:</p>

```<code>test('Should call next() with no error when no error with 2 requests', async() => {
        const p1 = Promise.resolve(testData.fbLongTimeToken);
        const p2 = Promise.resolve(testData.fbUserInfo);
        spy1 = jest.spyOn(service, 'exchangeLongTimeToken').mockImplementation((url) => {
            return p1
        });

        spy2 = jest.spyOn(service, 'retrieveUserInfo').mockImplementation((url) => {
            return p2
        });

        const request = httpMocks.createRequest();
        const response = httpMocks.createResponse();

        asyncAll(request, response, mockNext);
        await Promise.all([p1,p2])
        expect(spy1).toBeCalled();
        expect(spy2).toBeCalled();
        expect(mockNext).toBeCalled();
        expect(mockNext).toBeCalledWith();
        expect(mockNext.mock.calls.length).toBe(1);
    });
</code>```

Title: How to assert this promise via jest?

Body:
I write a test with jest to test one of my middleware.

const asyncAll = (req, res, next) => {
    const queue = [
        service.exchangeLongTimeToken(req),
        service.retrieveUserInfo(req),
    ];
    Promise.all(queue).then((values) => {
        res.locals.auth = values[0];
        res.locals.user = values[1];
        next();
    }).catch((err) => {
        next(err)
    });
};

The test file is like this:

const httpMocks = require('node-mocks-http');
const testData = require('../../testdata/data.json');

describe('Test asyncAll', () => {
    let spy1 = {};
    let spy2 = {};
    const mockNext = jest.fn();

    afterEach(() => {
        mockNext.mockReset();
        spy1.mockRestore();
        spy2.mockRestore();
    });

    test('Should call next() with no error when no error with 2 requests', () => {
        spy1 = jest.spyOn(service, 'exchangeLongTimeToken').mockImplementation((url) => {
            return Promise.resolve(testData.fbLongTimeToken);
        });

        spy2 = jest.spyOn(service, 'retrieveUserInfo').mockImplementation((url) => {
            return Promise.resolve(testData.fbUserInfo);
        });

        const request = httpMocks.createRequest();
        const response = httpMocks.createResponse();

        asyncAll(request, response, mockNext);

        expect(spy1).toBeCalled();
        expect(spy2).toBeCalled();
        expect(mockNext).toBeCalled();
        expect(mockNext).toBeCalledWith();
        expect(mockNext.mock.calls.length).toBe(1);
    });
}

The error is like this:

Error: expect(jest.fn()).toBeCalled()

Expected mock function to have been called.

  at Object.<anonymous> (tests/backend/unit/fblogin/asyncAll.test.js:39:26)

Which reflects the line:

expect(mockNext).toBeCalled();

Why it doesn't get called?
I read the documents about jest, it says I need to return the promise in order to test the value. But the asyncAll() doesn't return a promise, instead, it consumes a promise, how to deal with this?

Body:
You have to notify Jest about the promises you create in the test, have a look at the docs on this topic:

test('Should call next() with no error when no error with 2 requests', async() => {
        const p1 = Promise.resolve(testData.fbLongTimeToken);
        const p2 = Promise.resolve(testData.fbUserInfo);
        spy1 = jest.spyOn(service, 'exchangeLongTimeToken').mockImplementation((url) => {
            return p1
        });

        spy2 = jest.spyOn(service, 'retrieveUserInfo').mockImplementation((url) => {
            return p2
        });

        const request = httpMocks.createRequest();
        const response = httpMocks.createResponse();

        asyncAll(request, response, mockNext);
        await Promise.all([p1,p2])
        expect(spy1).toBeCalled();
        expect(spy2).toBeCalled();
        expect(mockNext).toBeCalled();
        expect(mockNext).toBeCalledWith();
        expect(mockNext.mock.calls.length).toBe(1);
    });


问:
Create View - access to success_url from templates
say I have:

```<code>class MyCreate(CreateView):
    template_name = 'template.html'
    success_url = reverse_lazy('blabla')
    form_class = MyForm
</code>```

And suppose in my template I want to add a back button. The back will lead me to the same page as success_url. My solution was to override get_context_data in MyCreate class and add {'back': self.get_success_url()} to the context.

The implications is that I have more CreateViews and I had to create a ContextMixin for this back button. Is there any other easier solution? something like accessing success_url directly in my template?

Thanks

答:
In my case using Django 1.10.3 the way to get it working was like this:

view:

```<code>from django.urls.base import reverse_lazy

class FooCreateView(CreateView):
    success_url = reverse_lazy('name-of-some-view')
</code>```

template:

```<code>{{ view.success_url }}
</code>```

The try of using {{ view.get_success_url }} was leading to:

AttributeError 'NoneType' object has no attribute '__dict__'

Body:
say I have:

class MyCreate(CreateView):
    template_name = 'template.html'
    success_url = reverse_lazy('blabla')
    form_class = MyForm

And suppose in my template I want to add a back button. The back will lead me to the same page as success_url. My solution was to override get_context_data in MyCreate class and add {'back': self.get_success_url()} to the context.

The implications is that I have more CreateViews and I had to create a ContextMixin for this back button. Is there any other easier solution? something like accessing success_url directly in my template?

Thanks

Body:
In my case using Django 1.10.3 the way to get it working was like this:

view:

from django.urls.base import reverse_lazy

class FooCreateView(CreateView):
    success_url = reverse_lazy('name-of-some-view')

template:

{{ view.success_url }}

The try of using {{ view.get_success_url }} was leading to:

AttributeError 'NoneType' object has no attribute '__dict__'


问:
feof() returning true when EOF is not reached
I'm trying to read from a file at a specific offset (simplified version):

```<code>typedef unsigned char u8;
FILE *data_fp = fopen("C:\\some_file.dat", "r");
fseek(data_fp, 0x004d0a68, SEEK_SET); // move filepointer to offset
u8 *data = new u8[0x3F0];
fread(data, 0x3F0, 1, data_fp);
delete[] data;
fclose(data_fp);
</code>```

The problem becomes, that data will not contain 1008 bytes, but 529 (seems random). When it reaches 529 bytes, calls to feof(data_fp) will start returning true.

I've also tried to read in smaller chunks (8 bytes at a time) but it just looks like it's hitting EOF when it's not there yet.

A simple look in a hex editor shows there are plenty of bytes left.

答:
I can't see your link from work, but if your computer claims no more bytes exist, I'd tend to believe it.  Why don't you print the size of the file rather than doing things by hand in a hex editor?

Also, you'd be better off using level 2 I/O  the f-calls are ancient C ugliness, and you're using C++ since you have new.

```<code>int fh =open(filename, O_RDONLY);
struct stat s;
fstat(fh, s);
cout << "size=" << hex << s.st_size << "\n";
</code>```

Now do your seeking and reading using level 2 I/O calls, which are faster anyway, and let's see what the size of the file really is.

Body:
I'm trying to read from a file at a specific offset (simplified version):

typedef unsigned char u8;
FILE *data_fp = fopen("C:\\some_file.dat", "r");
fseek(data_fp, 0x004d0a68, SEEK_SET); // move filepointer to offset
u8 *data = new u8[0x3F0];
fread(data, 0x3F0, 1, data_fp);
delete[] data;
fclose(data_fp);

The problem becomes, that data will not contain 1008 bytes, but 529 (seems random). When it reaches 529 bytes, calls to feof(data_fp) will start returning true.

I've also tried to read in smaller chunks (8 bytes at a time) but it just looks like it's hitting EOF when it's not there yet.

A simple look in a hex editor shows there are plenty of bytes left.

Body:
I can't see your link from work, but if your computer claims no more bytes exist, I'd tend to believe it.  Why don't you print the size of the file rather than doing things by hand in a hex editor?

Also, you'd be better off using level 2 I/O  the f-calls are ancient C ugliness, and you're using C++ since you have new.

int fh =open(filename, O_RDONLY);
struct stat s;
fstat(fh, s);
cout << "size=" << hex << s.st_size << "\n";

Now do your seeking and reading using level 2 I/O calls, which are faster anyway, and let's see what the size of the file really is.


问:
Add click event to dynamic button in xamarin
I want to add buttons from a list, depending of how many items there are in the list. It works perfectly when I do it like this:

The thing is they have no click events, I want each button to have an event that makes the user navigate to the right page depending on which button is clicked.

I'm trying to do it this way but it doesn't work:

Any ideas of the right way to do it if this is totally wrong?

答:
Create the button before adding in to your StackLayout:

```<code>foreach(var item in question.Answers)
{
     var button = new Button();
     button.Text = item.AnswerText;
     button.Clicked += async delegate { await Navigation.PushAsync(item.NextPage); };

     stack.Children.Add(button);
}
</code>```

Body:
Create the button before adding in to your StackLayout:

foreach(var item in question.Answers)
{
     var button = new Button();
     button.Text = item.AnswerText;
     button.Clicked += async delegate { await Navigation.PushAsync(item.NextPage); };

     stack.Children.Add(button);
}


问:
Django returns 403 error on POST request with Fetch
I have a graphql server implemented using graphene-django. I can make queries to it using jquery like this:

```<code>function allIngredients() {
    return 'query{allProducts{edges{node{name}}}}'
  }
  var query = allIngredients();
  $.ajaxSetup({
    data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
  });
  $.post("/graphql", {query: query}, function(response) {
    console.log(response);
  })
</code>```

However, when I try this call with Fetch, I get a 403, because of the CORS issue. I solved the same problem in jQuery by adding ajaxSetup... before the call.

Here's the call using fetch:

```<code>fetch('/graphql', {
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify({
          csrfmiddlewaretoken: '{{ csrf_token }}',
          query:`{allProducts{
            edges{
              node{
                id
                name
                orderPrice
                sellPrice
              }
            }
          }`})
      }
    )
    .then(function(response) {
        if (response.status >= 400) {
            throw new Error("Bad response from server");
        }
        return response.json();
    })
</code>```

I tried adding csrfmiddlewaretoken to the body in the similar way as I did in jQuery example, no luck. I tried adding credentials: 'include' as the docs say, again no luck. I tried with credentials: 'same-origin' and combining this options differently, again the same result. Web is unusually quiet about this, what am I doing wrong?

答:
If you want to make that post request form a different domain (in case when the front of the application is in React or angular and the backend is in Django), make sure the add following in the settings file:

Update the INSTALLED_APPS to use 'coreHeaders' :

INSTALLED_APPS = [

        'corsheaders',

     ]

White list your front end domain by adding following to settings file again:

CORS_ORIGIN_WHITELIST = (
'localhost:8080',
)

Now allow the permission to make this post request for anyone:

Note: Should be used in the cases where you don't need to authenticate the users for posting anything on our server, say, when a new user registers for the first time.

```<code>from rest_framework.permissions import AllowAny

class CreateUser(APIView):
    permission_classes = (AllowAny,)
    def post(self, request, format=None):
        return(Response("hi"))
</code>```

Body:
I have a graphql server implemented using graphene-django. I can make queries to it using jquery like this:

function allIngredients() {
    return 'query{allProducts{edges{node{name}}}}'
  }
  var query = allIngredients();
  $.ajaxSetup({
    data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
  });
  $.post("/graphql", {query: query}, function(response) {
    console.log(response);
  })

However, when I try this call with Fetch, I get a 403, because of the CORS issue. I solved the same problem in jQuery by adding ajaxSetup... before the call.

Here's the call using fetch:

fetch('/graphql', {
        method: "POST",
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify({
          csrfmiddlewaretoken: '{{ csrf_token }}',
          query:`{allProducts{
            edges{
              node{
                id
                name
                orderPrice
                sellPrice
              }
            }
          }`})
      }
    )
    .then(function(response) {
        if (response.status >= 400) {
            throw new Error("Bad response from server");
        }
        return response.json();
    })

I tried adding csrfmiddlewaretoken to the body in the similar way as I did in jQuery example, no luck. I tried adding credentials: 'include' as the docs say, again no luck. I tried with credentials: 'same-origin' and combining this options differently, again the same result. Web is unusually quiet about this, what am I doing wrong?

Body:
If you want to make that post request form a different domain (in case when the front of the application is in React or angular and the backend is in Django), make sure the add following in the settings file:

Update the INSTALLED_APPS to use 'coreHeaders' :

INSTALLED_APPS = [

        'corsheaders',

     ]

White list your front end domain by adding following to settings file again:

CORS_ORIGIN_WHITELIST = (
'localhost:8080',
)

Now allow the permission to make this post request for anyone:

Note: Should be used in the cases where you don't need to authenticate the users for posting anything on our server, say, when a new user registers for the first time.

from rest_framework.permissions import AllowAny

class CreateUser(APIView):
    permission_classes = (AllowAny,)
    def post(self, request, format=None):
        return(Response("hi"))


问:
Kotlin anko common selector not working as in the provided examples
When using anko selector as provided in the examples it is not working

```<code>val countries = listOf("Russia", "USA", "Japan", "Australia")
selector("Where are you from?", countries) { i ->
    toast("So you're living in ${countries[i]}, right?")
}
</code>```

here when defining the lambda function it says expected two types of arguments. (Dialoginterface and int). I am stuck with this. Alos the default kotlin alertdialog is saying the same thing. Can anywone solve this issue or tell me how to build an alert dialog with selection in kotlin?

答:
Seems like it's a mistake in the example.

The selector function source says it expects (DialogInterface, Int) -> Unit, a function with two parameters, so you can fix your code by adding the missing parameter as follows:

```<code>selector("Where are you from?", countries) { dialogInterface, i -> /* ... */ }
</code>```

Or, if you don't use the DialogInterface, just ignore it with an underscore:

```<code>selector("Where are you from?", countries) { _, i -> /* ... */ }
</code>```

Body:
When using anko selector as provided in the examples it is not working

val countries = listOf("Russia", "USA", "Japan", "Australia")
selector("Where are you from?", countries) { i ->
    toast("So you're living in ${countries[i]}, right?")
}

here when defining the lambda function it says expected two types of arguments. (Dialoginterface and int). I am stuck with this. Alos the default kotlin alertdialog is saying the same thing. Can anywone solve this issue or tell me how to build an alert dialog with selection in kotlin?

Body:
Seems like it's a mistake in the example.

The selector function source says it expects (DialogInterface, Int) -> Unit, a function with two parameters, so you can fix your code by adding the missing parameter as follows:

selector("Where are you from?", countries) { dialogInterface, i -> /* ... */ }

Or, if you don't use the DialogInterface, just ignore it with an underscore:

selector("Where are you from?", countries) { _, i -> /* ... */ }


问:
Why doesn't Deletion in Parse-server require to obtain that object beforehand?
I came across a strange behaviour. Even though my unit tests are passing, I don;t quite understand this.

```<code>func testDeleteMoment() {
        // Create a Moment for current user
        let expectCreate = expectation(description: "create moment should succeed")
        Datastore.shared.createMoment(notes: "myNotes", rating: 1, time: Date(), location: "", isPublic: true, completion: {(success, error) in
            XCTAssertTrue(success)
            expectCreate.fulfill()
        })
        waitForExpectations(timeout: 5) { (error) in
            XCTAssertNil(error, "Test timed out. \(String(describing: error?.localizedDescription))")
        }
        let query = PFQuery(className: "Moment")
        var objectId = ""
        do {
            query.whereKey("owner", equalTo:PFUser.current()!)
            let object = try query.getFirstObject()
            objectId = object.objectId!
        } catch {}
        let task = Datastore.shared.deleteMoment(id: objectId)
        task.waitUntilFinished()
        let query2 = PFQuery(className: "Moment")
        query2.whereKey("owner", equalTo:PFUser.current()!)
        let task3 = query2.countObjectsInBackground()
        task3.waitUntilFinished()
        XCTAssertEqual(task3.result, 0)
    }
</code>```

While writing my datastore.deleteMoment(), I noticed that unlike saveEventually(), deleteEventually() doesn't have a completion handler.  Instead, it only comes with a BFTask<NSNumber>. Hence I experimented with the following code and the unit test passes to my surprise.

```<code>func deleteMoment(id: String) -> BFTask<NSNumber> {
        let pfMoment = PFObject(className:"Moment")
        pfMoment.objectId = id
        return pfMoment.deleteEventually()
    }
</code>```

How comes that I don't have to retrieve the object before hand in order to delete it?  Why isn't there then just a method to delete the object via an id, instead of doing it like this?

答:
How comes that I don't have to retrieve the object before hand in order to delete it?

Parse lets you work with "shell objects". Basically, if you know the object id you can attach it to a blank instance of a Parse Object subclass and do some actions on it. You can create a shell, assign a couple values, and call object.save() and it will update just those fields. You can create a blank object, assign an id, then call object.fetch() to obtain it, without having to have gotten the object from a query or pointer on another object.

The reason it works is because in order to perform the database operations, the object id and class name are the only pieces of information required. If you just want to update a couple fields, you don't need to pull all of the rest of the data to do so. And if you want to destroy an object, why would you need all of it's data locally first? You just need to remove the entry in the database with the matching _id.

Why isn't there then just a method to delete the object via an id, instead of doing it like this?

Nobody has built it yet. Parse is open source, and while it's a pretty phenomenal resource today, there's certainly a lot of room for improvement. Feel free to add this feature and create a PR. Though you could easily build your own wrapper by extending the Parse.Object class with this function, that basically does what you already did under the hood.

Body:
I came across a strange behaviour. Even though my unit tests are passing, I don;t quite understand this.

func testDeleteMoment() {
        // Create a Moment for current user
        let expectCreate = expectation(description: "create moment should succeed")
        Datastore.shared.createMoment(notes: "myNotes", rating: 1, time: Date(), location: "", isPublic: true, completion: {(success, error) in
            XCTAssertTrue(success)
            expectCreate.fulfill()
        })
        waitForExpectations(timeout: 5) { (error) in
            XCTAssertNil(error, "Test timed out. \(String(describing: error?.localizedDescription))")
        }
        let query = PFQuery(className: "Moment")
        var objectId = ""
        do {
            query.whereKey("owner", equalTo:PFUser.current()!)
            let object = try query.getFirstObject()
            objectId = object.objectId!
        } catch {}
        let task = Datastore.shared.deleteMoment(id: objectId)
        task.waitUntilFinished()
        let query2 = PFQuery(className: "Moment")
        query2.whereKey("owner", equalTo:PFUser.current()!)
        let task3 = query2.countObjectsInBackground()
        task3.waitUntilFinished()
        XCTAssertEqual(task3.result, 0)
    }

While writing my datastore.deleteMoment(), I noticed that unlike saveEventually(), deleteEventually() doesn't have a completion handler.  Instead, it only comes with a BFTask<NSNumber>. Hence I experimented with the following code and the unit test passes to my surprise.

func deleteMoment(id: String) -> BFTask<NSNumber> {
        let pfMoment = PFObject(className:"Moment")
        pfMoment.objectId = id
        return pfMoment.deleteEventually()
    }

How comes that I don't have to retrieve the object before hand in order to delete it?  Why isn't there then just a method to delete the object via an id, instead of doing it like this?


问:
How can I start my MainActivity after Facebook Login to Android app?
I am trying to integrate Facebook login to my app through Firebase. When the user clicks on "Continue with Facebook" button, I see a blue progress bar and then the text on the button changes to "logout". I intent to open another Activity when the Login succeeds. I have used startActivity() method for that. However, nothing happens. Please help!

Below is the extract of onCreate() method of my Login Activity

```<code>     callbackManager = CallbackManager.Factory.create();
    // Register your callback
    LoginManager.getInstance().registerCallback(callbackManager,
            // If the login attempt is successful, then call onSuccess and pass the LoginResult
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

                    // The HomeScreen.class should load, it is not happening.
                    startActivity(new Intent(getApplicationContext() ,HomeScreen.class));
                    // I get this Log on my screen, which is proof that this loop is executed
                    Log.w("TAG", "User ID: " +
                            loginResult.getAccessToken().getUserId() + "\n" +
                            "Auth Token: " + loginResult.getAccessToken().getToken());
                }
                // If the user cancels the login, then call onCancel
                @Override
                public void onCancel() {
                    Toast.makeText(getApplicationContext(),
                            "Canceled login through Facebook",Toast.LENGTH_LONG).show();
                }
                // If an error occurs, then call onError
                @Override
                public void onError(FacebookException exception) {
                    Toast.makeText(getApplicationContext(),
                            " Facebook Login failed!",Toast.LENGTH_LONG).show();
                    Log.w("FB failed", exception);
                }
            });
</code>```

I am allowing for Google login also through Firebase, for this I have written the onActivityResult method. It is this -

```<code>    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);

        } else {
            // Handle failed signin here
           Toast.makeText(getApplicationContext(),
                   "Google Sign In Failed, Please try with Facebook or Email!", Toast.LENGTH_LONG).show();
        }
    }
    callbackManager.onActivityResult(requestCode, resultCode, data);

}
</code>```

答:
Try to use permissions when you are trying to login with facebook. For example:</p>

```<code>LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile", "email", "user_birthday", "user_photos"));
</code>```

Body:
I am trying to integrate Facebook login to my app through Firebase. When the user clicks on "Continue with Facebook" button, I see a blue progress bar and then the text on the button changes to "logout". I intent to open another Activity when the Login succeeds. I have used startActivity() method for that. However, nothing happens. Please help!

Below is the extract of onCreate() method of my Login Activity

     callbackManager = CallbackManager.Factory.create();
    // Register your callback
    LoginManager.getInstance().registerCallback(callbackManager,
            // If the login attempt is successful, then call onSuccess and pass the LoginResult
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {

                    // The HomeScreen.class should load, it is not happening.
                    startActivity(new Intent(getApplicationContext() ,HomeScreen.class));
                    // I get this Log on my screen, which is proof that this loop is executed
                    Log.w("TAG", "User ID: " +
                            loginResult.getAccessToken().getUserId() + "\n" +
                            "Auth Token: " + loginResult.getAccessToken().getToken());
                }
                // If the user cancels the login, then call onCancel
                @Override
                public void onCancel() {
                    Toast.makeText(getApplicationContext(),
                            "Canceled login through Facebook",Toast.LENGTH_LONG).show();
                }
                // If an error occurs, then call onError
                @Override
                public void onError(FacebookException exception) {
                    Toast.makeText(getApplicationContext(),
                            " Facebook Login failed!",Toast.LENGTH_LONG).show();
                    Log.w("FB failed", exception);
                }
            });

I am allowing for Google login also through Firebase, for this I have written the onActivityResult method. It is this -

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogle(account);

        } else {
            // Handle failed signin here
           Toast.makeText(getApplicationContext(),
                   "Google Sign In Failed, Please try with Facebook or Email!", Toast.LENGTH_LONG).show();
        }
    }
    callbackManager.onActivityResult(requestCode, resultCode, data);

}

Body:
Try to use permissions when you are trying to login with facebook. For example:

LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile", "email", "user_birthday", "user_photos"));


问:
is it possible to know if the url is redirecting
I'm developing in java an application which verifies if one site is online.
I get the http response by:

```<code>URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
</code>```

But when I access the URL it is redirecting and the HTTP response is always 301. I want to get the new URL that the site was redirected. Is it possible?

答: The target of the redirection is in the HTTP Header of the response, look for the "Location" header.</p>

Body:
I'm developing in java an application which verifies if one site is online.
I get the http response by:

URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

But when I access the URL it is redirecting and the HTTP response is always 301. I want to get the new URL that the site was redirected. Is it possible?


问:
Kendo UI data format for yearly data
I'm pretty new to Kendo UI, and am having some trouble understanding how to format some data, and how to get it into a chart.  I have the following data as an example:

```<code> var animals = [
 {
   "Animal": "Dog",
   "2017": 100,
   "2018": 120,
   "2019": 130
 },
 {
   "Animal": "Cat",
   "2017": 50,
   "2018": 40,
   "2019": 10
 },
 {
   "Animal": "Mouse",
   "2017": 10,
   "2018": 20,
   "2019": 80
 },
 {
   "Animal": "Pig",
   "2017": 40,
   "2018": 45,
   "2019": 50
 },
 {
   "Animal": "Cow",
   "2017": 80,
   "2018": 65,
   "2019": 60
 }
]
</code>```

I want to get this data into a line chart, with the years along the x axis, and the corresponding value on the y axis.  The different animals would be represented by individual lines on the line chart.

I've searched the web for a while to find an answer to this, but haven't been able to find anything.  If anyone would be able to help me get started with this issue, or point me to a helpful tutorial, I would really appreciate it.

答:
Check this example, it is almost what you need, but you'll need to adjust input data.
http://dojo.telerik.com/UnuSu/2

Here is how you could adjust the chart in the sample to display your data:

```<code>function createChart() {
    $("#chart").kendoChart({
        title: {
            text: "Your title"
        },
        seriesDefaults: {
          type: "line"
        },
        series: [{
            name: "Dog",
            data: [100, 120, 130]
        }, {
            name: "Cat",
            data: [50, 40, 10]
        }, {
            name: "Mouse",
            data: [10, 20, 80]
        },{
            name: "Pig",
            data: [40, 45, 50]
        },{
            name: "Cow",
            data: [80, 65, 60]
        }],
        categoryAxis: {
            categories: [2017, 2018, 2019]
        },
        tooltip: {
            visible: true,
            format: "{0}%",
            template: "#= series.name #: #= value #"
        }
    });
}

$(document).ready(createChart);
$(document).bind("kendo:skinChange", createChart);
</code>```

For other details regarding data-binding, charts configuration see reference:
http://docs.telerik.com/kendo-ui/controls/charts/overview

http://docs.telerik.com/kendo-ui/controls/charts/overview#see-also

Title: Kendo UI data format for yearly data

Body:
I'm pretty new to Kendo UI, and am having some trouble understanding how to format some data, and how to get it into a chart.  I have the following data as an example:

 var animals = [
 {
   "Animal": "Dog",
   "2017": 100,
   "2018": 120,
   "2019": 130
 },
 {
   "Animal": "Cat",
   "2017": 50,
   "2018": 40,
   "2019": 10
 },
 {
   "Animal": "Mouse",
   "2017": 10,
   "2018": 20,
   "2019": 80
 },
 {
   "Animal": "Pig",
   "2017": 40,
   "2018": 45,
   "2019": 50
 },
 {
   "Animal": "Cow",
   "2017": 80,
   "2018": 65,
   "2019": 60
 }
]

I want to get this data into a line chart, with the years along the x axis, and the corresponding value on the y axis.  The different animals would be represented by individual lines on the line chart.

I've searched the web for a while to find an answer to this, but haven't been able to find anything.  If anyone would be able to help me get started with this issue, or point me to a helpful tutorial, I would really appreciate it.

Body:
Check this example, it is almost what you need, but you'll need to adjust input data.
http://dojo.telerik.com/UnuSu/2

Here is how you could adjust the chart in the sample to display your data:

function createChart() {
    $("#chart").kendoChart({
        title: {
            text: "Your title"
        },
        seriesDefaults: {
          type: "line"
        },
        series: [{
            name: "Dog",
            data: [100, 120, 130]
        }, {
            name: "Cat",
            data: [50, 40, 10]
        }, {
            name: "Mouse",
            data: [10, 20, 80]
        },{
            name: "Pig",
            data: [40, 45, 50]
        },{
            name: "Cow",
            data: [80, 65, 60]
        }],
        categoryAxis: {
            categories: [2017, 2018, 2019]
        },
        tooltip: {
            visible: true,
            format: "{0}%",
            template: "#= series.name #: #= value #"
        }
    });
}

$(document).ready(createChart);
$(document).bind("kendo:skinChange", createChart);

For other details regarding data-binding, charts configuration see reference:
http://docs.telerik.com/kendo-ui/controls/charts/overview

http://docs.telerik.com/kendo-ui/controls/charts/overview#see-also


问:
Visual Studio 2015 Debugging: Can't expand local variables?
I'm using Visual Studio 2015 preview, and I'm trying to debug my project. I was using VS 2012 previously, and depended largely on being able to hover over and expand local variables to look at their values. I'm trying to do this in 2015 now, but when I hover over a variable, the box that shows up only says "(local variable) Classname variablename" (e.g. "(local variable) String title"). There is no expand button, and it doesn't show the value of the variable in the box.

Is there a setting I have to change in order to be able to hover over variables and expand them?

答:
I found that simply changing the combobox with "Release and debug" back to debug allowed me to see the expansion of variables when debugging my code again.

This newest solution worked for VS 2017 on my home PC.

My work PC was able to show this expansion in 2017 after I did the "Build >> Clean Solution option and will even work when the combobox is set to "Release".

Best of luck to anyone else that wants this wonderful debugging help form VS.  I hope that by using one of these methods you're able to get back to "normal".


问:
Can asyncio be used with http.client?
Currently using threads to make multiple "asynchronous" requests to download files. It has been suggested to me to look into using asyncio now that we have upgraded to Python 3+.

We have to use ssl.SSLContext(protocol = ssl.PROTOCOL_TLS) and pass PEM and KEY files.

Can I just work to convert my http.client script to be used with asyncio or do I need to convert the http.client functions to aiohttp functions?

Bonus:

Either way, could somebody outline how to choose between async def  and @asyncio.coroutine?

Supporting Info:

My program performs fairly well considering that our last one which was a sequential query and now works in parallel with around 15 concurrent requests. However another program I am working on sends upwards for 500 requests in parallel; I could use a threading.Semaphore() but I have read that asyncio is great for large volume requests.

First time messing around with it, so...

I'm reading the following (and like 80% of it seems like socket connection for non-blocking sockets, and the only applicable section is "Coordinating Coroutines").

答:
You can use aiohttp; you'll need to translate your http.client code to use aiohttp client API. You can re-use your ssl.SSLContext() object; pass it to a TCPConnector() instance, then create a client from that:

```<code>import aiohttp
import ssl

SSL_CONTEXT = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)
SSL_CONTEXT.load_cert_chain(certfile='foo', keyfile='bar')

async def fetch_url(url):
    conn = aiohttp.TCPConnector(ssl_context=SSL_CONTEXT)
    async with aiohttp.ClientSession(conn=connector) as client:
        async with client.get(url) as response:
            print(resp.status)
            print(await resp.text())
</code>```

Note that you can't share the connector between client sessions; if you want to re-use, reuse the client.

Title: Can asyncio be used with http.client?

Body:
You can use aiohttp; you'll need to translate your http.client code to use aiohttp client API. You can re-use your ssl.SSLContext() object; pass it to a TCPConnector() instance, then create a client from that:

import aiohttp
import ssl

SSL_CONTEXT = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS)
SSL_CONTEXT.load_cert_chain(certfile='foo', keyfile='bar')

async def fetch_url(url):
    conn = aiohttp.TCPConnector(ssl_context=SSL_CONTEXT)
    async with aiohttp.ClientSession(conn=connector) as client:
        async with client.get(url) as response:
            print(resp.status)
            print(await resp.text())

Note that you can't share the connector between client sessions; if you want to re-use, reuse the client.


问:
Does Cordova can work without safari ? (user can't run safari on educational device/ipad)
does apps build with Cordova work on IOS devices which hasn't Safari enable/install (ie iPad as educational device, users cant run Safari)

Best regards,
A newbie.

答:
On IOS (as of IOS8), Cordova uses the WKWebView JavaScript Engine which is based on Safari [source]

According to the Documentation,

A WKWebView object displays interactive web content, such as for an
  in-app browser. You can use the WKWebView class to embed web content
  in your app.

This leads me to believe that the answer is no. You do not need Safari for the app to work because the app is actually rendering the content itself using a built-in library. That is to say, the app has it's own built in "browser".

DISCLAIMER: I have no experience with Cordova and can only spectate based on the available documentation. I recommend you build a very simple Cordova app that displays web content, and test it on the device in question. Or better yet, just use the device, install an app that you know depends on Cordova, and try to run it! :)


问:
How to apply functional programming to remove two nested for i in?
originally I had this awful piece of code with two for i in. To sum up, the idea is to get a list of AMI's ID of some AMIS with a particular tag. To do so, I iterate over list (wrong!) and I get a list of IDS.

```<code>def aws_get_images_exceptions(connection, exceptions):
 list_exceptions = []
    for ex in exceptions:
        images = connection.get_all_images(filters={ "tag-key":"Name","tag-value":ex})
        for ami in images:
            list_exceptions.append(ami.id)
    return list_exceptions
</code>```

Over each iteration I get the complete list of "exceptions" based on the fixed tag Role that I provide to function and then I append the right AMIS.

Ok, I was able to remove the second for i in with the next code:

```<code>def aws_get_images_exceptions(connection, exceptions):
for ex in exceptions:
        images = connection.get_all_images(filters={ "tag-key":"Name","tag-value":ex})
       list_exceptions = list(map(lambda x: x.id, images)) + list_exceptions
return list_exceptions
</code>```

I've checked and I get the same amount of AMIS, same IDS, etc. But I don't get the way to do it in a functional way removing the very first for. As you notice I do a manual call to get_all_images because I iterate over a list of "exceptions" which I give to the function.

Do you know how I can remove this first for i in?

Thanks to all!

答:
you don't need to remove for-loops (especially with lambdas) because it is normal and readable enough,
however it will be better to extract images fetching to separate function using generator

```<code>def get_images(connection, exceptions):
    for ex in exceptions:
        images = connection.get_all_images(filters={"tag-key": "Name", "tag-value": ex})
        # in Python 3.3+ instead of loop use
        # yield from images
        for image in images:
            yield image
</code>```

and after that initial function will be

```<code>def aws_get_images_exceptions(connection, exceptions):
    images = get_images(connection, exceptions)
    return [ami.id for ami in images]
</code>```

and i don't think it can be written fully in functional way since it looks like you are making calls to some sort of database (and this is a side effect)

Further reading

about yield keyword and generators

docs,

PEP-255 where yield keyword was introduced,

epic Stack Overflow thread.

P. S.

get_images can also be re-written without using generator

```<code>def get_images(connection, exceptions):
    images = []
    for ex in exceptions:
        images += connection.get_all_images(filters={"tag-key": "Name", "tag-value": ex})
    return images
</code>```

but generators are truly awesome and you will see how powerful they are.

Body:
originally I had this awful piece of code with two for i in. To sum up, the idea is to get a list of AMI's ID of some AMIS with a particular tag. To do so, I iterate over list (wrong!) and I get a list of IDS.

def aws_get_images_exceptions(connection, exceptions):
 list_exceptions = []
    for ex in exceptions:
        images = connection.get_all_images(filters={ "tag-key":"Name","tag-value":ex})
        for ami in images:
            list_exceptions.append(ami.id)
    return list_exceptions

Over each iteration I get the complete list of "exceptions" based on the fixed tag Role that I provide to function and then I append the right AMIS.

Ok, I was able to remove the second for i in with the next code:

def aws_get_images_exceptions(connection, exceptions):
for ex in exceptions:
        images = connection.get_all_images(filters={ "tag-key":"Name","tag-value":ex})
       list_exceptions = list(map(lambda x: x.id, images)) + list_exceptions
return list_exceptions

I've checked and I get the same amount of AMIS, same IDS, etc. But I don't get the way to do it in a functional way removing the very first for. As you notice I do a manual call to get_all_images because I iterate over a list of "exceptions" which I give to the function.

Do you know how I can remove this first for i in?

Thanks to all!

Body:
you don't need to remove for-loops (especially with lambdas) because it is normal and readable enough,
however it will be better to extract images fetching to separate function using generator

def get_images(connection, exceptions):
    for ex in exceptions:
        images = connection.get_all_images(filters={"tag-key": "Name", "tag-value": ex})
        # in Python 3.3+ instead of loop use
        # yield from images
        for image in images:
            yield image

and after that initial function will be

def aws_get_images_exceptions(connection, exceptions):
    images = get_images(connection, exceptions)
    return [ami.id for ami in images]

and i don't think it can be written fully in functional way since it looks like you are making calls to some sort of database (and this is a side effect)

Further reading

about yield keyword and generators

docs,

PEP-255 where yield keyword was introduced,

epic Stack Overflow thread.

P. S.

get_images can also be re-written without using generator

def get_images(connection, exceptions):
    images = []
    for ex in exceptions:
        images += connection.get_all_images(filters={"tag-key": "Name", "tag-value": ex})
    return images

but generators are truly awesome and you will see how powerful they are.


答:
You can try with this.</p>

```<code>foreach(var item in question.Answers){

    var button = new Button{Text=item.AnswerText};
    button.Clicked += async(s,e)=> await Navigation.PushAsync(item.NextPage);
    stack.Children.Add(button);
}
</code>```

Title: Add click event to dynamic button in xamarin

Body:
I want to add buttons from a list, depending of how many items there are in the list. It works perfectly when I do it like this:

The thing is they have no click events, I want each button to have an event that makes the user navigate to the right page depending on which button is clicked.

I'm trying to do it this way but it doesn't work:

Any ideas of the right way to do it if this is totally wrong?

Body:
You can try with this.

foreach(var item in question.Answers){

    var button = new Button{Text=item.AnswerText};
    button.Clicked += async(s,e)=> await Navigation.PushAsync(item.NextPage);
    stack.Children.Add(button);
}


问:
PouchDB - Unable to start sync gateway
I am trying to the Sync Ionic app with Couchbase and PouchDB for that I have used couchbase sync gateway.

Here is my sync-gateway-config.json

```<code>{
    "log":["CRUD+", "REST+", "Changes+", "Attach+"],
    "databases": {
        "test-database": {
            "server":"http://localhost:8091",
            "sync":`
                function (doc) {
                    channel (doc.channels);
                }
            `,
            "users": {
                "GUEST": {
                    "disabled": false,
                    "admin_channels": ["*"]
                }
            }
        }
    },
    "CORS": {
        "Origin": ["http://localhost:9000"],
        "LoginOrigin": ["http://localhost:9000"],
        "Headers": ["Content-Type"],
        "MaxAge": 17280000
    }
}
</code>```

From terminal I execute the following command to start Sync Gateway :

```<code>./sync_gateway /ionic-pouchdb/sync-gateway-config.json
</code>```

I got the error below:

2016-08-26T12:19:34.178+05:30 WARNING: Error installing Couchbase design doc: no available couch rest URLs -- db.installViews() at database.go:333
2016-08-26T12:19:34.178+05:30 FATAL: Error opening database: no available couch rest URLs -- rest.RunServer() at config.go:480

Appreciate for Help.

Note : i have already set up bucket in couchbase server.

Please find screenshot below:

答:
```<code>{
    "log":["CRUD+", "REST+", "Changes+", "Attach+"],
    "databases": {
        "test-database": {
            "server":"http://localhost:8091",
            "bucket":"your bucket name",
            "sync":`
                function (doc) {
                    channel (doc.channels);
                }
            `,
            "users": {
                "GUEST": {
                    "disabled": false,
                    "admin_channels": ["*"]
                }
            }
        }
    },
    "CORS": {
        "Origin": ["http://localhost:9000"],
        "LoginOrigin": ["http://localhost:9000"],
        "Headers": ["Content-Type"],
        "MaxAge": 17280000
    }
}
</code>```

May be you have to provide bucket name.

Title: PouchDB - Unable to start sync gateway

Body:
I am trying to the Sync Ionic app with Couchbase and PouchDB for that I have used couchbase sync gateway.

Here is my sync-gateway-config.json

{
    "log":["CRUD+", "REST+", "Changes+", "Attach+"],
    "databases": {
        "test-database": {
            "server":"http://localhost:8091",
            "sync":`
                function (doc) {
                    channel (doc.channels);
                }
            `,
            "users": {
                "GUEST": {
                    "disabled": false,
                    "admin_channels": ["*"]
                }
            }
        }
    },
    "CORS": {
        "Origin": ["http://localhost:9000"],
        "LoginOrigin": ["http://localhost:9000"],
        "Headers": ["Content-Type"],
        "MaxAge": 17280000
    }
}

From terminal I execute the following command to start Sync Gateway :

./sync_gateway /ionic-pouchdb/sync-gateway-config.json

I got the error below:

2016-08-26T12:19:34.178+05:30 WARNING: Error installing Couchbase design doc: no available couch rest URLs -- db.installViews() at database.go:333
2016-08-26T12:19:34.178+05:30 FATAL: Error opening database: no available couch rest URLs -- rest.RunServer() at config.go:480

Appreciate for Help.

Note : i have already set up bucket in couchbase server.

Please find screenshot below:

Body:
{
    "log":["CRUD+", "REST+", "Changes+", "Attach+"],
    "databases": {
        "test-database": {
            "server":"http://localhost:8091",
            "bucket":"your bucket name",
            "sync":`
                function (doc) {
                    channel (doc.channels);
                }
            `,
            "users": {
                "GUEST": {
                    "disabled": false,
                    "admin_channels": ["*"]
                }
            }
        }
    },
    "CORS": {
        "Origin": ["http://localhost:9000"],
        "LoginOrigin": ["http://localhost:9000"],
        "Headers": ["Content-Type"],
        "MaxAge": 17280000
    }
}

May be you have to provide bucket name.


问:
Change Variable through Class Operating on DataFrame?
I have a variable initial_value, equal to 1000, that I would like to sum to values on Column B. initial_value and Column B will only be summed when Column C is equal to 1 and not 0. Therefore, the resulting initial value after the Class operation should be 1030 (or 1000 + 10 - 30 + 70 + 10). So far I have tried:</p>

```<code>import pandas as pd
from __future__ import division
import numpy as np

    df = pd.DataFrame({"A":[40,50,60,70,20,30,40,10,10,80,60,40,50],\
 "B":[0,10,10,10,-50,10,10,-30,0,70,-20,-20,10], \
 "C":[0,0,0,1,0,0,0,1,0,1,0,0,1]})

A = df['A']
B = df['B']
C = df['C']

initial_value = 1000.00

class test:
    def __init__(self, A, B, C, initial_value):
        self.A = A
        self.B = B
        self.C = C
        self.initial_value = initial_value

    def test_values(self):
        self.initial_value = self.initial_value + self.B

        return self.initial_value

x = test(A, B, C, initial_value)
x.test_values()

print x
</code>```

答:
You can multiply column B and column C and then sum the result up:

```<code>def test_values(self):
    self.initial_value = self.initial_value + self.B.mul(self.C).sum()
                                            # ^^^^^^^^^^^^^^^^^^^^^^^^
    return self.initial_value

x = test(A, B, C, initial_value)
x.test_values()
# 1060.0
</code>```

Body:
I have a variable initial_value, equal to 1000, that I would like to sum to values on Column B. initial_value and Column B will only be summed when Column C is equal to 1 and not 0. Therefore, the resulting initial value after the Class operation should be 1030 (or 1000 + 10 - 30 + 70 + 10). So far I have tried:

import pandas as pd
from __future__ import division
import numpy as np

    df = pd.DataFrame({"A":[40,50,60,70,20,30,40,10,10,80,60,40,50],\
 "B":[0,10,10,10,-50,10,10,-30,0,70,-20,-20,10], \
 "C":[0,0,0,1,0,0,0,1,0,1,0,0,1]})

A = df['A']
B = df['B']
C = df['C']

initial_value = 1000.00

class test:
    def __init__(self, A, B, C, initial_value):
        self.A = A
        self.B = B
        self.C = C
        self.initial_value = initial_value

    def test_values(self):
        self.initial_value = self.initial_value + self.B

        return self.initial_value

x = test(A, B, C, initial_value)
x.test_values()

print x

Body:
You can multiply column B and column C and then sum the result up:

def test_values(self):
    self.initial_value = self.initial_value + self.B.mul(self.C).sum()
                                            # ^^^^^^^^^^^^^^^^^^^^^^^^
    return self.initial_value

x = test(A, B, C, initial_value)
x.test_values()
# 1060.0


问:
Printing the 3 highest integers from an array without sorting
I am trying to create a program that prints the highest integers from a collection of student's grades array, but the code keeps returning me the same values each time it returns me a value.

So far this is the code:

```<code>class BestGrades {
public static void main(String args[]){
            Scanner sc = new Scanner(System.in);

            int grade[] = new int[6];
            int best[] = new int[3];

            System.out.println("Enter the student's grade...");

            for(int i = 0; i < grade.length; i++){

                    grade[i] = sc.nextInt();

                    for(int a = 0; a < best.length; a++){
                            if(grade[i] > best[a]){
                                    best[a] = grade[i];
                            }
                    }
            }

            for(int i = 0; i < best.length; i++){
                    System.out.println("Best degrees are: "+best[i]);
            }
    }
</code>```

}

As I said, the code will always return me the same highest value 3x.
Pardon me for any mistakes, first time asking here.

答:
I haven't tested it, but something like this should work.  It finds the minimum value in your best array, and if the new value is greater than that, it is one of the best values and replaces that original min value.  Similar to David's answer, but a little simpler.</p>

```<code>// Start best values at negative infinite so that the worst grade
// is still better that what's initially stored
best = {Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE};

for(int i = 0; i < grade.length; i++){
    grade[i] = sc.nextInt();

    // find min value of the max values
    // start by setting first value as the min
    int minIndex = 0;

    for(int a = 1; a < best.length; a++){
        if(best[a] < best[minIndex]) {
            minIndex = a;
        }
    }

    // place new grade into best array if it is better
    // than the worst best value
    if(grade[i] > best[minIndex])
        best[minIndex] = grade[i];
}
</code>```

Body:
I am trying to create a program that prints the highest integers from a collection of student's grades array, but the code keeps returning me the same values each time it returns me a value.

So far this is the code:

class BestGrades {
public static void main(String args[]){
            Scanner sc = new Scanner(System.in);

            int grade[] = new int[6];
            int best[] = new int[3];

            System.out.println("Enter the student's grade...");

            for(int i = 0; i < grade.length; i++){

                    grade[i] = sc.nextInt();

                    for(int a = 0; a < best.length; a++){
                            if(grade[i] > best[a]){
                                    best[a] = grade[i];
                            }
                    }
            }

            for(int i = 0; i < best.length; i++){
                    System.out.println("Best degrees are: "+best[i]);
            }
    }

}

As I said, the code will always return me the same highest value 3x.
Pardon me for any mistakes, first time asking here.

Body:
I haven't tested it, but something like this should work.  It finds the minimum value in your best array, and if the new value is greater than that, it is one of the best values and replaces that original min value.  Similar to David's answer, but a little simpler.

// Start best values at negative infinite so that the worst grade
// is still better that what's initially stored
best = {Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE};

for(int i = 0; i < grade.length; i++){
    grade[i] = sc.nextInt();

    // find min value of the max values
    // start by setting first value as the min
    int minIndex = 0;

    for(int a = 1; a < best.length; a++){
        if(best[a] < best[minIndex]) {
            minIndex = a;
        }
    }

    // place new grade into best array if it is better
    // than the worst best value
    if(grade[i] > best[minIndex])
        best[minIndex] = grade[i];
}


问:
How to loop through an associative array and get the key?
My associative array:

```<code>$arr = array(
   1 => "Value1",
   2 => "Value2",
   10 => "Value10"
);
</code>```

Using the following code, $v is filled with $arr's values

```<code> foreach ($arr as $v){
    echo $v;    // Value1, Value2, Value10
 }
</code>```

How do I get $arr's keys instead?

```<code> foreach (.....){
    echo $k;    // 1, 2, 10
 }
</code>```

答:
```<code><?php
$names = array("firstname"=>"maurice",
               "lastname"=>"muteti",
               "contact"=>"7844433339");

foreach ($names as $name => $value) {
    echo $name." ".$value."</br>";
}

print_r($names);
?>
</code>```

Body:
My associative array:

$arr = array(
   1 => "Value1",
   2 => "Value2",
   10 => "Value10"
);

Using the following code, $v is filled with $arr's values

 foreach ($arr as $v){
    echo $v;    // Value1, Value2, Value10
 }

How do I get $arr's keys instead?

 foreach (.....){
    echo $k;    // 1, 2, 10
 }