问:
EF Core Add a Related Entity (generic repository)
I have the an EF Core Db with the following models and one to many relationship

```<code>public class AttributeType
{
    public int AttributeTypeId { get; set; }
    public string Name { get; set; }

    public List<Attribute> AttributeList { get; set; }
}

public class Attribute
{
    public int AttributeId { get; set; }
    public string Name { get; set; }

    public int AttributeTypeId { get; set; }
    public AttributeType AttributeType { get; set; }
}
</code>```

If I'll try to add an attribute in this way it works:

```<code>using (var db = new SampleDbContext())
            {
                var attributeType = db.AttributeTypes.FirstOrDefault();

                Attribute attribute = new Attribute
                {
                    Name = "bbb",
                    AttributeTypeId = attributeType.AttributeTypeId,
                    AttributeType = attributeType
                };
                var item = db.Attributes.Add(attribute);
                db.SaveChanges();
            }
</code>```

(in the real the attributeType will come from a combobox and the name from a textbox, but now let's jus keep the code simple)

but when I try to use a generic method, like the following code, doesn't work

```<code>     AttributeType attributeType;

                using (var db = new SampleDbContext())
                {
                    attributeType = db.AttributeTypes.FirstOrDefault();
                }

                Attribute attribute = new Attribute
                {
                    Name = "eee",
                    AttributeType = attributeType,
                    AttributeTypeId = attributeType.AttributeTypeId
                };

                DbService.Insert(attribute);

 public static bool Insert<T>(T item) where T : class
        {
            try
            {
                using (var db = new SampleDbContext())
                {
                    db.Add(item);
                    db.SaveChanges();
                }
                return true;
            }
            catch (Exception exception)
            {
                Debug.WriteLine($"DbService Insert Exception: {exception}");
                return false;
            }
</code>```

and I get the following exception

Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in Microsoft.EntityFrameworkCore.dll
  DbService Insert Exception: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Microsoft.Data.Sqlite.SqliteException: SQLite Error 19: 'UNIQUE constraint failed: AttributeTypes.AttributeTypeId'.
  at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc, Sqlite3Handle db)
  at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
  at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary2 parameterValues, Boolean closeConnection)
  at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
  at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
  --- End of inner exception stack trace ---
  at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
  at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2 parameters)
  at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList1 entriesToSave)
  at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
  at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
  at UwpSamples.Services.DbService.Insert[T](T item)

but if I don't pass the AttributeType or I set it to null, like the following code, it works:

```<code>AttributeType attributeType;

        using (var db = new SampleDbContext())
        {
            attributeType = db.AttributeTypes.FirstOrDefault();
        }

        Attribute attribute = new Attribute
        {
            Name = "ddd",
            AttributeType = null,
            AttributeTypeId = attributeType.AttributeTypeId
        };

        DbService.Insert(attribute);
</code>```

-

```<code>AttributeType attributeType;

        using (var db = new SampleDbContext())
        {
            attributeType = db.AttributeTypes.FirstOrDefault();
        }

        Attribute attribute = new Attribute
        {
            Name = "ddd",
            AttributeTypeId = attributeType.AttributeTypeId
        };

        DbService.Insert(attribute);
</code>```

Thanks

答:
According to the failure, the value of attributeType.AttributeTypeId already exists in the DB. Could you check what is this value and if it is indeed unique?
I guess this value has to be unique because you use it as a primary key.

When you don't set the value or explicity set it to null, the ID is auto-generated by the DB, which explains why it works.

Hope it helps.

Body:
I have the an EF Core Db with the following models and one to many relationship

public class AttributeType
{
    public int AttributeTypeId { get; set; }
    public string Name { get; set; }

    public List<Attribute> AttributeList { get; set; }
}

public class Attribute
{
    public int AttributeId { get; set; }
    public string Name { get; set; }

    public int AttributeTypeId { get; set; }
    public AttributeType AttributeType { get; set; }
}

If I'll try to add an attribute in this way it works:

using (var db = new SampleDbContext())
            {
                var attributeType = db.AttributeTypes.FirstOrDefault();

                Attribute attribute = new Attribute
                {
                    Name = "bbb",
                    AttributeTypeId = attributeType.AttributeTypeId,
                    AttributeType = attributeType
                };
                var item = db.Attributes.Add(attribute);
                db.SaveChanges();
            }

(in the real the attributeType will come from a combobox and the name from a textbox, but now let's jus keep the code simple)

but when I try to use a generic method, like the following code, doesn't work

     AttributeType attributeType;

                using (var db = new SampleDbContext())
                {
                    attributeType = db.AttributeTypes.FirstOrDefault();
                }

                Attribute attribute = new Attribute
                {
                    Name = "eee",
                    AttributeType = attributeType,
                    AttributeTypeId = attributeType.AttributeTypeId
                };

                DbService.Insert(attribute);

 public static bool Insert<T>(T item) where T : class
        {
            try
            {
                using (var db = new SampleDbContext())
                {
                    db.Add(item);
                    db.SaveChanges();
                }
                return true;
            }
            catch (Exception exception)
            {
                Debug.WriteLine($"DbService Insert Exception: {exception}");
                return false;
            }

and I get the following exception

Exception thrown: 'Microsoft.EntityFrameworkCore.DbUpdateException' in Microsoft.EntityFrameworkCore.dll
  DbService Insert Exception: Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> Microsoft.Data.Sqlite.SqliteException: SQLite Error 19: 'UNIQUE constraint failed: AttributeTypes.AttributeTypeId'.
  at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc, Sqlite3Handle db)
  at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
  at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary2 parameterValues, Boolean closeConnection)
  at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
  at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
  --- End of inner exception stack trace ---
  at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
  at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(Tuple2 parameters)
  at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IReadOnlyList1 entriesToSave)
  at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
  at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
  at UwpSamples.Services.DbService.Insert[T](T item)

but if I don't pass the AttributeType or I set it to null, like the following code, it works:

AttributeType attributeType;

        using (var db = new SampleDbContext())
        {
            attributeType = db.AttributeTypes.FirstOrDefault();
        }

        Attribute attribute = new Attribute
        {
            Name = "ddd",
            AttributeType = null,
            AttributeTypeId = attributeType.AttributeTypeId
        };

        DbService.Insert(attribute);

-

AttributeType attributeType;

        using (var db = new SampleDbContext())
        {
            attributeType = db.AttributeTypes.FirstOrDefault();
        }

        Attribute attribute = new Attribute
        {
            Name = "ddd",
            AttributeTypeId = attributeType.AttributeTypeId
        };

        DbService.Insert(attribute);

Thanks


来源: stackexchange

问:
ruby Class.new(arg).method equivalent to Class.method(arg)
I have a class that includes a method to return a calculation based on the instance of the class.

```<code>class Foo
  def initialize(arg)
    @arg = arg
  end

  def baz
    @arg.dosomething
  end
end
</code>```

Is it possible to reformat this such that calling Foo.new(bar).baz is equal to Foo.baz(bar)?

答:
Is it possible to reformat this such that calling either Foo.new(bar).baz is equal to Foo.baz(bar)?

There are two different ways you can accomplish this. One looks like this:

```<code>def baz
  self.class.baz(@arg)
end

def self.baz(arg)
  arg.dosomething
end
</code>```

This makes sense when the calculation doesn't depend on any other instance methods or attributes. See it on repl.it: https://repl.it/I8m6/1

Alternatively, you can make the class method create an instance by calling new and call the instance method:

```<code>def self.baz(arg)
  new(arg).baz
end
</code>```

However, I think this is usually an antipattern: You're creating an instance just to call one method and then throw it away. I don't recommend this, but nevertheless you can see it on repl.it: https://repl.it/I8m6

ContentLicense: CC BY-SA 3.0

Body:
I have a class that includes a method to return a calculation based on the instance of the class.

class Foo
  def initialize(arg)
    @arg = arg
  end

  def baz
    @arg.dosomething
  end
end

Is it possible to reformat this such that calling Foo.new(bar).baz is equal to Foo.baz(bar)?

Body:
Is it possible to reformat this such that calling either Foo.new(bar).baz is equal to Foo.baz(bar)?

There are two different ways you can accomplish this. One looks like this:

def baz
  self.class.baz(@arg)
end

def self.baz(arg)
  arg.dosomething
end

This makes sense when the calculation doesn't depend on any other instance methods or attributes. See it on repl.it: https://repl.it/I8m6/1

Alternatively, you can make the class method create an instance by calling new and call the instance method:

def self.baz(arg)
  new(arg).baz
end

However, I think this is usually an antipattern: You're creating an instance just to call one method and then throw it away. I don't recommend this, but nevertheless you can see it on repl.it: https://repl.it/I8m6


问:
OpenGL 3.3 vertex buffer deletion before frame finished
This is an advanced OpenGL question and tbh. it seems more like a driver bug. I know that the standard explicitly states, that deletion of an object only deletes it's name, therefore a generator function can return the same name. However it's not clear on how to deal with this...

The situation is the following: I have a so called "transient" (C++) object (TO from now on), which generates GL objects, enqueues commands using them, then deletes them.

