问:
Click outside div to close, problems, in jQuery
I have a menu button on my site ("showmenu"), which when clicked opens up the menu div. I also have code that closes the menu if the user clicks outside of it (which I found on here)

```<code>// Code to open / close menu
$(document).ready(function() {
    $('#showmenu').click(function() {
            $('.menu').slideToggle("fast");
    });

// Code for clicking outside menu to close
$(document).mouseup(function (e) {
    var container = $('.menu');
    if (!container.is(e.target) && container.has(e.target).length === 0) {
        container.hide();
        }
    });

});
</code>```

This code gives me problem though. I can open the menu using the "showmenu" button, but I can't click the button again to close it. The only way I can close the menu is by clicking outside of it.

Any suggestions?

答:
This line:

```<code>container.has(e.target).length === 0
</code>```

Is checking if the click target is not a parent of the container element.  However, by checking that the length is equal to zero, this will evaluate to false when you want to check if it is true, i.e., to hide the container when you've clicked on one of it's parents.

Also, you need to change

```<code>e.target
</code>```

to

```<code>$(e.target)
</code>```

to treat it as a jquery object.

Change the line to

```<code>container.has($(e.target)).length > 0
</code>```

and it should work!

Body:
I have a menu button on my site ("showmenu"), which when clicked opens up the menu div. I also have code that closes the menu if the user clicks outside of it (which I found on here)

// Code to open / close menu
$(document).ready(function() {
    $('#showmenu').click(function() {
            $('.menu').slideToggle("fast");
    });

// Code for clicking outside menu to close
$(document).mouseup(function (e) {
    var container = $('.menu');
    if (!container.is(e.target) && container.has(e.target).length === 0) {
        container.hide();
        }
    });

});

This code gives me problem though. I can open the menu using the "showmenu" button, but I can't click the button again to close it. The only way I can close the menu is by clicking outside of it.

Any suggestions?

Body:
This line:

container.has(e.target).length === 0

Is checking if the click target is not a parent of the container element.  However, by checking that the length is equal to zero, this will evaluate to false when you want to check if it is true, i.e., to hide the container when you've clicked on one of it's parents.

Also, you need to change

e.target

to

$(e.target)

to treat it as a jquery object.

Change the line to

container.has($(e.target)).length > 0

and it should work!


来源: stackexchange

问:
What's a Good First Open Source Project?
I'm currently studying computer science and looking for a good way to practice and hone my programming skills.  Contributing to an open source project seems like a natural way to do this to me.  I currently know Java, Python, and some C, but wanted to open this up to any established language.

In particular, I'm looking for a project that's fairly active and has a lot of work for less experienced coders.

A better known project such as Firefox might have the advantage of being more recognizable on a resume, but perhaps one could have a larger impact on a smaller project.  Any thoughts on this?

Thanks in advance =) -Matt

答:
A popular one to start on if you know C is GNOME - www.gnome.org

Another great thing to do is look for projects that need help by checking out the Help Wanted listings at Sourceforge:

http://sourceforge.net/people/

The Python website also has a Volunteer Opportunities page:

http://wiki.python.org/moin/VolunteerOpportunities

A good way to contribute also is to look at the websites and mailing lists of open source software you use on a regular basis and ask if they need help, or just browse through their bug trackers to see what you can help with.  This would probably be more interesting for you as you'll probably be able to make more meaningful contributions quicker with an existing knowledge of the software.

Good luck!

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Wayne Koorts


问:
How do I iterate over a list of URLs to extract JSON data
I have MS SQL Server (2014) and what I need is to pull a bunch of JSON metadata off a web API.  Unfortunately the API is limited to returning only 30 records (and I have 7400 records to pull).  So I was going to just iterate over a bunch of URLs and import the data but I got stuck.

I have imported JSON data into SQL Server in the past adapting this method (Passing filename as variable in OPENROWSET(BULK filename)) and using parseJSON

This method works fine if I have the data local to my machine (e.g. on my C drive) but does not work when I use the URL - I get the following error:

```<code>(1 row(s) affected)
Msg 4861, Level 16, State 1, Line 1
Cannot bulk load because the file "https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow" could not be opened. Operating system error code 123(The filename, directory name, or volume label syntax is incorrect.).
Msg 8115, Level 16, State 2, Line 45
Arithmetic overflow error converting expression to data type nvarchar.
</code>```

How can I fix my code to work with a file on the internet?

```<code>--    SET @JSON_FILE= 'C:\Temp\SO.json'  --  If I save the data on my harddrive the following code works.
    SET @JSON_FILE= 'https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow'

    /* http://www.sqlservercentral.com/Forums/Topic982066-338-1.aspx
    Read the JSON file into the varchar variable.  This is done via a bulk insert using the OPENROWSET() function.   Because this stored proc is to be re-used with different JSON files, ideally you want to pass the JSON file path as a variable.  However, because the OPENROWSET() function won't accept variables as a parameter, the command needs to be built as a string and then passed to the sp_executesql system stored procedure.  The results are then passed back by an output variable.
    */
    -- Setup varchar variable to be used to hold contents of JSON file.
    DECLARE @txt varchar(max)

    -- The command line
    DECLARE @COMMAND NVARCHAR(MAX)
    -- The definition of the parameters used within the command line
    DECLARE @PARAM_DEF NVARCHAR(500)
    -- The parameter used to pass the file name into the command
    DECLARE @FILEVAR NVARCHAR(MAX)
    -- The output variable that holds the results of the OPENROWSET()
    DECLARE @JSON_OUT VARCHAR(MAX)

    SET @FILEVAR = @JSON_FILE
    SET @PARAM_DEF = N'@JSON_FILE NVARCHAR(MAX), @JSON_OUT VARCHAR(MAX) OUTPUT'
    SET @COMMAND = N'SELECT @JSON_OUT = BulkColumn FROM OPENROWSET(BULK ''' +  @JSON_FILE + ''', SINGLE_BLOB) ROW_SET';

    EXEC sp_executesql @COMMAND, @PARAM_DEF, @JSON_FILE = @FILEVAR, @JSON_OUT = @txt OUTPUT;
    --parseJSON function from https://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/
    SELECT * FROM parseJSON(@txt)
</code>```

答:
If you upgrade to SQL Server 2016, you can use openjson, but in 2014, I think you're stuck with either hoping for some magic with openrowset (Though I've yet to see an example of it working remotely) or, other options include SQL-CLR assemblies, which are summed up nicely by marc_s here.

-- Yes, the issue manifests specifically with read-only URL access.

ContentLicense: CC BY-SA 3.0

Body:
I have MS SQL Server (2014) and what I need is to pull a bunch of JSON metadata off a web API.  Unfortunately the API is limited to returning only 30 records (and I have 7400 records to pull).  So I was going to just iterate over a bunch of URLs and import the data but I got stuck.

I have imported JSON data into SQL Server in the past adapting this method (Passing filename as variable in OPENROWSET(BULK filename)) and using parseJSON

This method works fine if I have the data local to my machine (e.g. on my C drive) but does not work when I use the URL - I get the following error:

(1 row(s) affected)
Msg 4861, Level 16, State 1, Line 1
Cannot bulk load because the file "https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow" could not be opened. Operating system error code 123(The filename, directory name, or volume label syntax is incorrect.).
Msg 8115, Level 16, State 2, Line 45
Arithmetic overflow error converting expression to data type nvarchar.

How can I fix my code to work with a file on the internet?