Now consider that I use more than one of this kind before I call SwapBuffers(). The following happens:

TO 1. generates a vertex buffer named VBO1, along with a VAO1 and other things

TO 1. calls some mapping/drawing commands with VBO1

TO 1. deletes the VAO1 and VBO1 (therefore the name VBO1 is freed)

TO 2. generates a vertex buffer object, now of course with the same name (VBO1) as the name 1 is deleted and available, along with another VAO (probably 1)

TO 2. calls some other mapping/drawing commands with this new VBO1 (different vertex positions, etc.)

TO 2. deletes the new VBO1

SwapBuffers()

And the result is: only the modifications performed by TO 1. are in effect. In a nutshell: I wanted to render a triangle, then a square, but I only got the triangle.

Workaround: not deleting the VBO, so I get a new name in TO 2. (VBO2)

I would like to ask for your help in this matter; although I'm aware of the fact that I shouldn't delete/generate objects mid-frame, but aside that, this "buggy" mechanism really disturbs me (I mean how can I trust GL then?...short answer: I can't...)

(sideonote: I've been programming 3D graphics since 12 years, but this thing really gave me the creeps...)

答:
I have similar problems with my multithreaded rendering code.  I use a double buffering system for the render commands, so when I delete an object, it might be used in the next frame.

The short of it is that TO shouldn't directly delete the GL objects.  It needs to submit the handle to a manager to queue for deletion between frames.  With my double buffering, I add a small timer to count down 2 frames before releasing.

For my transient verts, I have a large chunk of memory that I write to for storage, and skip the VBO submission. I don't know what your setup is or how many vertices you are pushing, but you may not benefit from VBOs if you  1) regenerate every frame or 2) push small sets of verts.  Definitely perf test with and without VBOs.


问:
how to implement a dynamic combo box selection system
I'm implementing a system these days, i want to implement a combo box selection process but i don't know how to implement it, so asking you guys favor?

my scenario is this, let's say we have two combo box selection lists, left one and right one, left one is the main one and the right one is the child of the left one.

when i select a item from the left combo box the right combo box's content should be changed according to the selection of the left one,

Ex: let's think about mobile phones, if i select the brand

Nokia

from the left combo box right combo box's content should be changed to

```<code>C6-01
E7-00
5232
X3-02
C1-01
C7-00
5228
C5-03
5250
6120ci
E5-00
E73
</code>```

like wise. please help me to implement a this kind of scenario!
any tutorial links, sample codes to understand the scenario is better!

regards,
Rangana

答:
This works by having two things. Firstly, a server that will return JSON for the category you need and, secondly, the code for the front end.

```<code><?php

    // Do what you need to
    $modelsArray = getModelsForBrand($_REQUEST['brand']);
    echo json_encode($modelsArray);
?>
</code>```

This uses the json_encode function to get the JSON on the array returned by whatever you use to get the models. I haven't used this function myself but it looks pretty simple.

Then your jQuery would look like this:

```<code>$("#brandCombo").change(function(){
    var chosenBrand = $(this).val(); // Get the value

    $.getJSON('/your-php-file.php', { "brand" : chosenBrand }, function(request){

        // Successful return from your PHP file

        $("#modelCombo").empty();

        // For each item returned, add it to your models combo box
        $.each(request, function(i,item){
            $("#modelCombo").append("<option value='" + item.value + "'>"+ item.name + "</option>");
        });
    });
});
</code>```

In this example, brandCombo is the ID of the list with the brands and modelCombo is the ID of the list the models should appear. When the value of brandCombo is changed, it makes the request to your PHP file to get the array of models in JSON. Then it goes through each one and adds a new option to your modelCombo list.

A similar question I answered is here, where I mentioned how to do it with all the data already on the page and in listboxes (hiding/showing them) or by AJAX requests (as the example above).

The other option, as shown in dyve's answer is to have all the information you need on the page already, in the form of a JavaScript object. If you wanted to do this, then then PHP json_encode function could still be of use (although you just call it once with all your data and plop it onto the page).

ContentLicense: CC BY-SA 2.5

Body:
I'm implementing a system these days, i want to implement a combo box selection process but i don't know how to implement it, so asking you guys favor?

my scenario is this, let's say we have two combo box selection lists, left one and right one, left one is the main one and the right one is the child of the left one.

when i select a item from the left combo box the right combo box's content should be changed according to the selection of the left one,

Ex: let's think about mobile phones, if i select the brand

Nokia

from the left combo box right combo box's content should be changed to

C6-01
E7-00
5232
X3-02
C1-01
C7-00
5228
C5-03
5250
6120ci
E5-00
E73

like wise. please help me to implement a this kind of scenario!
any tutorial links, sample codes to understand the scenario is better!

regards,
Rangana

Body:
This works by having two things. Firstly, a server that will return JSON for the category you need and, secondly, the code for the front end.

<?php

    // Do what you need to
    $modelsArray = getModelsForBrand($_REQUEST['brand']);
    echo json_encode($modelsArray);
?>

This uses the json_encode function to get the JSON on the array returned by whatever you use to get the models. I haven't used this function myself but it looks pretty simple.

Then your jQuery would look like this:

$("#brandCombo").change(function(){
    var chosenBrand = $(this).val(); // Get the value

    $.getJSON('/your-php-file.php', { "brand" : chosenBrand }, function(request){

        // Successful return from your PHP file

        $("#modelCombo").empty();

        // For each item returned, add it to your models combo box
        $.each(request, function(i,item){
            $("#modelCombo").append("<option value='" + item.value + "'>"+ item.name + "</option>");
        });
    });
});

In this example, brandCombo is the ID of the list with the brands and modelCombo is the ID of the list the models should appear. When the value of brandCombo is changed, it makes the request to your PHP file to get the array of models in JSON. Then it goes through each one and adds a new option to your modelCombo list.

A similar question I answered is here, where I mentioned how to do it with all the data already on the page and in listboxes (hiding/showing them) or by AJAX requests (as the example above).

The other option, as shown in dyve's answer is to have all the information you need on the page already, in the form of a JavaScript object. If you wanted to do this, then then PHP json_encode function could still be of use (although you just call it once with all your data and plop it onto the page).


问:
Create path from javascript object property
Let's say I've got the following javascript object

```<code>var obj = {
            a:{
                b:"value",
                c:{
                    d:"value2"
                }
            }
        }
</code>```

What function would, when input with the "d" object (for example, function getPath(obj, d)), output the "a.c.d" string? I've tried various things including object-path, but it doesn't seem to be designed for that

答:
You can iterate over the object using a recursive function, and save the path like :

function getPath(object, keyValue, path) {
  for (var k in object) {
    if (k === keyValue) {
      return path + '.' + k;
    }
    else if (typeof object[k] === 'object') {
      return getPath(object[k], keyValue, path !== '' ? path + '.' + k : k);
    }
  }
}

var obj = {
    a:{
        b:"value",
        c:{
            d:"value2"
        }
    }
};

var path = getPath(obj, 'd', '');
console.log(path);```

Body:
Let's say I've got the following javascript object

var obj = {
            a:{
                b:"value",
                c:{
                    d:"value2"
                }
            }
        }

What function would, when input with the "d" object (for example, function getPath(obj, d)), output the "a.c.d" string? I've tried various things including object-path, but it doesn't seem to be designed for that


问:
Resolving iphone 7 photo pixel data in matlab?
I just imported an image taken from my iphone 7 onto matlab. It turns out that the image has 3d size instead of 2d.

```<code>boxImage1 = imread('IMG_5175.jpg');

boxImage1      480x640x3            921600  uint8
</code>```

Can anyone explain why the size of image is in 3d instead of just two. I am trying to run object detection tools on a set of images to extract relevant objects.
Thanks,

答:
As pointed out in the comments, the three dimensions corresponds with the R, G and B channels. Have a look into the matlab documentation:

If the file contains a truecolor image, then A is an m-by-n-by-3 array.

Converting it to grayscale, using rgb2gray, is often a good idea, but it may depend on your application:

```<code>I = rgb2gray(boxImage1); % 480x640 matrix
</code>```

Body:
I just imported an image taken from my iphone 7 onto matlab. It turns out that the image has 3d size instead of 2d.

boxImage1 = imread('IMG_5175.jpg');

boxImage1      480x640x3            921600  uint8

Can anyone explain why the size of image is in 3d instead of just two. I am trying to run object detection tools on a set of images to extract relevant objects.
Thanks,

Body:
As pointed out in the comments, the three dimensions corresponds with the R, G and B channels. Have a look into the matlab documentation:

If the file contains a truecolor image, then A is an m-by-n-by-3 array.

Converting it to grayscale, using rgb2gray, is often a good idea, but it may depend on your application:

I = rgb2gray(boxImage1); % 480x640 matrix


问:
Inconsistencies in URL encoding methods across Objective-C and Swift
I have the following Objective-C code:

```<code>[@"http://www.google.com" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
// http%3A//www.google.com
</code>```

And yet, in Swift:

```<code>"http://www.google.com".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
// http://www.google.com
</code>```

To what can I attribute this discrepancy?

..and for extra credit, can I rely on this code to encode for url path reserved characters while passing a full url like this?

答:
The issue actually rests in the difference between NSString method stringByAddingPercentEncodingWithAllowedCharacters and String method addingPercentEncoding(withAllowedCharacters:). And this behavior has been changing from version to version. (It looks like the latest beta of iOS 11 now restores this behavior we used to see.)

I believe the root of the issue rests in the particulars of how paths are percent encoded. Section 3.3 of RFC 3986 says that colons are permitted in paths except in the first segment of a relative path.

The NSString method captures this notion, e.g. imagine a path whose first directory was foo: (with a colon) and a subdirectory of bar: (also with a colon):

```<code>NSString *string = @"foo:/bar:";
NSCharacterSet *cs = [NSCharacterSet URLPathAllowedCharacterSet];
NSLog(@"%@", [string stringByAddingPercentEncodingWithAllowedCharacters:cs]);
</code>```

That results in:

foo%3A/bar:

The : in the first segment of the page is percent encoded, but the : in subsequent segments are not. This captures the logic of how to handle colons in relative paths per RFC 3986.

The String method addingPercentEncoding(withAllowedCharacters:), however, does not do this:

```<code>let string = "foo:/bar:"
os_log("%@", string.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)
</code>```

Yields:

foo:/bar:

Clearly, the String method does not attempt that position-sensitive logic. This implementation is more in keeping with the name of the method (it considers solely what characters are "allowed" with no special logic that tries to guess, based upon where the allowed character appears, whether it's truly allowed or not.)

I gather that you are saddled with the code supplied in the question, but we should note that this behavior of percent escaping colons in relative paths, while interesting to explain what you experienced, is not really relevant to your immediate problem. The code you have been provided is simply incorrect. It is attempting to percent encode a URL as if it was just a path. But, it’s not a path; it’s a URL, which is a different thing with its own rules.

The deeper insight in percent encoding URLs is to acknowledge that different components of a URL allow different sets of characters, i.e. they require different percent encoding. That’s why NSCharacterSet has so many different URL-related character sets.

You really should percent encode the individual components, percent encoding each with the character set allowed for that type of component. Only when the individual components are percent encoded should they then be concatenated together to form the whole the URL.

Alternatively, NSURLComponents is designed precisely for this purpose, getting you out of the weeds of percent-encoding the individual components yourself. For example:

```<code>var components = URLComponents(string: "http://httpbin.org/post")!
let foo = URLQueryItem(name: "foo", value: "bar & baz")
let qux = URLQueryItem(name: "qux", value: "42")
components.queryItems = [foo, qux]

let url = components.url!
</code>```

That yields the following, with the & and the two spaces properly percent escaped within the foo value, but it correctly left the & in-between foo and qux:

http://httpbin.org/post?foo=bar%20%26%20baz&qux=42

It’s worth noting, though, that NSURLComponents has a small, yet fairly fundamental flaw: Specifically, if you have query values, NSURLQueryItem, that could have + characters, most web services need that percent escaped, but NSURLComponents won’t. If your URL has query components and if those query values might include + characters, I’d advise against NSURLComponents and would instead advise percent encoding the individual components of a URL yourself.

Body:
I have the following Objective-C code:

[@"http://www.google.com" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
// http%3A//www.google.com

And yet, in Swift:

"http://www.google.com".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)
// http://www.google.com

To what can I attribute this discrepancy?

..and for extra credit, can I rely on this code to encode for url path reserved characters while passing a full url like this?

Body:
The issue actually rests in the difference between NSString method stringByAddingPercentEncodingWithAllowedCharacters and String method addingPercentEncoding(withAllowedCharacters:). And this behavior has been changing from version to version. (It looks like the latest beta of iOS 11 now restores this behavior we used to see.)

I believe the root of the issue rests in the particulars of how paths are percent encoded. Section 3.3 of RFC 3986 says that colons are permitted in paths except in the first segment of a relative path.

The NSString method captures this notion, e.g. imagine a path whose first directory was foo: (with a colon) and a subdirectory of bar: (also with a colon):

NSString *string = @"foo:/bar:";
NSCharacterSet *cs = [NSCharacterSet URLPathAllowedCharacterSet];
NSLog(@"%@", [string stringByAddingPercentEncodingWithAllowedCharacters:cs]);

That results in:

foo%3A/bar:

The : in the first segment of the page is percent encoded, but the : in subsequent segments are not. This captures the logic of how to handle colons in relative paths per RFC 3986.

The String method addingPercentEncoding(withAllowedCharacters:), however, does not do this:

let string = "foo:/bar:"
os_log("%@", string.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)

Yields:

foo:/bar:

Clearly, the String method does not attempt that position-sensitive logic. This implementation is more in keeping with the name of the method (it considers solely what characters are "allowed" with no special logic that tries to guess, based upon where the allowed character appears, whether it's truly allowed or not.)

I gather that you are saddled with the code supplied in the question, but we should note that this behavior of percent escaping colons in relative paths, while interesting to explain what you experienced, is not really relevant to your immediate problem. The code you have been provided is simply incorrect. It is attempting to percent encode a URL as if it was just a path. But, it’s not a path; it’s a URL, which is a different thing with its own rules.

The deeper insight in percent encoding URLs is to acknowledge that different components of a URL allow different sets of characters, i.e. they require different percent encoding. That’s why NSCharacterSet has so many different URL-related character sets.

You really should percent encode the individual components, percent encoding each with the character set allowed for that type of component. Only when the individual components are percent encoded should they then be concatenated together to form the whole the URL.

Alternatively, NSURLComponents is designed precisely for this purpose, getting you out of the weeds of percent-encoding the individual components yourself. For example:

var components = URLComponents(string: "http://httpbin.org/post")!
let foo = URLQueryItem(name: "foo", value: "bar & baz")
let qux = URLQueryItem(name: "qux", value: "42")
components.queryItems = [foo, qux]

let url = components.url!

That yields the following, with the & and the two spaces properly percent escaped within the foo value, but it correctly left the & in-between foo and qux:

http://httpbin.org/post?foo=bar%20%26%20baz&qux=42

It’s worth noting, though, that NSURLComponents has a small, yet fairly fundamental flaw: Specifically, if you have query values, NSURLQueryItem, that could have + characters, most web services need that percent escaped, but NSURLComponents won’t. If your URL has query components and if those query values might include + characters, I’d advise against NSURLComponents and would instead advise percent encoding the individual components of a URL yourself.


问:
Start css animation without adding special class jQuery
I am trying to improve my image/div slider, that runs on jQuery. Each slide is a DIV where any other tag can be added (text, image..). and has it's specific class with specific animation (so adding another class with jQuery for animation seems a bit more difficult, and I have at least 2 different sliders using same jQuery.. is there something to just say NOW to css (only for elements inside DIV)).

When I animate events on each slide (text coming from up etc.), they all start on page load - logically -, not on DIV that's currently in front. But with my current code I cannot apply CSS animation by adding another class to IMG, SPAN etc. since I have specific animation for each one, but jQuery does not recognize classes and just move DIVs to left/right.

How do I make jQuery (css probably not) to start this animations just on current showed DIV? I also want to let CSS animate it, not jQuery (.animate()) because I have already prepared long animations in CSS for it.

jQuery:

automatic slide:

```<code>jQuery(document).ready(function ($) {

  $('#slider .some').ready(function(){
    setInterval(function () {
        moveRight();
    }, 60000);
  });
</code>```

and move right function

```<code>function moveRight() {
        $('#slider .some').animate({
            left: - slideWidth
        }, 200, function () {
            $('#slider .some div.slid:first-child').appendTo('#slider .some');
            $('#slider .some').css('left', '');
        });
    };
</code>```

CSS: /*removed all unnecessary stuff */

```<code>.slid {
   /*width, height, overflow ... */
  }

img { -webkit-animation: frameFirst 2s ease-out;
      -moz-animation: frameFirst 2s ease-out;
      -o-animation: frameFirst 2s ease-out;
      animation: frameFirst 2s ease-out;
    }

span { -webkit-animation: frameSecond 2s ease-out;
      -moz-animation: frameSecond 2s ease-out;
      -o-animation: frameSecond 2s ease-out;
      animation: frameSecond 2s ease-out;
    }

    /* and  @keyframes for those animations */
</code>```

HTML:

```<code><div id="slider">
  <div class="some">
     <div class="slid">
         <span></span><!--TEXT STUFF, HAS ITS OWN ANIMATION-->
         <img /><!--IMAGE STUFF, HAS ITS OWN ANIMATION-->
      </div>
      <div class="slid">
         <!-- ANOTHER STUFF WITH ANOTHER ANIMATIONS -->
      </div>
  </div>
</div>
</code>```

答:
Based on your comments, you can use .children() and .each() to identify elements that do not have a lot in common.

For example, you can use:

```<code>$('.slid').children().addClass("go");
</code>```

This will add the class "go" to all the children elements of class 'slid'. You can then use .each() to iterate each of those items.

```<code>$(".go").each(function(){
  $(this).animate();
});
</code>```

In this, $(this) represents the individual element. If need you can also do:

```<code>$(".go").each(function(i, el){
  $(el).animate();
});
</code>```

Where i is the Index (0, 1, 2, n...) of the element and el is the element itself.

Body:
I am trying to improve my image/div slider, that runs on jQuery. Each slide is a DIV where any other tag can be added (text, image..). and has it's specific class with specific animation (so adding another class with jQuery for animation seems a bit more difficult, and I have at least 2 different sliders using same jQuery.. is there something to just say NOW to css (only for elements inside DIV)).

When I animate events on each slide (text coming from up etc.), they all start on page load - logically -, not on DIV that's currently in front. But with my current code I cannot apply CSS animation by adding another class to IMG, SPAN etc. since I have specific animation for each one, but jQuery does not recognize classes and just move DIVs to left/right.

How do I make jQuery (css probably not) to start this animations just on current showed DIV? I also want to let CSS animate it, not jQuery (.animate()) because I have already prepared long animations in CSS for it.

jQuery:

automatic slide:

jQuery(document).ready(function ($) {

  $('#slider .some').ready(function(){
    setInterval(function () {
        moveRight();
    }, 60000);
  });

and move right function

function moveRight() {
        $('#slider .some').animate({
            left: - slideWidth
        }, 200, function () {
            $('#slider .some div.slid:first-child').appendTo('#slider .some');
            $('#slider .some').css('left', '');
        });
    };

CSS: /*removed all unnecessary stuff */

.slid {
   /*width, height, overflow ... */
  }

img { -webkit-animation: frameFirst 2s ease-out;
      -moz-animation: frameFirst 2s ease-out;
      -o-animation: frameFirst 2s ease-out;
      animation: frameFirst 2s ease-out;
    }

span { -webkit-animation: frameSecond 2s ease-out;
      -moz-animation: frameSecond 2s ease-out;
      -o-animation: frameSecond 2s ease-out;
      animation: frameSecond 2s ease-out;
    }

    /* and  @keyframes for those animations */

HTML:

Body:
Based on your comments, you can use .children() and .each() to identify elements that do not have a lot in common.

For example, you can use:

$('.slid').children().addClass("go");

This will add the class "go" to all the children elements of class 'slid'. You can then use .each() to iterate each of those items.

$(".go").each(function(){
  $(this).animate();
});

In this, $(this) represents the individual element. If need you can also do:

$(".go").each(function(i, el){
  $(el).animate();
});

Where i is the Index (0, 1, 2, n...) of the element and el is the element itself.


问:
tcp/ip without ip in .net
Strange title I know, but please hear me out. I am looking for a version of TcpClient and TcpListener which don't use IP. In essence, I would like to be able to use all the TCP benefits (reliable & ordered) on top of any protocol of my choosing (UDP, ICMP, DNS, carrier pigeon).

Is there a way I could somehow tap into what TCP is passing down to the IP layer?

Thanks,
Fidel

Edit:

I want a reliable protocol (eg. TCP) which can pump data into a stream, and read data from a stream, without knowing exactly how the stream transports that data.

I have explicit control over that stream. I just need TCP to send information to that stream instead of its regular underlying layer.

答:
You can achieve this and you do not need to use TCP/IP.

Have a look here, you can pass different address types not just TCP/IP.

But remember if you are talking about UDP, ICMP, ... they are different protocols not different addressing schemes.

Title: tcp/ip without ip in .net


问:
Getting correct status message of a shell script when using variables in shell script
I have a shell script like below.

```<code>#!/bin/bash

source /home/$USER/source.sh

[ $# -ne 1 ] && { echo "Usage : $0  table "; exit 1; }

table=$1

TIMESTAMP=`date "+%Y-%m-%d"`
touch /home/$USER/logs/${TIMESTAMP}.success_log
touch /home/$USER/logs/${TIMESTAMP}.fail_log
success_logs=/home/$USER/logs/${TIMESTAMP}.success_log
failed_logs=/home/$USER/logs/${TIMESTAMP}.fail_log
touch /home/$USER/logs/${TIMESTAMP}.log
logs=/home/$USER/logs/${TIMESTAMP}.log

function log_status
{
       status=$1
       message=$2
       if [ "$status" -ne 0 ]; then
                echo "`date +\"%Y-%m-%d %H:%M:%S\"` [ERROR] $message [Status] $status : failed" | tee -a "${failed_logs}"
                echo "$output" | tee -a "${logs}"
       else
                    echo "`date +\"%Y-%m-%d %H:%M:%S\"` [INFO] $message [Status] $status : success" | tee -a "${success_logs}"
                    echo "$output" | tee -a "${logs}"
       fi
}

Final=$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table)

output=$(echo "$Final" | tail -1)
echo "$output"

g_STATUS=$?
log_status $g_STATUS  "spark $table"

#output=$(echo "$Final" | tail -1)
echo "$Final"
#echo "$output"
echo "****************************************************************************************************************************"
</code>```

In this the variable output has to be appended to file.

Now when I have like below in the script.

```<code>output=$(echo "$Final" | tail -1)
echo "$output"
echo "$Final"

g_STATUS=$?
log_status $g_STATUS  "spark $table"
</code>```

I am getting the output variable printed in the logs file which is my expected result. But the status of the shell script is always success, even if Final =$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table) fails

Now when I have like below in the script.

```<code>g_STATUS=$?
log_status $g_STATUS  "spark $table"

output=$(echo "$Final" | tail -1)
echo "$output"
echo "$Final"
</code>```

Then the status of the shell script is always success, if Final =$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table) is success and the status of the shell script is always failed, if Final =$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table) is failed

And I am not having output variable printed in the logs file.

What should I do in order to have the output variable printed all the time to the logs file and have the correct status message.

I mean if the status of Final =$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table) is success then shell script status to be success if not then failed.

答:
Have you tried saving the status right after you execute the subshell of interest, and then returning it at the very end?</p>

```<code>Final =$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table)
g_STATUS=$?
output=$(echo "$Final" | tail -1)
echo "$output"

log_status $g_STATUS  "spark $table"

echo "$Final"

echo "****************************************************************************************************************************"
return $g_STATUS
</code>```

Body:
I have a shell script like below.

#!/bin/bash

source /home/$USER/source.sh

[ $# -ne 1 ] && { echo "Usage : $0  table "; exit 1; }

table=$1

TIMESTAMP=`date "+%Y-%m-%d"`
touch /home/$USER/logs/${TIMESTAMP}.success_log
touch /home/$USER/logs/${TIMESTAMP}.fail_log
success_logs=/home/$USER/logs/${TIMESTAMP}.success_log
failed_logs=/home/$USER/logs/${TIMESTAMP}.fail_log
touch /home/$USER/logs/${TIMESTAMP}.log
logs=/home/$USER/logs/${TIMESTAMP}.log

function log_status
{
       status=$1
       message=$2
       if [ "$status" -ne 0 ]; then
                echo "`date +\"%Y-%m-%d %H:%M:%S\"` [ERROR] $message [Status] $status : failed" | tee -a "${failed_logs}"
                echo "$output" | tee -a "${logs}"
       else
                    echo "`date +\"%Y-%m-%d %H:%M:%S\"` [INFO] $message [Status] $status : success" | tee -a "${success_logs}"
                    echo "$output" | tee -a "${logs}"
       fi
}

Final=$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table)

output=$(echo "$Final" | tail -1)
echo "$output"

g_STATUS=$?
log_status $g_STATUS  "spark $table"

#output=$(echo "$Final" | tail -1)
echo "$Final"
#echo "$output"
echo "****************************************************************************************************************************"

In this the variable output has to be appended to file.

Now when I have like below in the script.

output=$(echo "$Final" | tail -1)
echo "$output"
echo "$Final"

g_STATUS=$?
log_status $g_STATUS  "spark $table"

I am getting the output variable printed in the logs file which is my expected result. But the status of the shell script is always success, even if Final =$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table) fails

Now when I have like below in the script.

g_STATUS=$?
log_status $g_STATUS  "spark $table"

output=$(echo "$Final" | tail -1)
echo "$output"
echo "$Final"

Then the status of the shell script is always success, if Final =$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table) is success and the status of the shell script is always failed, if Final =$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table) is failed

And I am not having output variable printed in the logs file.

What should I do in order to have the output variable printed all the time to the logs file and have the correct status message.

I mean if the status of Final =$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table) is success then shell script status to be success if not then failed.

Body:
Have you tried saving the status right after you execute the subshell of interest, and then returning it at the very end?

Final =$(spark-submit --name "Spark" --master "yarn-client" /home/$USER/import.py $table)
g_STATUS=$?
output=$(echo "$Final" | tail -1)
echo "$output"

log_status $g_STATUS  "spark $table"

echo "$Final"

echo "****************************************************************************************************************************"
return $g_STATUS


问:
Selecting images inside the table and inside the div
How do I select the images below (@div class="this") without selecting the images above so that I can style it with CSS?</p>

```<code><table>
    <tr>
        <td><a href="../index.html"><img src="../home.png"></a></td> <!-- GO BACK TO HOMEPAGE -->
        <td><a href="########"><img src="../artist.png"></a></td> <!-- GO TO ARTIST -->
        <td><img src="../portfolio.png"></td>
        <td><img src="../contact.png"></td>
    </tr>
    <tr>
        <td colspan="8"><img src="../logo.png"></td>
    </tr>
    <tr>
        <td colspan="8"><img src="../greenmoralesgraphic.png"></td>
    </tr>
    <tr><div class="this">
        <td><img src="nostalgia.jpg" width="400px" height="400px"></td>
        <td><img src="pwersa.jpg" width="400px" height="400px"></td>
        <td><img src="tag_along.jpg" width="400px" height="400px"></td>
        <td><img src="tweet.jpg" width="400px" height="400px"></td>
        </div>
    </tr>
</table>
</code>```