--    SET @JSON_FILE= 'C:\Temp\SO.json'  --  If I save the data on my harddrive the following code works.
    SET @JSON_FILE= 'https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow'

    /* http://www.sqlservercentral.com/Forums/Topic982066-338-1.aspx
    Read the JSON file into the varchar variable.  This is done via a bulk insert using the OPENROWSET() function.   Because this stored proc is to be re-used with different JSON files, ideally you want to pass the JSON file path as a variable.  However, because the OPENROWSET() function won't accept variables as a parameter, the command needs to be built as a string and then passed to the sp_executesql system stored procedure.  The results are then passed back by an output variable.
    */
    -- Setup varchar variable to be used to hold contents of JSON file.
    DECLARE @txt varchar(max)

    -- The command line
    DECLARE @COMMAND NVARCHAR(MAX)
    -- The definition of the parameters used within the command line
    DECLARE @PARAM_DEF NVARCHAR(500)
    -- The parameter used to pass the file name into the command
    DECLARE @FILEVAR NVARCHAR(MAX)
    -- The output variable that holds the results of the OPENROWSET()
    DECLARE @JSON_OUT VARCHAR(MAX)

    SET @FILEVAR = @JSON_FILE
    SET @PARAM_DEF = N'@JSON_FILE NVARCHAR(MAX), @JSON_OUT VARCHAR(MAX) OUTPUT'
    SET @COMMAND = N'SELECT @JSON_OUT = BulkColumn FROM OPENROWSET(BULK ''' +  @JSON_FILE + ''', SINGLE_BLOB) ROW_SET';

    EXEC sp_executesql @COMMAND, @PARAM_DEF, @JSON_FILE = @FILEVAR, @JSON_OUT = @txt OUTPUT;
    --parseJSON function from https://www.simple-talk.com/sql/t-sql-programming/consuming-json-strings-in-sql-server/
    SELECT * FROM parseJSON(@txt)


问:
Python - Using list of strings as class data member. When strings contain variables, variables don't update
Is there a way to change variables within lists within classes after the class instance has been initialized?  (Sorry, sounds more complicated than it is!)

I'm writing a game and storing all of my display text as array elements in instances of a "Text" class. I wrote the following example program to test what I'm trying to do:

```<code>#****************************************#
#INITIALIZE CLASS (to hold text component)
#****************************************#
class Text:
        def __init__(self, array, maxIndex):

            #list of text
            self.list = array

            #number of items in list
            self.max = maxIndex

#set global variable to 7
globalv = 7

#****************************************#
#INITIALIZE VARIABLE-ENHANCED TEXT
#necessary because variables inside class
#data member arrays seem to have a local
#scope, and can't be changed after they
#are initialized
#****************************************#
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

print varLine.list[varLine.max]
#prints 7

#CHANGE VALUE OF globalv:
print "Directly accessing globalv: {}".format(globalv)
#prints 7
print "\nUpdate value of globalv to 9"
globalv = 9
print "Directly accessing globalv: {}".format(globalv)
#prints 9

#Try to change and re-print variable
#doesn't work, despite the fact that "global" has changed outside of the class
print "\nfirst try:"

#call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 7

#Change variable by re-initializing class
print "\nsecond try:"
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

    #call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 9
</code>```

答:
The code is working correctly.  I'm not sure what you're expecting.

You convert globalv to text and store it in an object's text.  When you come back later, that text string is just as you left it.  Are you expecting it to magically change because you changed the value of globalv?  This is somewhat like taking a photograph of yourself, changing clothes, and expecting the photo to change to match your new outfit.   Variables don't work that way.

Perhaps what you need is a two-step approach:

Create an attribute to hold the value, such as self.value

Write a method to display an object's attribute; within that method, acces the current value of self.value, using that in the display string that you build.

Does that help?

Body:
Is there a way to change variables within lists within classes after the class instance has been initialized?  (Sorry, sounds more complicated than it is!)

I'm writing a game and storing all of my display text as array elements in instances of a "Text" class. I wrote the following example program to test what I'm trying to do:

#****************************************#
#INITIALIZE CLASS (to hold text component)
#****************************************#
class Text:
        def __init__(self, array, maxIndex):

            #list of text
            self.list = array

            #number of items in list
            self.max = maxIndex

#set global variable to 7
globalv = 7

#****************************************#
#INITIALIZE VARIABLE-ENHANCED TEXT
#necessary because variables inside class
#data member arrays seem to have a local
#scope, and can't be changed after they
#are initialized
#****************************************#
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

print varLine.list[varLine.max]
#prints 7

#CHANGE VALUE OF globalv:
print "Directly accessing globalv: {}".format(globalv)
#prints 7
print "\nUpdate value of globalv to 9"
globalv = 9
print "Directly accessing globalv: {}".format(globalv)
#prints 9

#Try to change and re-print variable
#doesn't work, despite the fact that "global" has changed outside of the class
print "\nfirst try:"

#call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 7

#Change variable by re-initializing class
print "\nsecond try:"
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

    #call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 9


问:
If the JSF Implementation is a server-wide configuration setting in WAS, why is it set at the application level in Admin Console?
The IBM documentation says, "The JSF implementation is a server-wide configuration setting" (https://www.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.nd.doc/ae/tweb_jsf.html) in version 8.0 and later of WebSphere Application Server, but the instructions say to go here:

Applications > Application Types > WebSphere enterprise applications > application_name > JSP and JSF options

to configure the setting.

On the WAS page itself where you set this parameter, it says:

JSF implementation

On version 8.0 and later nodes, the JSF implementation is a server-wide configuration setting. Thus, if you have multiple applications that require different JSF implementations, you must separate the applications into different application servers or clusters. On version 7.0 nodes, the JSF implementation is an application configuration setting. Read the topic in the information center about configuring JavaServer Faces.

I'm confused. Is it set at the server/node/cluster level or at the application level?

答: You're right - while the JSF implementation is configured via the application configuration options, the implementation selected there is used across the server.</p>


问:
How can I get container name using Contacts Framework (iOS9)
I am using Contacts framework in an app. the thing I'm trying to do is categorize all the contacts by their containers. e.g. facebook contacts will be under the title "Facebook", google contacts under "Google". But when I print the names of the containers sometimes it comes empty or null or something vague, like "Address Book". Is there any way to find out which container belongs to which account(local, facebook, google etc). Thanks in advance.    </p>

```<code>    CNContactStore *contactStore = [[CNContactStore alloc]init];
    NSArray *keysToFetch = @[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactIdentifierKey,CNContactMiddleNameKey,CNContactPhoneNumbersKey];
    NSError *error;
    NSArray *containers = [contactStore containersMatchingPredicate:nil error:&error];
    for (CNContainer *container in containers) {
        NSLog(@"Container: %@",container.name);
    }
</code>```

答:
Initialising the array worked for me:

NSArray *containers   = [[NSArray alloc] init];

Body:
I am using Contacts framework in an app. the thing I'm trying to do is categorize all the contacts by their containers. e.g. facebook contacts will be under the title "Facebook", google contacts under "Google". But when I print the names of the containers sometimes it comes empty or null or something vague, like "Address Book". Is there any way to find out which container belongs to which account(local, facebook, google etc). Thanks in advance.

    CNContactStore *contactStore = [[CNContactStore alloc]init];
    NSArray *keysToFetch = @[CNContactGivenNameKey,CNContactFamilyNameKey,CNContactIdentifierKey,CNContactMiddleNameKey,CNContactPhoneNumbersKey];
    NSError *error;
    NSArray *containers = [contactStore containersMatchingPredicate:nil error:&error];
    for (CNContainer *container in containers) {
        NSLog(@"Container: %@",container.name);
    }


问:
Android renderscript never runs on the gpu
Exactly as the title says.

I have a parallelized image creating/processing algorithm that I'd like to use. This is a kind of perlin noise implementation.

```<code>// Logging is never used here
#pragma version(1)
#pragma rs java_package_name(my.package.name)
#pragma rs_fp_full

float sizeX, sizeY;
float ratio;

static float fbm(float2 coord)
{ ... }

uchar4 RS_KERNEL root(uint32_t x, uint32_t y)
{
float u = x / sizeX * ratio;
float v = y / sizeY;

float2 p = {u, v};

float res = fbm(p) * 2.0f;   // rs.: 8245 ms, fs: 8307 ms; fs 9842 ms on tablet

float4 color = {res, res, res, 1.0f};
//float4 color = {p.x, p.y, 0.0, 1.0};  // rs.: 96 ms

return rsPackColorTo8888(color);
}
</code>```

As a comparison, this exact algorithm runs with at least 30 fps when I implement it on the gpu via fragment shader on a textured quad.

The overhead for running the RenderScript should be max 100 ms which I calculated from making a simple bitmap by returning the x and y normalized coordinates.

Which means that in case it would use the gpu it would surely not become 10 seconds.

The code I am using the RenderScript with:

```<code>// The non-support version gives at least an extra 25% performance boost
import android.renderscript.Allocation;
import android.renderscript.RenderScript;

public class RSNoise {

    private RenderScript renderScript;
    private ScriptC_noise noiseScript;

    private Allocation allOut;

    private Bitmap outBitmap;

    final int sizeX = 1536;
    final int sizeY = 2048;

    public RSNoise(Context context) {
        renderScript = RenderScript.create(context);

        outBitmap = Bitmap.createBitmap(sizeX, sizeY, Bitmap.Config.ARGB_8888);
        allOut = Allocation.createFromBitmap(renderScript, outBitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_GRAPHICS_TEXTURE);

        noiseScript = new ScriptC_noise(renderScript);
    }

    // The render function is benchmarked only
    public Bitmap render() {
        noiseScript.set_sizeX((float) sizeX);
        noiseScript.set_sizeY((float) sizeY);
        noiseScript.set_ratio((float) sizeX / (float) sizeY);

        noiseScript.forEach_root(allOut);

        allOut.copyTo(outBitmap);

        return outBitmap;
    }
}
</code>```

If I change it to FilterScript, from using this help (https://stackoverflow.com/a/14942723/4420543), I get several hundred milliseconds worse in case of support library and about double time worse in case of the non-support one. The precision did not influence the results.

I have also checked every question on stackoverflow, but most of them are outdated and I have also tried it with a nexus 5 (7.1.1 os version) among several other new devices, but the problem still remains.

So, when does RenderScript run on GPU? It would be enough if someone could give me an example on a GPU-running RenderScript.

答:
Can you try to run it with rs_fp_relaxed instead of rs_fp_full?

```<code>#pragma rs_fp_relaxed
</code>```

rs_fp_full will force your script running on CPU, since most GPUs don't support full precision floating point operations.

Body:
Exactly as the title says.

I have a parallelized image creating/processing algorithm that I'd like to use. This is a kind of perlin noise implementation.

// Logging is never used here
#pragma version(1)
#pragma rs java_package_name(my.package.name)
#pragma rs_fp_full

float sizeX, sizeY;
float ratio;

static float fbm(float2 coord)
{ ... }

uchar4 RS_KERNEL root(uint32_t x, uint32_t y)
{
float u = x / sizeX * ratio;
float v = y / sizeY;

float2 p = {u, v};

float res = fbm(p) * 2.0f;   // rs.: 8245 ms, fs: 8307 ms; fs 9842 ms on tablet

float4 color = {res, res, res, 1.0f};
//float4 color = {p.x, p.y, 0.0, 1.0};  // rs.: 96 ms

return rsPackColorTo8888(color);
}

As a comparison, this exact algorithm runs with at least 30 fps when I implement it on the gpu via fragment shader on a textured quad.

The overhead for running the RenderScript should be max 100 ms which I calculated from making a simple bitmap by returning the x and y normalized coordinates.

Which means that in case it would use the gpu it would surely not become 10 seconds.

The code I am using the RenderScript with:

// The non-support version gives at least an extra 25% performance boost
import android.renderscript.Allocation;
import android.renderscript.RenderScript;

public class RSNoise {

    private RenderScript renderScript;
    private ScriptC_noise noiseScript;

    private Allocation allOut;

    private Bitmap outBitmap;

    final int sizeX = 1536;
    final int sizeY = 2048;

    public RSNoise(Context context) {
        renderScript = RenderScript.create(context);

        outBitmap = Bitmap.createBitmap(sizeX, sizeY, Bitmap.Config.ARGB_8888);
        allOut = Allocation.createFromBitmap(renderScript, outBitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_GRAPHICS_TEXTURE);

        noiseScript = new ScriptC_noise(renderScript);
    }

    // The render function is benchmarked only
    public Bitmap render() {
        noiseScript.set_sizeX((float) sizeX);
        noiseScript.set_sizeY((float) sizeY);
        noiseScript.set_ratio((float) sizeX / (float) sizeY);

        noiseScript.forEach_root(allOut);

        allOut.copyTo(outBitmap);

        return outBitmap;
    }
}

If I change it to FilterScript, from using this help (https://stackoverflow.com/a/14942723/4420543), I get several hundred milliseconds worse in case of support library and about double time worse in case of the non-support one. The precision did not influence the results.

I have also checked every question on stackoverflow, but most of them are outdated and I have also tried it with a nexus 5 (7.1.1 os version) among several other new devices, but the problem still remains.

So, when does RenderScript run on GPU? It would be enough if someone could give me an example on a GPU-running RenderScript.

Body:
Can you try to run it with rs_fp_relaxed instead of rs_fp_full?

#pragma rs_fp_relaxed

rs_fp_full will force your script running on CPU, since most GPUs don't support full precision floating point operations.


问:
How to drop by filter input logs in logstash
I want to filter my incoming messages.
I don`t want receive messages, which contains next regexp:

```<code>\*sshd\*|\*k8s_kube\-proxy\*|\*k8s_kube\-proxy\*|worker|\-proxy|k8s_influxdb|\*sshd\*|\*k8s_kube\-proxy\*|\*k8s_kube\-proxy\*|worker|\-proxy|k8s_influxdb|200\ POST|200\ GET|GET\ 200|GET\ /status\ HTTP/1\.1
</code>```

How to write logstash config properly?

答:
There is an if construct that takes a regular expression and a drop filter to get rid of events.

Putting that together:

```<code>filter {
  if ([message] =~ /YOUR_REGEX_HERE/) {
    drop {}
  }
}
</code>```

Body:
I want to filter my incoming messages.
I don`t want receive messages, which contains next regexp:

\*sshd\*|\*k8s_kube\-proxy\*|\*k8s_kube\-proxy\*|worker|\-proxy|k8s_influxdb|\*sshd\*|\*k8s_kube\-proxy\*|\*k8s_kube\-proxy\*|worker|\-proxy|k8s_influxdb|200\ POST|200\ GET|GET\ 200|GET\ /status\ HTTP/1\.1

How to write logstash config properly?

Body:
There is an if construct that takes a regular expression and a drop filter to get rid of events.

Putting that together:

filter {
  if ([message] =~ /YOUR_REGEX_HERE/) {
    drop {}
  }
}


问:
How to create int list from string in mysql?
I have a mysql stored procedure which accepts a string, which is a list of integers. I would like to search in this string using the msql ,,in (),, .

Example:
string parameter = "1,2,3,4,5,6";

select * from table where table.id in (parameter);

答:
I guess you can use find_in_set:

```<code>select *
from table
where find_in_set(id, parameter);
</code>```

Note, however, that the above will restrict optimizer from using index if any on the id column.

If you can, after checking for SQL injection etc. in your application, concatenate it to the SQL like this, that will perform better:

```<code>"select * from table where id in (" + parameter + ")"
</code>```

and use that to execute.

Body:
I guess you can use find_in_set:

select *
from table
where find_in_set(id, parameter);

Note, however, that the above will restrict optimizer from using index if any on the id column.

If you can, after checking for SQL injection etc. in your application, concatenate it to the SQL like this, that will perform better:

"select * from table where id in (" + parameter + ")"

and use that to execute.


问:
Enable PHP's POSIX functions on Rackspace Cloud Sites
I use Rackspace Cloud Sites for web hosting.  I was trying to use a couple of the posix_* functions and noticed that they aren't available.  Using phpinfo() I was able to see that --disable-posix is part of the "Configure Command".  Also, the disable_functions directive has this string leak,posix_getpwuid,posix_getpwnam,posix_getgrid,posix_getgrnam,posix_getgroups.

Is there a way to override this using .htaccess? I didn't see any mention of it in the manual.

答:
Configure commands like --disable-posix are part of the compilation process.

Unless they let you compile and run your own build of PHP (I'm not familiar with RackSpace Cloud), you can't change that.


问:
How to call controller function from javascript
Creating a web app using mvc and codeigniter. In the view, on the click of a button it calls a javascript method. This method should take the source of 3 images as parameters, and pass them to a controller method. The controller method then turns them into a single $record and passes it to a function in the model, which will then insert the record contents into a database.

View button:

```<code><input type="submit" class="btn btn-primary" value="Assemble bot" onclick="insertAssembled()"></input>
</code>```

Javascript function:

```<code>function assemble(var head, var body, var legs) {
    var head = document.getElementById("HeadImage".src);
    var body = document.getElementById("BodyImage".src);
    var legs = document.getElementById("FeetImage".src);
    // call controller function here, passing head body and legs
}
</code>```

Controller method:

```<code>    public function insertAssembled($head, $body, $legs) {
        //Build record and send to saveBot
        $record['id'] = 1;
        $record['head'] = $head;
        $record['body'] = $body;
        $record['legs'] = $legs;
        $this->Robotsdata->saveBot($record);
   }
</code>```

Model method (very rough, help not needed just trying to pass parameters):

```<code>public function saveBot($record) {
    $con = mysql_connect("localhost","root@localhost","");
    mysql_select_db("factory", $con);
    $bot_id = $_POST['id'];
    $bot_head = $_POST['head'];
    $bot_body = $_POST['body'];
    $bot_legs = $_POST['legs'];
    $query = "INSERT INTO `factory`.`assembledbots` ('id', 'head', 'body', 'legs') "
            . "VALUES ('$bot_id', '$bot_head', '$bot_body', '$bot_legs');";
    mysql_query($query);
    mysql_close($con);
}
</code>```

答:
You can try to pass your datas using ajax if you've included the jQuery library :</p>

```<code>$.ajax({
    url: 'Path/To/YourController.php',
    type: 'POST',
    dataType: 'text',
    data: {
        head: head, //You'll get it with $_POST['head']
        body: body, //You'll get it with $_POST['body']
        legs: legs  //You'll get it with $_POST['legs']
    },
})
.done(function(data) {
    // Do what you want in case of success
})
.fail(function(err) {
    //Do what you want incase of error
});
</code>```

Body:
Creating a web app using mvc and codeigniter. In the view, on the click of a button it calls a javascript method. This method should take the source of 3 images as parameters, and pass them to a controller method. The controller method then turns them into a single $record and passes it to a function in the model, which will then insert the record contents into a database.

View button:

<input type="submit" class="btn btn-primary" value="Assemble bot" onclick="insertAssembled()"></input>

Javascript function:

function assemble(var head, var body, var legs) {
    var head = document.getElementById("HeadImage".src);
    var body = document.getElementById("BodyImage".src);
    var legs = document.getElementById("FeetImage".src);
    // call controller function here, passing head body and legs
}

Controller method:

    public function insertAssembled($head, $body, $legs) {
        //Build record and send to saveBot
        $record['id'] = 1;
        $record['head'] = $head;
        $record['body'] = $body;
        $record['legs'] = $legs;
        $this->Robotsdata->saveBot($record);
   }

Model method (very rough, help not needed just trying to pass parameters):

public function saveBot($record) {
    $con = mysql_connect("localhost","root@localhost","");
    mysql_select_db("factory", $con);
    $bot_id = $_POST['id'];
    $bot_head = $_POST['head'];
    $bot_body = $_POST['body'];
    $bot_legs = $_POST['legs'];
    $query = "INSERT INTO `factory`.`assembledbots` ('id', 'head', 'body', 'legs') "
            . "VALUES ('$bot_id', '$bot_head', '$bot_body', '$bot_legs');";
    mysql_query($query);
    mysql_close($con);
}

Body:
You can try to pass your datas using ajax if you've included the jQuery library :

$.ajax({
    url: 'Path/To/YourController.php',
    type: 'POST',
    dataType: 'text',
    data: {
        head: head, //You'll get it with $_POST['head']
        body: body, //You'll get it with $_POST['body']
        legs: legs  //You'll get it with $_POST['legs']
    },
})
.done(function(data) {
    // Do what you want in case of success
})
.fail(function(err) {
    //Do what you want incase of error
});


问:
Delete all elements with same value from doubly circular linked list
I have doubly circular linked list

```<code>struct Element {
    int data;
    Element *next;
    Element *previous;
};

struct List {
    Element *head;
};
</code>```

The task is to delete elements/nodes with the same data. For example, if the list has 1,1,3,4,5,1 and after parsing the function value=1 it should be as following 3,4,5.

```<code>bool removeAllValue(List &l, int value) {
    if(!l.head)
        return false;
    else if(l.head->next == l.head && l.head->data == value){
        l.head = NULL;
        return true;
    }
    Element *p = l.head;
    do{
        if(p->data == value)
            removeElement(l, p);
        p = p->next;
    }while(p!=l.head);
    return true;
</code>```

Above is function which itterates through elements, finds element with given value/data and calls the following function to delete element.

```<code>void removeElement(List &l, Element *element){
    Element *previous = element->previous;
    Element *next = element->next;
    Element *head = l.head;
    if(next == head){ //if element is tail of the list
        l.head->previous = element->previous; // relinking head's previous to new tail
        element->previous->next = head;
    }else if(element == head){ // if element is head of the list
        l.head = next; // relinking head to tail
        l.head->previous = previous; // relinking tail to head
    }else{
        previous->next = next;
        next->previous = previous;
    }
    delete element;

}
</code>```

I have tried different ways but it always gave me errors. The problem is in relinking tail and head, as I think but I can't find the way to fix it.

答:
I think you can streamline it. Handling the removing tail/head/middle situations in removeElement differently is not needed, with the only extra of resetting the list's head when removing the former head. I would rather put determining the next element in list and last item removal detection. Like this:

```<code>Element* removeElement(List &l, Element *element) {
    Element *newnext;
    Element *previous = element->previous;
    Element *next = element->next;
    Element *head = l.head;

    previous->next = next;
    next->previous = previous;
    newnext = next;

    if (element == head) { // if element is head of the list
        l.head = next; // set the head correctly
    }

    if (element == newnext)  // detect if last element in the list was deleted
        l.head = newnext = nullptr;
    else if (newnext == head) // detect if next is at the head again
        newnext = nullptr;

    delete element;
    return newnext;
}
</code>```

Then you do not have to re-iterate from the head each tiem you remove an element and you do not have to handle the single item list as a special case:

```<code>bool removeAllValue(List &l, int value) {
    if (!l.head)
        return false;

    Element *p = l.head;
    do {
        if (p->data == value)
        {
            p = removeElement(l, p);
        }
        else
        {
            p = p->next;
            if (p == l.head)
                p = nullptr;
        }
    } while (p);
    return true;
}
</code>```

Body:
I have doubly circular linked list

struct Element {
    int data;
    Element *next;
    Element *previous;
};

struct List {
    Element *head;
};

The task is to delete elements/nodes with the same data. For example, if the list has 1,1,3,4,5,1 and after parsing the function value=1 it should be as following 3,4,5.

bool removeAllValue(List &l, int value) {
    if(!l.head)
        return false;
    else if(l.head->next == l.head && l.head->data == value){
        l.head = NULL;
        return true;
    }
    Element *p = l.head;
    do{
        if(p->data == value)
            removeElement(l, p);
        p = p->next;
    }while(p!=l.head);
    return true;

Above is function which itterates through elements, finds element with given value/data and calls the following function to delete element.

void removeElement(List &l, Element *element){
    Element *previous = element->previous;
    Element *next = element->next;
    Element *head = l.head;
    if(next == head){ //if element is tail of the list
        l.head->previous = element->previous; // relinking head's previous to new tail
        element->previous->next = head;
    }else if(element == head){ // if element is head of the list
        l.head = next; // relinking head to tail
        l.head->previous = previous; // relinking tail to head
    }else{
        previous->next = next;
        next->previous = previous;
    }
    delete element;

}

I have tried different ways but it always gave me errors. The problem is in relinking tail and head, as I think but I can't find the way to fix it.

Body:
I think you can streamline it. Handling the removing tail/head/middle situations in removeElement differently is not needed, with the only extra of resetting the list's head when removing the former head. I would rather put determining the next element in list and last item removal detection. Like this:

Element* removeElement(List &l, Element *element) {
    Element *newnext;
    Element *previous = element->previous;
    Element *next = element->next;
    Element *head = l.head;

    previous->next = next;
    next->previous = previous;
    newnext = next;

    if (element == head) { // if element is head of the list
        l.head = next; // set the head correctly
    }

    if (element == newnext)  // detect if last element in the list was deleted
        l.head = newnext = nullptr;
    else if (newnext == head) // detect if next is at the head again
        newnext = nullptr;

    delete element;
    return newnext;
}

Then you do not have to re-iterate from the head each tiem you remove an element and you do not have to handle the single item list as a special case:

bool removeAllValue(List &l, int value) {
    if (!l.head)
        return false;

    Element *p = l.head;
    do {
        if (p->data == value)
        {
            p = removeElement(l, p);
        }
        else
        {
            p = p->next;
            if (p == l.head)
                p = nullptr;
        }
    } while (p);
    return true;
}


问:
Getting cumulative proportion in pca
I want to retrive the cumulative proportion of explained variance after a pca in R. summary(pca) returns this result in its last row, but how can I extract this row?

```<code>summary(prcomp(USArrests, scale = TRUE))
Importance of components:
                          PC1    PC2     PC3     PC4
Standard deviation     1.5749 0.9949 0.59713 0.41645
Proportion of Variance 0.6201 0.2474 0.08914 0.04336
Cumulative Proportion  0.6201 0.8675 0.95664 1.00000
</code>```

I tried s <- summary(prcomp(USArrests, scale = TRUE))  and s[3] etc, but it doesn't return the last row.

答:
What about this?

R » s <- as.data.frame( summary(prcomp(USArrests, scale=TRUE))$importance )
 R » s[3, 1:2]
                         PC1    PC2
Cumulative Proportion 0.6201 0.8675
R » message("PC1: ", s[3,1])
PC1: 0.62006

Title: Getting cumulative proportion in pca

Body:
I want to retrive the cumulative proportion of explained variance after a pca in R. summary(pca) returns this result in its last row, but how can I extract this row?

summary(prcomp(USArrests, scale = TRUE))
Importance of components:
                          PC1    PC2     PC3     PC4
Standard deviation     1.5749 0.9949 0.59713 0.41645
Proportion of Variance 0.6201 0.2474 0.08914 0.04336
Cumulative Proportion  0.6201 0.8675 0.95664 1.00000

I tried s <- summary(prcomp(USArrests, scale = TRUE))  and s[3] etc, but it doesn't return the last row.


问:
how to properly make call functions of trigonometry in degrees
In this program I am forced to make a call function for 3 trig functions "sind, cosd, tand", and I have to invoke them to the main program. I am clueless on how to make them work. I also have to have the input values in degrees. I also don't know what the 'while' statement is supposed to equal. Any tips would greatly be appreciated.</p>

```<code>#include <iostream>
#include <cmath>
#include <iomanip>

double sind();

int main(void)
{
double s, c, t;

char select;

    std::cout << "Trigonometric functions in degrees." << std::endl     << std::endl;
    std::cout << "Please select a funcion to be performed : " <<     std::endl << std::endl;

do
{
    std::cout << "S/s: sin, " << "C/c: cos, " << "T/t: tan, " <<     "E/e: Exit" << std::endl;
    std::cout << "please enter your selection. \n";
    std::cin >> select;

    switch (select)
    {
        case 'S' : case 's':
            std::cout << "Please enter a value in degrees : ";
            std::cin >> s;
            std::cout << "sin(" << s << " degrees" << ")" << "=" <<     sind << std::endl;
            break;
        case 'C' : case 'c':
            std::cout << "Please enter a value in degrees : ";
            std::cin >> c;
            std::cout << "cos(cos) : " << "cosd "<< std::endl;
            break;
        case 'T' : case 't':
            std::cout << "Please enter a value in degrees : ";
            std::cin >> t;
            std::cout << "tan(tan) : " << "tand" << std::endl;
            break;
        case 'E' : case 'e' :
            std::cout << "Program has terminated. Goodbye." <<     std::endl;
            break;
        default:
            std::cout << "You have entered an invalid code. Please     try again." << std::endl;
        }
} while (select != 'e');
}
</code>```

答:
As @François Andrieux said, you should really learn how functions work in C++.
Here´s some help with your specific problem:
To calculate the sine of a angle in degrees you have to first convert it to radians:

```<code>double s_rad = s / 180 * PI;
</code>```

You have to define Pi between your include statements and the start of your main function

```<code>#define PI 3.14159265
</code>```

You can then pass this value to the function by writing it in bracket behind the function name:

```<code>double result = sin ( s_rad );
</code>```

Or directly

```<code>double result = sin (s / 180 * PI);
</code>```

Body:
In this program I am forced to make a call function for 3 trig functions "sind, cosd, tand", and I have to invoke them to the main program. I am clueless on how to make them work. I also have to have the input values in degrees. I also don't know what the 'while' statement is supposed to equal. Any tips would greatly be appreciated.

#include <iostream>
#include <cmath>
#include <iomanip>

double sind();

int main(void)
{
double s, c, t;

char select;

    std::cout << "Trigonometric functions in degrees." << std::endl     << std::endl;
    std::cout << "Please select a funcion to be performed : " <<     std::endl << std::endl;

do
{
    std::cout << "S/s: sin, " << "C/c: cos, " << "T/t: tan, " <<     "E/e: Exit" << std::endl;
    std::cout << "please enter your selection. \n";
    std::cin >> select;

    switch (select)
    {
        case 'S' : case 's':
            std::cout << "Please enter a value in degrees : ";
            std::cin >> s;
            std::cout << "sin(" << s << " degrees" << ")" << "=" <<     sind << std::endl;
            break;
        case 'C' : case 'c':
            std::cout << "Please enter a value in degrees : ";
            std::cin >> c;
            std::cout << "cos(cos) : " << "cosd "<< std::endl;
            break;
        case 'T' : case 't':
            std::cout << "Please enter a value in degrees : ";
            std::cin >> t;
            std::cout << "tan(tan) : " << "tand" << std::endl;
            break;
        case 'E' : case 'e' :
            std::cout << "Program has terminated. Goodbye." <<     std::endl;
            break;
        default:
            std::cout << "You have entered an invalid code. Please     try again." << std::endl;
        }
} while (select != 'e');
}

Body:
As @François Andrieux said, you should really learn how functions work in C++.
Here´s some help with your specific problem:
To calculate the sine of a angle in degrees you have to first convert it to radians:

double s_rad = s / 180 * PI;

You have to define Pi between your include statements and the start of your main function

#define PI 3.14159265

You can then pass this value to the function by writing it in bracket behind the function name:

double result = sin ( s_rad );

Or directly

double result = sin (s / 180 * PI);


问:
ftp batch file script
Hoping someone can guide me / help me.

The issue, I have 2 servers one running a Ubuntu which has a website for clients to login and download / view reports. The other is a windows server 2012 R2 which creates / stores the reports. I need to move the files from the windows to the Ubuntu server so clients can view. The data is large currently 7gb and growing at 3 gb a year.

I need a batch file to connect using ftp and then copy the folder to a local folder. However it only needs to copy those files which have modified.

I have only ever written one batch file and I cant seem to find any ftp batch scripts which only copies modifed files.

Your my last resort as I cant seem to find a coder who knows batch script (its a dieing art). I have never used powershell so would not know where to start here.

Any help or advice please let me know.

Thanks
John

答:
This would be a way to do it in PowerShell. It would take files that are older then 31 days and upload them.

```<code>function FTP-Upload {
    [CmdletBinding()]
    param(
    [Parameter(Mandatory=$true)]
    [string]$Source_File,
    [Parameter(Mandatory=$true)]
    [string]$Target_File,
    [Parameter(Mandatory=$true)]
    [string]$Target_Server,
    [Parameter(Mandatory=$true)]
    [string]$Target_Username,
    [Parameter(Mandatory=$true)]
    [string]$Target_Password
    )

    $FTP = [System.Net.FTPWebRequest]::Create("ftp://$Target_Server/$Target_File")
    $FTP = [System.Net.FTPWebRequest]$FTP
    $FTP.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
    $FTP.Credentials = New-Object System.Net.NetworkCredential($Target_Username,$Target_Password)
    $FTP.UseBinary = $true
    $FTP.UsePassive = $true
    # read in the file to upload as a byte array
    $content = [System.IO.File]::ReadAllBytes($Source_File)
    $FTP.ContentLength = $content.Length
    # get the request stream, and write the bytes into it
    $rs = $FTP.GetRequestStream()
    $rs.Write($content, 0, $content.Length)
    # be sure to clean up after ourselves
    $rs.Close()
    $rs.Dispose()
}

$Upload_Server = "server.network.tld"
$Upload_Location = "/data/"
$Upload_Username = "ftpuser"
$Upload_Password = "ftppassword"

$Files_To_Upload = Get-ChildItem E:\Path\To\Files -Recurse | Where-Object {($_.CreationTime -le (Get-Date).AddDays(-31)) -and (!$_.PSIsContainer)}

Foreach ($File in $Files_To_Upload) {
    FTP-Upload -Source_File $File.FullName -Target_File ($Upload_Location + $File.Name) -Target_Server $Upload_Server -Target_Username $Upload_Username -Target_Password $Upload_Password
}
</code>```

Title: ftp batch file script

Body:
This would be a way to do it in PowerShell. It would take files that are older then 31 days and upload them.

function FTP-Upload {
    [CmdletBinding()]
    param(
    [Parameter(Mandatory=$true)]
    [string]$Source_File,
    [Parameter(Mandatory=$true)]
    [string]$Target_File,
    [Parameter(Mandatory=$true)]
    [string]$Target_Server,
    [Parameter(Mandatory=$true)]
    [string]$Target_Username,
    [Parameter(Mandatory=$true)]
    [string]$Target_Password
    )

    $FTP = [System.Net.FTPWebRequest]::Create("ftp://$Target_Server/$Target_File")
    $FTP = [System.Net.FTPWebRequest]$FTP
    $FTP.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
    $FTP.Credentials = New-Object System.Net.NetworkCredential($Target_Username,$Target_Password)
    $FTP.UseBinary = $true
    $FTP.UsePassive = $true
    # read in the file to upload as a byte array
    $content = [System.IO.File]::ReadAllBytes($Source_File)
    $FTP.ContentLength = $content.Length
    # get the request stream, and write the bytes into it
    $rs = $FTP.GetRequestStream()
    $rs.Write($content, 0, $content.Length)
    # be sure to clean up after ourselves
    $rs.Close()
    $rs.Dispose()
}

$Upload_Server = "server.network.tld"
$Upload_Location = "/data/"
$Upload_Username = "ftpuser"
$Upload_Password = "ftppassword"

$Files_To_Upload = Get-ChildItem E:\Path\To\Files -Recurse | Where-Object {($_.CreationTime -le (Get-Date).AddDays(-31)) -and (!$_.PSIsContainer)}

Foreach ($File in $Files_To_Upload) {
    FTP-Upload -Source_File $File.FullName -Target_File ($Upload_Location + $File.Name) -Target_Server $Upload_Server -Target_Username $Upload_Username -Target_Password $Upload_Password
}


问:
Heroku Database save issue
I'm trying store the number of views for every workshop.

My Workshops controller is:

```<code>  def show
    @workshop.view = @workshop.view + 1
    @workshop.save
  end
</code>```

The view column in the schema:

```<code>  create_table "workshops", force: :cascade do |t|
    t.integer  "view",         default: 0
  end
</code>```

So I expect every time show action works, this will increase the view number by 1. It's working in local, bur on heroku view column is every time 0. I could not find the reason.

Maybe it's because of PG database. Any idea is welcome.

答:
The issue is gone after I did : heroku restart.
It's probably because I did not restart the heroku server after rake db:migrate. </p>

Title: Heroku Database save issue

Body:
I'm trying store the number of views for every workshop.

My Workshops controller is:

  def show
    @workshop.view = @workshop.view + 1
    @workshop.save
  end

The view column in the schema:

  create_table "workshops", force: :cascade do |t|
    t.integer  "view",         default: 0
  end

So I expect every time show action works, this will increase the view number by 1. It's working in local, bur on heroku view column is every time 0. I could not find the reason.

Maybe it's because of PG database. Any idea is welcome.


问:
Lowercase query parameters in URL using iOS universal links
I was just about to link an app to a domain using universal links (or also refered to as associated domains; available since iOS 9). So far everything worked out and while testing with Safari I was able to open my app correctly, also parse path and query parameters of any URL.

But when I opened an URL that worked before with Safari from inside iMessage or Mail it failed.
I found out that when opening an app that way each query parameter gets reformatted to lowercase characters, which is invalid towards my data handling.
For example

```<code>https://www.example.com/path?paramNameOne=ValueOne&paramNameTwo=ValueTwo
</code>```

is altered to

```<code>https://www.example.com/path?paramnameone=valueone&paramnametwo=valuetwo
</code>```

So question is if there is a detail with this technology that I'm not aware of or - in case of a known bug - a propper strategy to cope with this issue.

答: Universal linking does not accept font formatting. Remove styling from your link and check</p>

Body:
I was just about to link an app to a domain using universal links (or also refered to as associated domains; available since iOS 9). So far everything worked out and while testing with Safari I was able to open my app correctly, also parse path and query parameters of any URL.

But when I opened an URL that worked before with Safari from inside iMessage or Mail it failed.
I found out that when opening an app that way each query parameter gets reformatted to lowercase characters, which is invalid towards my data handling.
For example

https://www.example.com/path?paramNameOne=ValueOne&paramNameTwo=ValueTwo

is altered to

https://www.example.com/path?paramnameone=valueone&paramnametwo=valuetwo

So question is if there is a detail with this technology that I'm not aware of or - in case of a known bug - a propper strategy to cope with this issue.


问:
500 Error from Microsoft Graph on create child in approot
Got the following error while trying to create a folder in my app folder:

```<code>com.microsoft.graph.http.GraphFatalServiceException: [This is an unexpected error from Graph, please report this at https://github.com/microsoftgraph/msgraph-sdk-android/issues]
        POST https://graph.microsoft.com/v1.0/me/drive/special/approot/children
        SdkVersion : graph-android-v1.2.0
        Authorization : bearer <REDACTED>
{"folder":{},"name":"gg"}

        500 : Internal Server Error
        Duration : 234.839
        Cache-Control : private
X-Android-Sent-Millis : 1489454003081
        Content-Type : application/json
        x-ms-ags-diagnostic : {"ServerInfo":{"DataCenter":"West US","Slice":"SliceA","ScaleUnit":"000","Host":"AGSFE_IN_2","ADSiteName":"WST"}}
        request-id : f25e8a83-5b40-493f-811c-7c9731790c9f
        Date : Tue, 14 Mar 2017 01:13:37 GMT
        Transfer-Encoding : chunked
        X-Android-Response-Source : NETWORK 500
        client-request-id : f25e8a83-5b40-493f-811c-7c9731790c9f
        X-Android-Received-Millis : 1489454003395
        {
        "error": {
        "code": "generalException",
        "message": "An unspecified error has occurred.",
        "innerError": {
        "request-id": "f25e8a83-5b40-493f-811c-7c9731790c9f",
        "date": "2017-03-14T01:13:37"
        }
        }
        }
</code>```

Per the app folder and the create folder documentation, the request should work given I have "Files.ReadWrite.AppFolder" permission scope.

I created the folder manually and tried to access its metadata and it failed similarly:

```<code>com.microsoft.graph.http.GraphFatalServiceException: [This is an unexpected error from Graph, please report this at https://github.com/microsoftgraph/msgraph-sdk-android/issues]
        GET https://graph.microsoft.com/v1.0/me/drive/special/approot:/gg:
        SdkVersion : graph-android-v1.2.0
        Authorization : bearer <REDACTED>

500 : Internal Server Error
        Duration : 199.4711
        Cache-Control : private
X-Android-Sent-Millis : 1489455064558
        Content-Type : application/json
        x-ms-ags-diagnostic : {"ServerInfo":{"DataCenter":"West US","Slice":"SliceA","ScaleUnit":"003","Host":"AGSFE_IN_3","ADSiteName":"WST"}}
        request-id : 660fad6b-491a-4876-98c5-9160c9f8715c
        Date : Tue, 14 Mar 2017 01:31:19 GMT
        Transfer-Encoding : chunked
        X-Android-Response-Source : NETWORK 500
        client-request-id : 660fad6b-491a-4876-98c5-9160c9f8715c
        X-Android-Received-Millis : 1489455064872
        {
        "error": {
        "code": "generalException",
        "message": "An unspecified error has occurred.",
        "innerError": {
        "request-id": "660fad6b-491a-4876-98c5-9160c9f8715c",
        "date": "2017-03-14T01:31:20"
        }
        }
        }
</code>```

There's a file in the app directory that I can access via its item id and get its contents without issues.

Any ideas what might be causing this issue?

答:
The Files.ReadWrite.AppFolder scope is not currently supported, but cannot be removed for a list of reasons which are unfortunate. You will need to use a different scope, such as Files.ReadWrite, to gain access and create this folder.

Note that even after changing permissions requested by your app, you will need to reconsent to the app to get the new permissions. You can force that to happen to adding &prompt=consent to the end of the OAuth2 Authorization URL or you can remove consent to your app first from

Body:
Got the following error while trying to create a folder in my app folder:

com.microsoft.graph.http.GraphFatalServiceException: [This is an unexpected error from Graph, please report this at https://github.com/microsoftgraph/msgraph-sdk-android/issues]
        POST https://graph.microsoft.com/v1.0/me/drive/special/approot/children
        SdkVersion : graph-android-v1.2.0
        Authorization : bearer <REDACTED>
{"folder":{},"name":"gg"}

        500 : Internal Server Error
        Duration : 234.839
        Cache-Control : private
X-Android-Sent-Millis : 1489454003081
        Content-Type : application/json
        x-ms-ags-diagnostic : {"ServerInfo":{"DataCenter":"West US","Slice":"SliceA","ScaleUnit":"000","Host":"AGSFE_IN_2","ADSiteName":"WST"}}
        request-id : f25e8a83-5b40-493f-811c-7c9731790c9f
        Date : Tue, 14 Mar 2017 01:13:37 GMT
        Transfer-Encoding : chunked
        X-Android-Response-Source : NETWORK 500
        client-request-id : f25e8a83-5b40-493f-811c-7c9731790c9f
        X-Android-Received-Millis : 1489454003395
        {
        "error": {
        "code": "generalException",
        "message": "An unspecified error has occurred.",
        "innerError": {
        "request-id": "f25e8a83-5b40-493f-811c-7c9731790c9f",
        "date": "2017-03-14T01:13:37"
        }
        }
        }

Per the app folder and the create folder documentation, the request should work given I have "Files.ReadWrite.AppFolder" permission scope.

I created the folder manually and tried to access its metadata and it failed similarly:

com.microsoft.graph.http.GraphFatalServiceException: [This is an unexpected error from Graph, please report this at https://github.com/microsoftgraph/msgraph-sdk-android/issues]
        GET https://graph.microsoft.com/v1.0/me/drive/special/approot:/gg:
        SdkVersion : graph-android-v1.2.0
        Authorization : bearer <REDACTED>

500 : Internal Server Error
        Duration : 199.4711
        Cache-Control : private
X-Android-Sent-Millis : 1489455064558
        Content-Type : application/json
        x-ms-ags-diagnostic : {"ServerInfo":{"DataCenter":"West US","Slice":"SliceA","ScaleUnit":"003","Host":"AGSFE_IN_3","ADSiteName":"WST"}}
        request-id : 660fad6b-491a-4876-98c5-9160c9f8715c
        Date : Tue, 14 Mar 2017 01:31:19 GMT
        Transfer-Encoding : chunked
        X-Android-Response-Source : NETWORK 500
        client-request-id : 660fad6b-491a-4876-98c5-9160c9f8715c
        X-Android-Received-Millis : 1489455064872
        {
        "error": {
        "code": "generalException",
        "message": "An unspecified error has occurred.",
        "innerError": {
        "request-id": "660fad6b-491a-4876-98c5-9160c9f8715c",
        "date": "2017-03-14T01:31:20"
        }
        }
        }

There's a file in the app directory that I can access via its item id and get its contents without issues.

Any ideas what might be causing this issue?


问:
Ace Editor PHP Syntax for using brackets
Trying to figure out how to handle syntax errors when using PHP mode in Ace Editor for shortcodes (to include shortcodes inside of PHP code).  Highlighting already looks/works fine, the problem is with PHP syntax errors showing when shortcodes are used.

A simple shortcode would be [shortcode] while an extended one would have open and closing brackets [shortcode]something[/shortcode]

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

    // Example single shortcode (without closing shortcode), [...] will be replaced with "Some value entered by user"
    $site_name = [get_input type="text" desc="Please enter the site name"];

    // Example with open closing shortcodes
    [check_question question="Do you want to add period to the end of the title?"]
        $title .= '.';
    [/check_question]

    $title = ucfirst( $title );

    return $title;
}
</code>```

Can someone help me to figure out how to extend the PHP mode/worker, or what needs to be done to prevent PHP syntax errors from showing in the editor when shortcodes are included?  Everything works great besides the simple PHP syntax errors on shortcodes.

https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode

Fiddle example:
http://jsfiddle.net/tripflex/crm4ywu0/

The regex that is used on backend to replace [...] with custom values/code is:

```<code>\[(\[?)(get_input|check_question)(?![\w-])([^\]\/]*(?:\/(?!\])[^\]\/]*)*?)(?:(\/)\]|\](?:([^\[]*+(?:\[(?!\/\2\])[^\[]*+)*+)\[\/\2\])?)(\]?)
</code>```

Which is direct from WordPress shortcode handling:
https://github.com/WordPress/WordPress/blob/master/wp-includes/js/shortcode.js#L105
https://github.com/WordPress/WordPress/blob/master/wp-includes/shortcodes.php#L264

答:
You could use that regex to replace brackets at https://github.com/ajaxorg/ace/blob/v1.2.6/lib/ace/mode/php_worker.js#L51, before passing the value to the php lexer.
Unfortunately there is no way to do that without directly modifying the source code in worker-php.js file.</p>

Body:
Trying to figure out how to handle syntax errors when using PHP mode in Ace Editor for shortcodes (to include shortcodes inside of PHP code).  Highlighting already looks/works fine, the problem is with PHP syntax errors showing when shortcodes are used.

A simple shortcode would be [shortcode] while an extended one would have open and closing brackets [shortcode]something[/shortcode]

function foo( $title ) {

    // Example single shortcode (without closing shortcode), [...] will be replaced with "Some value entered by user"
    $site_name = [get_input type="text" desc="Please enter the site name"];

    // Example with open closing shortcodes
    [check_question question="Do you want to add period to the end of the title?"]
        $title .= '.';
    [/check_question]

    $title = ucfirst( $title );

    return $title;
}

Can someone help me to figure out how to extend the PHP mode/worker, or what needs to be done to prevent PHP syntax errors from showing in the editor when shortcodes are included?  Everything works great besides the simple PHP syntax errors on shortcodes.

https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode

Fiddle example:
http://jsfiddle.net/tripflex/crm4ywu0/

The regex that is used on backend to replace [...] with custom values/code is:

\[(\[?)(get_input|check_question)(?![\w-])([^\]\/]*(?:\/(?!\])[^\]\/]*)*?)(?:(\/)\]|\](?:([^\[]*+(?:\[(?!\/\2\])[^\[]*+)*+)\[\/\2\])?)(\]?)

Which is direct from WordPress shortcode handling:
https://github.com/WordPress/WordPress/blob/master/wp-includes/js/shortcode.js#L105
https://github.com/WordPress/WordPress/blob/master/wp-includes/shortcodes.php#L264


问:
Ansible: SSH Error: unix_listener: too long for Unix domain socket
This is a known issue and I found a solution but it's not working for me.

First I had:

```<code>fatal: [openshift-node-compute-e50xx] => SSH Error: ControlPath too long
It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue.
</code>```

So I created a ~/.ansible.cfg. The content of it:

```<code>[ssh_connection]
control_path=%(directory)s/%%h‐%%r
</code>```

But after rerunning my ansible I stil have an error about 'too long'.

```<code>fatal: [openshift-master-32axx] => SSH Error: unix_listener: "/Users/myuser/.ansible/cp/ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com-centos.AAZFTHkT5xXXXXXX" too long for Unix domain socket
    while connecting to 52.xx.xx.xx:22
It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue.
</code>```

Why is it still too long?

答:
Customizing the control_path solves the problem for me. Here is how to do it without spamming the home directory.

The control_path defaults to (documentation):

```<code>control_path=%(directory)s/ansible-ssh-%%h-%%p-%%r
</code>```

Edit ansible config.

```<code>vim ~/.ansible.cfg
</code>```

Here are sample file contents with new control_path value:

```<code>[defaults]
inventory=/etc/ansible/hosts

[ssh_connection]
control_path=%(directory)s/%%h-%%r
control_path_dir=~/.ansible/cp
</code>```

Body:
This is a known issue and I found a solution but it's not working for me.

First I had:

fatal: [openshift-node-compute-e50xx] => SSH Error: ControlPath too long
It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue.

So I created a ~/.ansible.cfg. The content of it:

[ssh_connection]
control_path=%(directory)s/%%h‐%%r

But after rerunning my ansible I stil have an error about 'too long'.

fatal: [openshift-master-32axx] => SSH Error: unix_listener: "/Users/myuser/.ansible/cp/ec2-xx-xx-xx-xx.eu-central-1.compute.amazonaws.com-centos.AAZFTHkT5xXXXXXX" too long for Unix domain socket
    while connecting to 52.xx.xx.xx:22
It is sometimes useful to re-run the command using -vvvv, which prints SSH debug output to help diagnose the issue.

Why is it still too long?

Body:
Customizing the control_path solves the problem for me. Here is how to do it without spamming the home directory.

The control_path defaults to (documentation):

control_path=%(directory)s/ansible-ssh-%%h-%%p-%%r

Edit ansible config.

vim ~/.ansible.cfg

Here are sample file contents with new control_path value:

[defaults]
inventory=/etc/ansible/hosts

[ssh_connection]
control_path=%(directory)s/%%h-%%r
control_path_dir=~/.ansible/cp


问:
Guard condition provokes compiler error that talks about closure
Consider this code:

```<code>class Foo {
    var a: Int
    var b: Int

    init(a: Int, b: String?) throws {
        self.a = a

        guard self.a > 0 else {
            throw "Too little a!"
        }
        self.b = self.a
    }
}

extension String: Error {}
</code>```

Pretty non-sensical, but the point is that it compiles fine.
Now replace the guard with:

```<code>guard b == nil || self.a > 0 else {
</code>```

Not we get a compiler error!

Error: 'self' captured by a closure before all members were initialized

I for one don't see a closure anywhere. Is the compiler translating guard conditions into closures if they are compound expressions, thus introducing the error (which would be correct if there was a closure)?

Bug or feature?

This is with Swift 3.0.2.

答:
The problem, as explained by Martin in this Q&A, is that the || operator is implemented with an @autoclosure second parameter, in order to allow for short-circuit evaluation (the right hand expression need only be evaluated if the left hand expression evaluates to false).

Therefore in the expression

```<code>b == nil || self.a > 0
</code>```

self.a > 0 is implicitly wrapped in a () -> Bool closure. This is problematic, because it requires the capture of self, so that a can be accessed upon applying the closure.

However, in an initialiser, Swift tightly restricts what you can do with self before it has been fully initialised. One of these restrictions is the inability to be captured by a closure – which is why you get a compiler error.

Although really, there's nothing wrong with the closure { self.a > 0 } capturing self before it's fully initialised, because all the closure is doing is accessing a on it, which has already been initialised. Therefore, this is really just an edge case (for which there's an open bug report), which I hope will be smoothed out in a future version of the language.

Until then, one solution as shown by Martin in this Q&A, is to use a temporary local variable to create a copy of the value of self.a, avoiding the capturing of self in the closure:

```<code>class Foo {
    var a: Int
    var b: Int

    init(a: Int, b: String?) throws {

        // some computation meaning that a != self.a
        self.a = a * 42

        // temporary local variable to be captured by the @autoclosure.
        let _a = self.a
        guard b == nil || _a > 0 else {
            throw "Too little a!"
        }

        self.b = self.a
    }
}

extension String: Error {}
</code>```

Obviously, this assumes that self.a != a, otherwise you can just refer to a instead of self.a in the guard condition.

Body:
Consider this code:

class Foo {
    var a: Int
    var b: Int

    init(a: Int, b: String?) throws {
        self.a = a

        guard self.a > 0 else {
            throw "Too little a!"
        }
        self.b = self.a
    }
}

extension String: Error {}

Pretty non-sensical, but the point is that it compiles fine.
Now replace the guard with:

guard b == nil || self.a > 0 else {

Not we get a compiler error!

Error: 'self' captured by a closure before all members were initialized

I for one don't see a closure anywhere. Is the compiler translating guard conditions into closures if they are compound expressions, thus introducing the error (which would be correct if there was a closure)?

Bug or feature?

This is with Swift 3.0.2.

Body:
The problem, as explained by Martin in this Q&A, is that the || operator is implemented with an @autoclosure second parameter, in order to allow for short-circuit evaluation (the right hand expression need only be evaluated if the left hand expression evaluates to false).

Therefore in the expression

b == nil || self.a > 0

self.a > 0 is implicitly wrapped in a () -> Bool closure. This is problematic, because it requires the capture of self, so that a can be accessed upon applying the closure.

However, in an initialiser, Swift tightly restricts what you can do with self before it has been fully initialised. One of these restrictions is the inability to be captured by a closure – which is why you get a compiler error.

Although really, there's nothing wrong with the closure { self.a > 0 } capturing self before it's fully initialised, because all the closure is doing is accessing a on it, which has already been initialised. Therefore, this is really just an edge case (for which there's an open bug report), which I hope will be smoothed out in a future version of the language.

Until then, one solution as shown by Martin in this Q&A, is to use a temporary local variable to create a copy of the value of self.a, avoiding the capturing of self in the closure:

class Foo {
    var a: Int
    var b: Int

    init(a: Int, b: String?) throws {

        // some computation meaning that a != self.a
        self.a = a * 42

        // temporary local variable to be captured by the @autoclosure.
        let _a = self.a
        guard b == nil || _a > 0 else {
            throw "Too little a!"
        }

        self.b = self.a
    }
}

extension String: Error {}

Obviously, this assumes that self.a != a, otherwise you can just refer to a instead of self.a in the guard condition.


问:
custom svg filter not working on firefox
This below code works fine in chrome and filter is applied but fails in firefox. An extra space is also added by direct inclusion of svg definition in the html(This is present in all browsers). Not sure why its happening like this. Can someone let me know the issue, I am new to svg

Here is the codepen link: http://codepen.io/susheel61/pen/wJYgwr

```<code><svg version="1.1" id="ThemeSvg">
    <defs>
        <g>
            <!--/* Polygon definitions for overlay shape */-->
            <rect id="red-poly" x="0%" y="0%" width="53%" height="100%" fill="#b5121b" transform="skewX(-10)"></rect>
            <rect id="rect-fade-out" x="0%" y="0%" width="53%" height="100%" fill="url(#fade-out)" transform="skewX(-10)"></rect>
        </g>
        <g>
            <filter id="red-angled-overlay" x="0%" y="0%" width="100%" height="100%">
                <!--/* Bring in the mask for fading the image out */-->
                <feImage xlink:href="#rect-fade-out" result="red-overlay" x="0" y="0"></feImage>
                <!--/* Create composite of image and fade mask */-->
                <feComposite in="SourceGraphic" in2="red-overlay" operator="out" result="composite"></feComposite>
                <!--/* Bring in the colored polygon for the overlay */-->
                <feImage xlink:href="#red-poly" result="overlay" x="0" y="0"></feImage>
                <!--/* Blend the overlay with the faded image */-->
                <feBlend in="composite" in2="overlay" mode="multiply"></feBlend>
            </filter>
        </g>
    </defs>
</svg>

<svg version="1.1" viewBox="0 0 840 474" preserveAspectRatio="xMaxYMin slice">
    <image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://wowslider.com/sliders/demo-10/data/images/autumn_leaves.jpg" width="100%" height="100%" filter="url(#red-angled-overlay)" class="svg-black-overlay"></image>
</svg>
</code>```

答:
Firefox does not support feImage filters where the image is a fragment. It only supports feImage where the image is a complete standalone image or a data URI of a complete SVG document.

You'd have to create two additional standalone SVG images one with each polygon definition in and point the feImage elements at the complete image document in each case.

Body:
This below code works fine in chrome and filter is applied but fails in firefox. An extra space is also added by direct inclusion of svg definition in the html(This is present in all browsers). Not sure why its happening like this. Can someone let me know the issue, I am new to svg

Here is the codepen link: http://codepen.io/susheel61/pen/wJYgwr

<svg version="1.1" id="ThemeSvg">
    <defs>
        <g>

            <rect id="red-poly" x="0%" y="0%" width="53%" height="100%" fill="#b5121b" transform="skewX(-10)"></rect>
            <rect id="rect-fade-out" x="0%" y="0%" width="53%" height="100%" fill="url(#fade-out)" transform="skewX(-10)"></rect>
        </g>
        <g>
            <filter id="red-angled-overlay" x="0%" y="0%" width="100%" height="100%">

                <feImage xlink:href="#rect-fade-out" result="red-overlay" x="0" y="0"></feImage>

                <feComposite in="SourceGraphic" in2="red-overlay" operator="out" result="composite"></feComposite>

                <feImage xlink:href="#red-poly" result="overlay" x="0" y="0"></feImage>

                <feBlend in="composite" in2="overlay" mode="multiply"></feBlend>
            </filter>
        </g>
    </defs>
</svg>

<svg version="1.1" viewBox="0 0 840 474" preserveAspectRatio="xMaxYMin slice">
    <image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://wowslider.com/sliders/demo-10/data/images/autumn_leaves.jpg" width="100%" height="100%" filter="url(#red-angled-overlay)" class="svg-black-overlay"></image>
</svg>


问:
How to get a non null value using getLastKnownLocation when the app is launched
```<code>package com.example.getlocation;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class LbsGeocodingActivity extends Activity {

    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
    private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;

    protected LocationManager locationManager;

    protected Button retrieveLocationButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

        if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {

            ActivityCompat.requestPermissions( this, new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                    LbsGeocodingActivity.MY_PERMISSION_ACCESS_COARSE_LOCATION );
        }

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                MINIMUM_TIME_BETWEEN_UPDATES,
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                new MyLocationListener()
        );

        retrieveLocationButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showCurrentLocation();
            }
        });

    }

    protected void showCurrentLocation() {

        if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {

            ActivityCompat.requestPermissions( this, new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                    LbsGeocodingActivity.MY_PERMISSION_ACCESS_COARSE_LOCATION );
        }

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {
            String message = String.format(
                    "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude()
            );
            Toast.makeText(LbsGeocodingActivity.this, message,
                    Toast.LENGTH_LONG).show();
        }

    }

    private class MyLocationListener implements LocationListener {

        public void onLocationChanged(Location location) {
            String message = String.format(
                    "New Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude()
            );
            Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
        }

        public void onStatusChanged(String s, int i, Bundle b) {
            Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderDisabled(String s) {
            Toast.makeText(LbsGeocodingActivity.this,
                    "Provider disabled by the user. GPS turned off",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderEnabled(String s) {
            Toast.makeText(LbsGeocodingActivity.this,
                    "Provider enabled by the user. GPS turned on",
                    Toast.LENGTH_LONG).show();
        }

    }

}
</code>```

I am trying to get my current location on the click of a button. I tried the above code but the line Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) always gives the location null. I looked up to find out the problem may be due to getLastKnownLocation. As LastKnownLocation is not cancehd, I am getting null value. But how I modify this code to give the current location instead of null value.

答:
make two global strings like:

```<code>public class LbsGeocodingActivity extends Activity {

private latVar;
private lonVar;
</code>```

then in your onLocationChanged method in your location listener:

```<code>public void onLocationChanged(Location location) {

double lat = location.getLatitude();
double lon = location.getLongitude();
latVar = Double.toString(lat);
lonVar = Double.toString(lon);
</code>```

then in your button click:

```<code>protected void showCurrentLocation() {

    if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {

        ActivityCompat.requestPermissions( this, new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                LbsGeocodingActivity.MY_PERMISSION_ACCESS_COARSE_LOCATION );
    }
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                lonVar, latVar
        );
        Toast.makeText(LbsGeocodingActivity.this, message,
                Toast.LENGTH_LONG).show();
        }
</code>```

also consider changing your variable MINIMUM_DISTANCE_CHANGE_FOR_UPDATES to 0

Body:
package com.example.getlocation;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class LbsGeocodingActivity extends Activity {

    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
    private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;

    protected LocationManager locationManager;

    protected Button retrieveLocationButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

        if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {

            ActivityCompat.requestPermissions( this, new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                    LbsGeocodingActivity.MY_PERMISSION_ACCESS_COARSE_LOCATION );
        }

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                MINIMUM_TIME_BETWEEN_UPDATES,
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                new MyLocationListener()
        );

        retrieveLocationButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showCurrentLocation();
            }
        });

    }

    protected void showCurrentLocation() {

        if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {

            ActivityCompat.requestPermissions( this, new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                    LbsGeocodingActivity.MY_PERMISSION_ACCESS_COARSE_LOCATION );
        }

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {
            String message = String.format(
                    "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude()
            );
            Toast.makeText(LbsGeocodingActivity.this, message,
                    Toast.LENGTH_LONG).show();
        }

    }

    private class MyLocationListener implements LocationListener {

        public void onLocationChanged(Location location) {
            String message = String.format(
                    "New Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude()
            );
            Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
        }

        public void onStatusChanged(String s, int i, Bundle b) {
            Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderDisabled(String s) {
            Toast.makeText(LbsGeocodingActivity.this,
                    "Provider disabled by the user. GPS turned off",
                    Toast.LENGTH_LONG).show();
        }

        public void onProviderEnabled(String s) {
            Toast.makeText(LbsGeocodingActivity.this,
                    "Provider enabled by the user. GPS turned on",
                    Toast.LENGTH_LONG).show();
        }

    }

}

I am trying to get my current location on the click of a button. I tried the above code but the line Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) always gives the location null. I looked up to find out the problem may be due to getLastKnownLocation. As LastKnownLocation is not cancehd, I am getting null value. But how I modify this code to give the current location instead of null value.

Body:
make two global strings like:

public class LbsGeocodingActivity extends Activity {

private latVar;
private lonVar;

then in your onLocationChanged method in your location listener:

public void onLocationChanged(Location location) {

double lat = location.getLatitude();
double lon = location.getLongitude();
latVar = Double.toString(lat);
lonVar = Double.toString(lon);

then in your button click:

protected void showCurrentLocation() {

    if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {

        ActivityCompat.requestPermissions( this, new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                LbsGeocodingActivity.MY_PERMISSION_ACCESS_COARSE_LOCATION );
    }
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                lonVar, latVar
        );
        Toast.makeText(LbsGeocodingActivity.this, message,
                Toast.LENGTH_LONG).show();
        }

also consider changing your variable MINIMUM_DISTANCE_CHANGE_FOR_UPDATES to 0


问:
create associative array from collection in laravel for checking purposes
I am having an hard time trying to create an associative array from a collection in Laravel. The array should then be used for case checking.

I get my collection like this:

```<code>$collected_items = $user->collected_items()->where('model_id', '=', $model_id)->get();
</code>```

I need to extract only some relevant data from this collection like 'color_id'

I need to check the color_id because I should run different code if the color_id = 0, 1 or 2

Since I don't want to do a DB query for every case I thought I'd better eager load the data and then put it in an associative array;

However for the life of me I can't create this array
I tried:

```<code>$array_of_colors = []

    foreach ($collected_items as $i) {

                    if ($i['color_id'] == 0) {

                        $array_of_colors += ['black' => $i->model_color_id];
                    }
                    if ($i['color_id'] == 1) {

                        $array_of_colors += ['colored' => $i->model_color_id];
                    }
                    if ($i['color_id'] == 2) {

                        $array_of_colors += ['white' => $i->model_color_id];
                    }

                }
</code>```

Then I would use the $array_of_colors to check if I have a case of black then do something, is white something else etc etc.

答:
```<code>$array_of_colors = []

foreach ($collected_items as $i) {

                if ($i['color_id'] == 0) {

                    $array_of_colors[] = ['black' => $i->model_color_id];
                }
                if ($i['color_id'] == 1) {

                    $array_of_colors[] = ['colored' => $i->model_color_id];
                }
                if ($i['color_id'] == 2) {

                    $array_of_colors[] = ['white' => $i->model_color_id];
                }

            }
</code>```

Body:
I am having an hard time trying to create an associative array from a collection in Laravel. The array should then be used for case checking.

I get my collection like this:

$collected_items = $user->collected_items()->where('model_id', '=', $model_id)->get();

I need to extract only some relevant data from this collection like 'color_id'

I need to check the color_id because I should run different code if the color_id = 0, 1 or 2

Since I don't want to do a DB query for every case I thought I'd better eager load the data and then put it in an associative array;

However for the life of me I can't create this array
I tried:

$array_of_colors = []

    foreach ($collected_items as $i) {

                    if ($i['color_id'] == 0) {

                        $array_of_colors += ['black' => $i->model_color_id];
                    }
                    if ($i['color_id'] == 1) {

                        $array_of_colors += ['colored' => $i->model_color_id];
                    }
                    if ($i['color_id'] == 2) {

                        $array_of_colors += ['white' => $i->model_color_id];
                    }

                }

Then I would use the $array_of_colors to check if I have a case of black then do something, is white something else etc etc.


问:
WebAPI File upload function with parameters called from c# desktop app
I am working on a c# desktop application that makes calls a WebAPI.  One function uploads a file and has parameters.

I have found examples that use MultipartFormDataContent but I can't get that to work if there are parameters in the call.

How do you set up the PostAsync to have both MultiFormDataContent and url parameters in the content and not embedding them as part of the requestURI?

API Functions

```<code>    //Can Call this
    [HttpPost]
    [Route("UploadFileTest")]
    public async Task<HttpResponseMessage> UploadFileTest()
    {...

    //How to do this
    [HttpPost]
    [Route("UploadFileTest")]
    public async Task<HttpResponseMessage> UploadFileTest(string toolToken)
    {...
</code>```

C# calling it

```<code>    //this works with the first API call
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("www.someURL/APICalls/");
    var content = new MultipartFormDataContent();
    content.Add(new StreamContent(fileStream), "\"file\"", string.Format("\"{0}\"", fileInfo.Name));
    //adding the following line doesn't work with the second API function, it can't find the API function to call.
    //content.Add(new StringContent("12345"), "toolToken");

    Task taskUpload = client.PostAsync("UploadFileTest", content).ContinueWith(task =>
    {...
</code>```

答:
try [FromBody]

```<code>[HttpPost]
[Route("UploadFileTest")]
public async Task<HttpResponseMessage> UploadFileTest([FromBody]string toolToken)
{...
</code>```

Body:
I am working on a c# desktop application that makes calls a WebAPI.  One function uploads a file and has parameters.

I have found examples that use MultipartFormDataContent but I can't get that to work if there are parameters in the call.

How do you set up the PostAsync to have both MultiFormDataContent and url parameters in the content and not embedding them as part of the requestURI?

API Functions

    //Can Call this
    [HttpPost]
    [Route("UploadFileTest")]
    public async Task<HttpResponseMessage> UploadFileTest()
    {...

    //How to do this
    [HttpPost]
    [Route("UploadFileTest")]
    public async Task<HttpResponseMessage> UploadFileTest(string toolToken)
    {...

C# calling it

    //this works with the first API call
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("www.someURL/APICalls/");
    var content = new MultipartFormDataContent();
    content.Add(new StreamContent(fileStream), "\"file\"", string.Format("\"{0}\"", fileInfo.Name));
    //adding the following line doesn't work with the second API function, it can't find the API function to call.
    //content.Add(new StringContent("12345"), "toolToken");

    Task taskUpload = client.PostAsync("UploadFileTest", content).ContinueWith(task =>
    {...

Body:
try [FromBody]

[HttpPost]
[Route("UploadFileTest")]
public async Task<HttpResponseMessage> UploadFileTest([FromBody]string toolToken)
{...


问:
React JSX - dynamic html attribute
In JSX, we can indicate attribute value dynamically like:

```<code><div className={this.state.className}>This is a div.</div>
</code>```

Is it possible to indicate attribute (including attribute name and attribute value) dynamically? Like:

```<code>const value = emptyValue ? "" : "value='test'";
<input {value} />
</code>```

That means, once emptyValue is true, "input" tag should not include "value" attribute (value="" is different from no value attribute, as one is show empty in input field, another is show existing text in input field).

答:
ES6 object expansion only works for objects. Therefore to generate a dynamic attribute, try something like this:

```<code>const value = emptyValue ? {} : { value: 'test' }
<a  {...value} ></a>
</code>```

Note value will always be an object.

Title: React JSX - dynamic html attribute

Body:
In JSX, we can indicate attribute value dynamically like:

This is a div.

Is it possible to indicate attribute (including attribute name and attribute value) dynamically? Like:

const value = emptyValue ? "" : "value='test'";
<input {value} />

That means, once emptyValue is true, "input" tag should not include "value" attribute (value="" is different from no value attribute, as one is show empty in input field, another is show existing text in input field).

Body:
ES6 object expansion only works for objects. Therefore to generate a dynamic attribute, try something like this:

const value = emptyValue ? {} : { value: 'test' }
<a  {...value} ></a>

Note value will always be an object.