答:
You can use

```<code>.this img {
  outline: 1px solid red;
}
</code>```

to style all images within that specific class.

Body:
You can use

.this img {
  outline: 1px solid red;
}

to style all images within that specific class.


问:
How do I map with rarely used state in clojure?
The situation is as follows: I'm transforming a sequence of values. The transformation of each value breaks down into a number of different cases. Most values are completely independent of each other. However there is one special case that requires me to keep track of how many special cases I've encountered so far. In imperative programming this is pretty straightforward:

```<code>int i = 0;
List<String> results = new ArrayList<>();
for (String value : values) {
  if (case1(value)) {
    results.add(handleCase1(value));
  } else if (case2(value)) {
  ...
  } else if (special(value)) {
    results.add(handleSpecial(value, i));
    i++;
  }
}
</code>```

However in Clojure the best I've come up with is:

```<code>(first
 (reduce
  (fn [[results i] value]
      (cond
       (case-1? value) [(conj results (handle-case-1 value)) i]
       (case-2? value) ...
       (special? value) [(conj results (handle-special value i))
                         (inc i)]))
  [[] 0] values))
</code>```

Which is pretty ugly considering that without the special case this would become:

```<code>(map #(cond
       (case-1? %) (handle-case-1 %)
       (case-2? %) ...)
      values)
</code>```

The trouble is that I'm manually stitching a sequence together during the reduction. Also most cases don't even care about the index but must nonetheless pass it along for the next reduction step.

Is there a cleaner solution to this problem?

答:
There is nothing wrong in using a volatile! for this - in your case, it does not escape the context of the expression and does not create any mutability or threading complications:

```<code>(let [i (volatile! 0)]
  (map #(cond
          (case-1? %) (handle-case-1 %)
          (case-2? %) (handle-case-2 %)
          (special? %) (do (handle-special % @i)
                           (vswap! i inc)))
       values)
</code>```

You can use an atom instead if you are using Clojure < 1.7 or want to do it in a multi-threaded way (e. g. with pmap).

Body:
The situation is as follows: I'm transforming a sequence of values. The transformation of each value breaks down into a number of different cases. Most values are completely independent of each other. However there is one special case that requires me to keep track of how many special cases I've encountered so far. In imperative programming this is pretty straightforward:

int i = 0;
List<String> results = new ArrayList<>();
for (String value : values) {
  if (case1(value)) {
    results.add(handleCase1(value));
  } else if (case2(value)) {
  ...
  } else if (special(value)) {
    results.add(handleSpecial(value, i));
    i++;
  }
}

However in Clojure the best I've come up with is:

(first
 (reduce
  (fn [[results i] value]
      (cond
       (case-1? value) [(conj results (handle-case-1 value)) i]
       (case-2? value) ...
       (special? value) [(conj results (handle-special value i))
                         (inc i)]))
  [[] 0] values))

Which is pretty ugly considering that without the special case this would become:

(map #(cond
       (case-1? %) (handle-case-1 %)
       (case-2? %) ...)
      values)

The trouble is that I'm manually stitching a sequence together during the reduction. Also most cases don't even care about the index but must nonetheless pass it along for the next reduction step.

Is there a cleaner solution to this problem?

Body:
There is nothing wrong in using a volatile! for this - in your case, it does not escape the context of the expression and does not create any mutability or threading complications:

(let [i (volatile! 0)]
  (map #(cond
          (case-1? %) (handle-case-1 %)
          (case-2? %) (handle-case-2 %)
          (special? %) (do (handle-special % @i)
                           (vswap! i inc)))
       values)

You can use an atom instead if you are using Clojure < 1.7 or want to do it in a multi-threaded way (e. g. with pmap).


问:
How can I collect the user's correct choice in my Trivia game?
I have tried multiple things to collect the right answer when the radio button is pressed, but after the game is done I still get a 0 out of 5.
I'm not sure what else to do and have been stuck on this for a while.  Any help will be greatly appreciated!

$(document).ready(function() {

  $("#clickStart").click(function() {
    $('#questions').show(600);
    $('#clock').show(700);
    $('#hide').hide(500);

  });

  (function() {
    var questions = [{
        question: "The great Victoria Desert is located in?",
        choices: ['Canada', 'West Africa', 'Australia', 'North America'],
        correctAnswer: 'Australia'
      },
      {
        question: "The intersecting lines drawn on maps and globes are?",
        choices: ['lattitudes', 'longitudes', 'geographic grids', 'none of the above'],
        correctAnswer: 'geographic gird'
      },
      {
        question: "The landmass of which of the following continents is the least?",
        choices: ['Africa', 'Asia', 'Australia', 'Europe'],
        correctAnswer: 'Australia'
      },
      {
        question: "Without ____ the equator would be much hotter than it is while the poles would be much cooler",
        choices: ['Lattitude of redistribution of heat', 'Cycle of air circulation', 'Global wind pattern', 'All are similiar'],
        correctAnswer: 'All are simliar'
      },
      {
        question: "The habitats valuable for commercially harvested species are called?",
        choices: ['Coral reefs', 'Sea grass bed', 'hot spots', 'None of the above'],
        correctAnswer: 'Sea grass bed'
      }
    ];

    var questionCounter = 0; //Tracks question number
    var selections = []; //Array containing user choices
    var quiz = $("#quiz"); //Quiz div object

    // Display initial question
    displayNext();

    //  'next' button
    $("#next").on("click", function(e) {
      e.preventDefault();

      // Suspend click listener during fade animation
      if (quiz.is(":animated")) {
        return false;
      }
      choose();

      // If no user selection, progress is stopped
      if (isNaN(selections[questionCounter])) {
        alert("Please make a selection!");
      } else {
        questionCounter++;
        displayNext();
      }
    });

    // 'prev' button
    $("#prev").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      choose();
      questionCounter--;
      displayNext();
    });

    // 'Start Over' button
    $("#start").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      questionCounter = 0;
      selections = [];
      displayNext();
      $("#start").hide();
    });

    // Animates buttons on hover
    $(".button").on("mouseenter", function() {
      $(this).addClass("active");
    });
    $(".button").on("mouseleave", function() {
      $(this).removeClass("active");
    });

    // Creates and returns the div that contains the questions and
    // the answer selections
    function createQuestionElement(index) {
      var qElement = $("
", {
        id: "question"
      });

      var header = $("
Question " + (index + 1) + ":
");
      qElement.append(header);

      var question = $("
").append(questions[index].question);
      qElement.append(question);

      var radioButtons = createRadios(index);
      qElement.append(radioButtons);

      return qElement;
    }

    // Creates a list of the answer choices as radio inputs
    function createRadios(index) {
      var radioList = $("
");
      var item;
      var input = "";
      for (var i = 0; i < questions[index].choices.length; i++) {
        item = $("
");
        input = '<input type="radio" name="answer" value=' + i + " />";
        input += questions[index].choices[i];
        item.append(input);
        radioList.append(item);
      }
      return radioList;
    }

    // Reads the user selection and pushes the value to an array
    function choose() {
      selections[questionCounter] = +$('input[name="answer"]:checked').val();
    }

    // Displays next requested element
    function displayNext() {
      quiz.fadeOut(function() {
        $("#question").remove();

        if (questionCounter < questions.length) {
          var nextQuestion = createQuestionElement(questionCounter);
          quiz.append(nextQuestion).fadeIn();
          if (!isNaN(selections[questionCounter])) {
            $("input[value=" + selections[questionCounter] + "]").prop(
              "checked",
              true
            );
          }

          // Controls display of 'prev' button
          if (questionCounter === 1) {
            $("#prev").show();
          } else if (questionCounter === 0) {
            $("#prev").hide();
            $("#next").show();
          }
        } else {
          var scoreElem = displayScore();
          quiz.append(scoreElem).fadeIn();
          $("#next").hide();
          $("#prev").hide();
          $("#start").show();
        }
      });
    }

    // Computes score and returns a paragraph element to be displayed
    function displayScore() {
      var score = $("
", {
        id: "question"
      });

      var numCorrect = 0;
      for (var i = 0; i < selections.length; i++) {
        if (selections[i] === questions[i].correctAnswer) {
          numCorrect++;
        }
      }

      score.append(
        "You got " +
        numCorrect +
        " questions out of " +
        questions.length +
        " right!!!"
      );
      return score;
    }
  })();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 0;
  margin: 0;
  width: 100%;
  background: url(../images/background.png);
  height: 1vh;
  background-repeat: no-repeat;
}

h1 {
  font-family: sans-serif;
  font-size: 3em;
  font-weight: 700;
  color: #fff;
  text-align: center;
}

#title {
  text-decoration: underline;
}

#header {
  text-align: center;
  font-size: 30px;
  font-weight: 700px;
  color: #fff;
  width: 100%;
  height: 200px;
  padding: 7%;
}

.start-button {
  background-color: rgba(0, 0, 0, .7);
  margin-top: 5%;
  width: 300px;
  height: 100px;
}

.start-button:hover {
  background-color: #0246e2;
  color: #f5684f;
  font-size: 50px;
}

button {
  text-align: center;
}

#clock {
  display: none;
  color: #fff;
  font-size: 100px;
  z-index: 1000;
}

#quiz {
  text-indent: 10px;
}

.button {
  border: 4px solid;
  border-radius: 5px;
  width: 40px;
  padding-left: 5px;
  padding-right: 5px;
  position: relative;
  float: right;
  background-color: #DCDCDC;
  color: black;
  margin: 0 2px 0 2px;
}

.button.active {
  background-color: #F8F8FF;
  color: #525252;
}

#questions {
  display: none;
  padding-top: 10%;
  width: 100%;
  height: auto;
}

.button a {
  text-decoration: none;
  color: black;
}

#content {
  width: 100%;
  margin: auto;
  padding: 0 25px 40px 10px;
  background-color: rgba(0, 0, 0, .7);
  border: 4px solid #B0E0E6;
  border-radius: 5px;
  color: #FFFFFF;
  font-weight: bold;
  box-shadow: 5px 5px 5px #888;
  height: 500px;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#prev {
  display: none;
}

#start {
  display: none;
  width: 90px;
}</code>```

<!DOCTYPE html>

  <title>Trivia Game</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="./assets/css/style.css">

How Well Do You Know Your Geography?

You have 2 min to guess all the questions...Good Luck!

          <button id="clickStart" class="start-button">Start!</button>

00:00

Next

Prev

 Start Over

```

答: No, I was just being dumb and calling the string of the array rather than the number.  So instead of having the correct answer be 'Austrailia', it would be 2.  As soon as I posted this question, of course, I figure it out lol.  Thanks for the help anyways though. </p>

Body:
I have tried multiple things to collect the right answer when the radio button is pressed, but after the game is done I still get a 0 out of 5.
I'm not sure what else to do and have been stuck on this for a while.  Any help will be greatly appreciated!

$(document).ready(function() {

  $("#clickStart").click(function() {
    $('#questions').show(600);
    $('#clock').show(700);
    $('#hide').hide(500);

  });

  (function() {
    var questions = [{
        question: "The great Victoria Desert is located in?",
        choices: ['Canada', 'West Africa', 'Australia', 'North America'],
        correctAnswer: 'Australia'
      },
      {
        question: "The intersecting lines drawn on maps and globes are?",
        choices: ['lattitudes', 'longitudes', 'geographic grids', 'none of the above'],
        correctAnswer: 'geographic gird'
      },
      {
        question: "The landmass of which of the following continents is the least?",
        choices: ['Africa', 'Asia', 'Australia', 'Europe'],
        correctAnswer: 'Australia'
      },
      {
        question: "Without ____ the equator would be much hotter than it is while the poles would be much cooler",
        choices: ['Lattitude of redistribution of heat', 'Cycle of air circulation', 'Global wind pattern', 'All are similiar'],
        correctAnswer: 'All are simliar'
      },
      {
        question: "The habitats valuable for commercially harvested species are called?",
        choices: ['Coral reefs', 'Sea grass bed', 'hot spots', 'None of the above'],
        correctAnswer: 'Sea grass bed'
      }
    ];

    var questionCounter = 0; //Tracks question number
    var selections = []; //Array containing user choices
    var quiz = $("#quiz"); //Quiz div object

    // Display initial question
    displayNext();

    //  'next' button
    $("#next").on("click", function(e) {
      e.preventDefault();

      // Suspend click listener during fade animation
      if (quiz.is(":animated")) {
        return false;
      }
      choose();

      // If no user selection, progress is stopped
      if (isNaN(selections[questionCounter])) {
        alert("Please make a selection!");
      } else {
        questionCounter++;
        displayNext();
      }
    });

    // 'prev' button
    $("#prev").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      choose();
      questionCounter--;
      displayNext();
    });

    // 'Start Over' button
    $("#start").on("click", function(e) {
      e.preventDefault();

      if (quiz.is(":animated")) {
        return false;
      }
      questionCounter = 0;
      selections = [];
      displayNext();
      $("#start").hide();
    });

    // Animates buttons on hover
    $(".button").on("mouseenter", function() {
      $(this).addClass("active");
    });
    $(".button").on("mouseleave", function() {
      $(this).removeClass("active");
    });

    // Creates and returns the div that contains the questions and
    // the answer selections
    function createQuestionElement(index) {
      var qElement = $("
", {
        id: "question"
      });

      var header = $("
Question " + (index + 1) + ":
");
      qElement.append(header);

      var question = $("
").append(questions[index].question);
      qElement.append(question);

      var radioButtons = createRadios(index);
      qElement.append(radioButtons);

      return qElement;
    }

    // Creates a list of the answer choices as radio inputs
    function createRadios(index) {
      var radioList = $("
");
      var item;
      var input = "";
      for (var i = 0; i < questions[index].choices.length; i++) {
        item = $("
");
        input = '<input type="radio" name="answer" value=' + i + " />";
        input += questions[index].choices[i];
        item.append(input);
        radioList.append(item);
      }
      return radioList;
    }

    // Reads the user selection and pushes the value to an array
    function choose() {
      selections[questionCounter] = +$('input[name="answer"]:checked').val();
    }

    // Displays next requested element
    function displayNext() {
      quiz.fadeOut(function() {
        $("#question").remove();

        if (questionCounter < questions.length) {
          var nextQuestion = createQuestionElement(questionCounter);
          quiz.append(nextQuestion).fadeIn();
          if (!isNaN(selections[questionCounter])) {
            $("input[value=" + selections[questionCounter] + "]").prop(
              "checked",
              true
            );
          }

          // Controls display of 'prev' button
          if (questionCounter === 1) {
            $("#prev").show();
          } else if (questionCounter === 0) {
            $("#prev").hide();
            $("#next").show();
          }
        } else {
          var scoreElem = displayScore();
          quiz.append(scoreElem).fadeIn();
          $("#next").hide();
          $("#prev").hide();
          $("#start").show();
        }
      });
    }

    // Computes score and returns a paragraph element to be displayed
    function displayScore() {
      var score = $("
", {
        id: "question"
      });

      var numCorrect = 0;
      for (var i = 0; i < selections.length; i++) {
        if (selections[i] === questions[i].correctAnswer) {
          numCorrect++;
        }
      }

      score.append(
        "You got " +
        numCorrect +
        " questions out of " +
        questions.length +
        " right!!!"
      );
      return score;
    }
  })();
});

body {
  padding: 0;
  margin: 0;
  width: 100%;
  background: url(../images/background.png);
  height: 1vh;
  background-repeat: no-repeat;
}

h1 {
  font-family: sans-serif;
  font-size: 3em;
  font-weight: 700;
  color: #fff;
  text-align: center;
}

#title {
  text-decoration: underline;
}

#header {
  text-align: center;
  font-size: 30px;
  font-weight: 700px;
  color: #fff;
  width: 100%;
  height: 200px;
  padding: 7%;
}

.start-button {
  background-color: rgba(0, 0, 0, .7);
  margin-top: 5%;
  width: 300px;
  height: 100px;
}

.start-button:hover {
  background-color: #0246e2;
  color: #f5684f;
  font-size: 50px;
}

button {
  text-align: center;
}

#clock {
  display: none;
  color: #fff;
  font-size: 100px;
  z-index: 1000;
}

#quiz {
  text-indent: 10px;
}

.button {
  border: 4px solid;
  border-radius: 5px;
  width: 40px;
  padding-left: 5px;
  padding-right: 5px;
  position: relative;
  float: right;
  background-color: #DCDCDC;
  color: black;
  margin: 0 2px 0 2px;
}

.button.active {
  background-color: #F8F8FF;
  color: #525252;
}

#questions {
  display: none;
  padding-top: 10%;
  width: 100%;
  height: auto;
}

.button a {
  text-decoration: none;
  color: black;
}

#content {
  width: 100%;
  margin: auto;
  padding: 0 25px 40px 10px;
  background-color: rgba(0, 0, 0, .7);
  border: 4px solid #B0E0E6;
  border-radius: 5px;
  color: #FFFFFF;
  font-weight: bold;
  box-shadow: 5px 5px 5px #888;
  height: 500px;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#prev {
  display: none;
}

#start {
  display: none;
  width: 90px;
}

<!DOCTYPE html>

  <title>Trivia Game</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="./assets/css/style.css">

How Well Do You Know Your Geography?

You have 2 min to guess all the questions...Good Luck!

          <button id="clickStart" class="start-button">Start!</button>

00:00

Next

Prev

 Start Over


问:
Drawing box around message
I'm working on this Python task that I can't figure out. It is the last of 3 functions and the first 2 were much easier to program then this one. The instructions are
"Given a message that may contain multiple lines, utilize the split() function to identify the individual lines, and the format() function so that when printed, it draws a box around the message's lines, all centered. Box uses vertical bars & dashes on the sides (|, -), +'s in the corners (+), and there is always a column of spaces to the left and right of the widest line of the message."

Some examples for what this function needs to do:

test that: border_msg('a') == '+---+\n| a |\n+---+\n'

test that: border_msg('hello') == '+-------+\n| hello |\n+-------+\n'

test that: border_msg("hi!\nhow are you?\ndrive safely!") == '+---------------+\n| hi! |\n| how are you? |\n| drive safely! |\n+---------------+\n'

I think it needs to print the above tests so that the words in the middle are surrounded by the "+------+ on the top and bottom and "|"'s on the sides.

Here is the code I have so far. I'm not sure where I would go from here.

```<code>def border_msg(msg):
    border_msg.split("\n")
    '%s'.format(msg)
    return border_msg(msg)
    print border_msg(msg)
</code>```

答:
```<code>def border_msg(msg):
    msg_lines=msg.split('\n')
    max_length=max([len(line) for line in msg_lines])
    count = max_length +2

    dash = "*"*count
    print("*%s*" %dash)

    for line in msg_lines:
        half_dif=(max_length-len(line))
        if half_dif==0:
            print("* %s *"%line)
        else:
            print("* %s "%line+' '*half_dif+'*')

    print("*%s*"%dash)

border_msg('first_line\nsecond_line\nthe_ultimate_longest_line') # without print
</code>```

Title: Drawing box around message

Body:
I'm working on this Python task that I can't figure out. It is the last of 3 functions and the first 2 were much easier to program then this one. The instructions are
"Given a message that may contain multiple lines, utilize the split() function to identify the individual lines, and the format() function so that when printed, it draws a box around the message's lines, all centered. Box uses vertical bars & dashes on the sides (|, -), +'s in the corners (+), and there is always a column of spaces to the left and right of the widest line of the message."

Some examples for what this function needs to do:

test that: border_msg('a') == '+---+\n| a |\n+---+\n'

test that: border_msg('hello') == '+-------+\n| hello |\n+-------+\n'

test that: border_msg("hi!\nhow are you?\ndrive safely!") == '+---------------+\n| hi! |\n| how are you? |\n| drive safely! |\n+---------------+\n'

I think it needs to print the above tests so that the words in the middle are surrounded by the "+------+ on the top and bottom and "|"'s on the sides.

Here is the code I have so far. I'm not sure where I would go from here.

def border_msg(msg):
    border_msg.split("\n")
    '%s'.format(msg)
    return border_msg(msg)
    print border_msg(msg)


问:
open same frame when button click in java
i updated the code because many people doesn't understand so write a simple representation for that.
here is the problem whenever i clicked the button it open a new frame but i dont want this it does't open a new frame it remain open the same frame.

code for main frame :

```<code>import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JavaProject2_27 {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JavaProject2_27 window = new JavaProject2_27();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public JavaProject2_27() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnClicked = new JButton("Clicked");
        btnClicked.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JavaProject2_28 obj=new JavaProject2_28();
                obj.getJavaProject2_28();
            }
        });
        btnClicked.setBounds(150, 99, 89, 23);
        frame.getContentPane().add(btnClicked);
    }
}
</code>```

code for the second frame :

```<code>import java.awt.EventQueue;

import javax.swing.JFrame;

public class JavaProject2_28 {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JavaProject2_28 window = new JavaProject2_28();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public JavaProject2_28() {
        initialize();
    }

    public void getJavaProject2_28()
    {
        frame.setVisible(true);
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}
</code>```

snapshot

答:
I solved It Please A look :
Parent Class:

```<code>import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ParentClass {

    private JFrame frame;
    private int Count;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ParentClass window = new ParentClass();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ParentClass() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnClicked = new JButton("Clicked");
        btnClicked.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                Count++;
                System.out.println("Count = "+Count);
                if(Count==1)
                {
                    ChildClass obj=new ChildClass();
                    obj.ChildClassVisibility();
                }
            }
        });
        btnClicked.setBounds(150, 99, 89, 23);
        frame.getContentPane().add(btnClicked);
    }
}
</code>```

ChildClass:

```<code>import java.awt.EventQueue;

import javax.swing.JFrame;

public class ChildClass {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ChildClass window = new ChildClass();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ChildClass() {
        initialize();
    }

    public void ChildClassVisibility()
    {
        frame.setVisible(true);
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}
</code>```

Body:
i updated the code because many people doesn't understand so write a simple representation for that.
here is the problem whenever i clicked the button it open a new frame but i dont want this it does't open a new frame it remain open the same frame.

code for main frame :

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JavaProject2_27 {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JavaProject2_27 window = new JavaProject2_27();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public JavaProject2_27() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnClicked = new JButton("Clicked");
        btnClicked.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JavaProject2_28 obj=new JavaProject2_28();
                obj.getJavaProject2_28();
            }
        });
        btnClicked.setBounds(150, 99, 89, 23);
        frame.getContentPane().add(btnClicked);
    }
}

code for the second frame :

import java.awt.EventQueue;

import javax.swing.JFrame;

public class JavaProject2_28 {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JavaProject2_28 window = new JavaProject2_28();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public JavaProject2_28() {
        initialize();
    }

    public void getJavaProject2_28()
    {
        frame.setVisible(true);
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

snapshot

Body:
I solved It Please A look :
Parent Class:

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ParentClass {

    private JFrame frame;
    private int Count;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ParentClass window = new ParentClass();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ParentClass() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JButton btnClicked = new JButton("Clicked");
        btnClicked.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                Count++;
                System.out.println("Count = "+Count);
                if(Count==1)
                {
                    ChildClass obj=new ChildClass();
                    obj.ChildClassVisibility();
                }
            }
        });
        btnClicked.setBounds(150, 99, 89, 23);
        frame.getContentPane().add(btnClicked);
    }
}

ChildClass:

import java.awt.EventQueue;

import javax.swing.JFrame;

public class ChildClass {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ChildClass window = new ChildClass();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ChildClass() {
        initialize();
    }

    public void ChildClassVisibility()
    {
        frame.setVisible(true);
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}


问:
Get Android Google Analytics referrer tag
We're planning to use Google Analytics to track ad click-through referrals, through the Android Market, to our application.

According to the Google Documentation the referrer tag comes through via an intent, and is automatically recorded by the Google Analytics library.

That's great, but we need to extract that referral tag for our own internal analytics.  The documentation is shy on details about how to grab it out of the initial launch intent, and instructions on how to simulate this before going live.

Does anyone have experience with this?

答:
Check at:

Get referrer after installing app from Android Market

for the solutions.

Tobia


问:
Minifiying List of ranges as integer arrays
I have code like this

```<code>public List<int[]> getMinifiedRanges(List<int[]> ranges) {
    for (int[] range : ranges) {

    }
}
</code>```

My goal is to condense the list of ranges, represented by integer arrays which contain the ranges upper & lower bounds

ex. [100, 200] [250, 350] - this example would return the same input because nothing overlaps

[100, 200] [150, 350] [400, 500] - this would return [100, 350] [400, 500] because the second ranges lower bound is inclusive in the first range so the returned range would have its upper bound extended to 350 - notice how it returns only two arrays when the input was 3 arrays.

I am having trouble figuring out how to retrieve a previous range from a current range so that I could extend either the lower or upper bound.

答:
First blush, look for the places where the arrays stop intersecting. With this implementation you'll need to create the last range in the new, "merged" list...</p>

```<code>List<int[]> ranges = new ArrayList<>(); //holds the original list of ranges
int[] current;
int[] previous;
List<int[]> merged = new ArrayList<>(); //will end up with the merged ranges
int max = ranges.size() - 1;
int start = 0;
for (int i = 1; i <= max; i++) {
  previous = ranges.get(i-1);
  current = ranges.get(i);
  if (current[0] > previous[1]) {
    merged.add(new int[] {ranges.get(start)[0], previous[1]});
    start = i;
  }
}
merged.add(new int[] {ranges.get(start)[0], ranges.get(max)[1]});
</code>```

Body:
I have code like this

public List<int[]> getMinifiedRanges(List<int[]> ranges) {
    for (int[] range : ranges) {

    }
}

My goal is to condense the list of ranges, represented by integer arrays which contain the ranges upper & lower bounds

ex. [100, 200] [250, 350] - this example would return the same input because nothing overlaps

[100, 200] [150, 350] [400, 500] - this would return [100, 350] [400, 500] because the second ranges lower bound is inclusive in the first range so the returned range would have its upper bound extended to 350 - notice how it returns only two arrays when the input was 3 arrays.

I am having trouble figuring out how to retrieve a previous range from a current range so that I could extend either the lower or upper bound.

Body:
First blush, look for the places where the arrays stop intersecting. With this implementation you'll need to create the last range in the new, "merged" list...

List<int[]> ranges = new ArrayList<>(); //holds the original list of ranges
int[] current;
int[] previous;
List<int[]> merged = new ArrayList<>(); //will end up with the merged ranges
int max = ranges.size() - 1;
int start = 0;
for (int i = 1; i <= max; i++) {
  previous = ranges.get(i-1);
  current = ranges.get(i);
  if (current[0] > previous[1]) {
    merged.add(new int[] {ranges.get(start)[0], previous[1]});
    start = i;
  }
}
merged.add(new int[] {ranges.get(start)[0], ranges.get(max)[1]});


问:
Data channel in Edge Browser
Could someone help me with the following - is Data Channel supported by Edge browser? I can't find this with Edge while with all other browsers it is ok. I want to ensure data transfer (chat) directly browser to browser.

I would appreciate if someone could provide me with some guidance for this case.

答: WebRTC Data Channel support is currently under review for MS Edge. It's been that way for a while however with the recent announcement of WebRTC support in Safari 11 (including Data Channels) I suspect that this will spur MS to prioritize it in Edge.</p>

Title: Data channel in Edge Browser


问:
How to save as ArrayList<String>, all possible combinations of a set of characters in string?
How can I save as an ArrayList all possible combinations of a set of characters in string?

You can see my code below. It only print the combinations, but doesn't save all combinations. Any idea?

```<code>public class All_Possible_Combinatons
{

static String combinations(char[] sequence, char[] data, int start, int end,
        int index, int r)
{

    if (index == r)
    {
        for (int j = 0; j < r; j++)
            // = data[j];
            System.out.print(data[j] + " ");
        System.out.println();
    }

    for (int i = start; i <= end && ((end - i + 1) >= (r - index)); i++)
    {
        data[index] = sequence[i];
        combinations(sequence, data, i + 1, end, index + 1, r);
    }
    return null;

}

public static void main(String args[])
{
    char[] sequence = { '0','1','2'/*,'3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[',']','^','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' */};
    System.out.print("The combinations are: ");

  // printCombinations(sequence, sequence.length);

    int N=sequence.length;
    char[] data = new char[N];
    for (int r = 0; r < sequence.length; r++)
        combinations(sequence, data, 0, N - 1, 0, r);
}
</code>```

答:
This is may not be the effiecient one but give it a try:

```<code>List<String> list = new ArrayList<>();
    int[] a = {0,1,2};
    for(int i: a){
        list.add(i+"");
    }
    for(int times = 0; times < a.length; times++){
        String first = a[times]+"";

        for(int i = 0; i< a.length; i++){
            String temp = first + i;
            list.add(temp);
        }
    }
    for(String s: list){
        System.out.print(s + " ");
    }
</code>```

Output:

```<code>0 1 2 00 01 02 10 11 12 20 21 22
</code>```

Body:
How can I save as an ArrayList all possible combinations of a set of characters in string?

You can see my code below. It only print the combinations, but doesn't save all combinations. Any idea?

public class All_Possible_Combinatons
{

static String combinations(char[] sequence, char[] data, int start, int end,
        int index, int r)
{

    if (index == r)
    {
        for (int j = 0; j < r; j++)
            // = data[j];
            System.out.print(data[j] + " ");
        System.out.println();
    }

    for (int i = start; i <= end && ((end - i + 1) >= (r - index)); i++)
    {
        data[index] = sequence[i];
        combinations(sequence, data, i + 1, end, index + 1, r);
    }
    return null;

}

public static void main(String args[])
{
    char[] sequence = { '0','1','2'/*,'3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[',']','^','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' */};
    System.out.print("The combinations are: ");

  // printCombinations(sequence, sequence.length);

    int N=sequence.length;
    char[] data = new char[N];
    for (int r = 0; r < sequence.length; r++)
        combinations(sequence, data, 0, N - 1, 0, r);
}

Body:
This is may not be the effiecient one but give it a try:

List<String> list = new ArrayList<>();
    int[] a = {0,1,2};
    for(int i: a){
        list.add(i+"");
    }
    for(int times = 0; times < a.length; times++){
        String first = a[times]+"";

        for(int i = 0; i< a.length; i++){
            String temp = first + i;
            list.add(temp);
        }
    }
    for(String s: list){
        System.out.print(s + " ");
    }

Output:

0 1 2 00 01 02 10 11 12 20 21 22


问:
How to stop copyright theft of images?
Is there s a way for anti theft images? I'm not referring to web sites, what I want is if a JPEG is stolen it cannot be manipulated by the thief, only can be used by the owner.</p>

答: Even if you could come up with a protection scheme on the file itself, if the user can display it they only have to hit print screen to get a copy of the file they can work with.  Unless you control the computer used to view the file completely it's not possible.</p>

Title: How to stop copyright theft of images?


问:
How to make 0,0 on matplotlib graph on the bottom left corner?
I currently have a graph that looks like this using mathplotlib

However the margins between where the line actually starts and the edges of the graph are unnecessary, do you know how I can get rid of the margins so 0,0 starts at the corner?

For example, I want it to look like this

答:
```<code>plt.xlim([0, x_max])
plt.ylim([0, y_max])
</code>```

You can easily get the values of (x_max, y_max) from your data.

Body:
plt.xlim([0, x_max])
plt.ylim([0, y_max])

You can easily get the values of (x_max, y_max) from your data.


问:
Executing R file from bash script
I need to run the same R script over and over with different parameters for each run. I've written the R portion and it works. I'm trying to integrate this process with some other Java tools I've written that will need to use on the files changed by the R script. I'm therefore trying to run my R file from Java. I've tried to run it using the command line prompt: RScript TestR.R (this command works in terminal), but that didn't work. I am therefore in the process of trying to run my R script from a bash file. I am using the same command as above and my bash file can execute other commands but for some reason nothing happens when I try to run the R file. The java command I'm using is

```<code>Process proc = Runtime.getRuntime().exec("absolute-path/testbash.sh");
</code>```

I'm not sure what format of output to look for. Currently, this runs without any runtime errors.

UPDATE: when I checked the ErrorStream, it said "Rscript: command not found"

UPDATE: I figured it out by using "/usr/local/bin/RScript" as the command

答:
With simple R code I have found it easier to call RScript from the terminal, within Java, and parse the output of the R code. If you print whatever information you want in an easily parsed format this can work well.

For instance I will call a function like so in Java

```<code>private ArrayList<String> runCommand(String command)
{
    try
    {
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(command);

        BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(proc.getInputStream()));

        String lastReadLine = null;
        ArrayList<String> output = new ArrayList<>();
        while((lastReadLine = stdInput.readLine()) != null)
            output.add(lastReadLine);
        return output;
    }
    catch(Exception ex) { throw new RuntimeException("[RunCommand]: Exception when trying to execute command: " + ex.getMessage()); }
}
</code>```

with the argument \pathTo\RScript \pathTo\MyRCode.R and parse the resulting ArrayList<String> in Java to obtain whatever information the R code produced.

There are other ways to do this to. You could potentially write out some JSON file from the R code and return a path to this in the R code output, Java could then parse and read this file. Or you could use one of the many R-Java interop libraries out there (Just google).

Hope this helped.

Title: Executing R file from bash script

Body:
I need to run the same R script over and over with different parameters for each run. I've written the R portion and it works. I'm trying to integrate this process with some other Java tools I've written that will need to use on the files changed by the R script. I'm therefore trying to run my R file from Java. I've tried to run it using the command line prompt: RScript TestR.R (this command works in terminal), but that didn't work. I am therefore in the process of trying to run my R script from a bash file. I am using the same command as above and my bash file can execute other commands but for some reason nothing happens when I try to run the R file. The java command I'm using is

Process proc = Runtime.getRuntime().exec("absolute-path/testbash.sh");

I'm not sure what format of output to look for. Currently, this runs without any runtime errors.

UPDATE: when I checked the ErrorStream, it said "Rscript: command not found"

UPDATE: I figured it out by using "/usr/local/bin/RScript" as the command

Body:
With simple R code I have found it easier to call RScript from the terminal, within Java, and parse the output of the R code. If you print whatever information you want in an easily parsed format this can work well.

For instance I will call a function like so in Java

private ArrayList<String> runCommand(String command)
{
    try
    {
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(command);

        BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(proc.getInputStream()));

        String lastReadLine = null;
        ArrayList<String> output = new ArrayList<>();
        while((lastReadLine = stdInput.readLine()) != null)
            output.add(lastReadLine);
        return output;
    }
    catch(Exception ex) { throw new RuntimeException("[RunCommand]: Exception when trying to execute command: " + ex.getMessage()); }
}

with the argument \pathTo\RScript \pathTo\MyRCode.R and parse the resulting ArrayList<String> in Java to obtain whatever information the R code produced.

There are other ways to do this to. You could potentially write out some JSON file from the R code and return a path to this in the R code output, Java could then parse and read this file. Or you could use one of the many R-Java interop libraries out there (Just google).

Hope this helped.