问:
Excel Formula with OFFSET Fails When Copied to Different Sheet
I've been struggling with this longer than I care to admit, but I have a fairly simple OFFSET function call which works on one sheet, but if I copy it to a different sheet it gives a #VALUE error.

On a sheet named "Deliverable" I have this formula in a cell:

```<code>=OFFSET(Deliverable!$B$72,1,0,,3)
</code>```

and it works fine.

If I go to any other sheet and use the same exact formula, or use it in the Name Manager, it gives a #VALUE error.

If I leave off the final parameter indicated the number of columns I want, it does work:

```<code>=OFFSET(Deliverable!$B$72,1,0)
</code>```

but of course isn't giving me the range I need.

Any idea what's going on with this?

I'm using Excel 2016 on Windows 7.

-- Updated Info --
In a nutshell, my spreadsheet has two cells which I'm using as dropdown lists, where the 2nd cell's list feeds off the selection in the first.  The data they are based on has this format:

```<code>OptionA     A     B     C     D
OptionB     A     B
OptionC     D     E     F
</code>```

So the first dropdown uses a simple Data Validation source pointing to the column with OptionA, OptionB, etc.  Once that's chosen, the second dropdown list should contain the appropriate options for the one selected.  So if OptionB is selected, then the 2nd dropdown list should show A and B.

When I initially wrote this, the data validation source was just a simple VLOOKUP entry, but the lists often had blanks since the number of options varies for each entry.  Wanting to fix it up a bit, I ended up with this formula:
    =OFFSET(Deliverable!B72,Deliverable!B87,0,1,COUNTA(OFFSET(Deliverable!B72,Deliverable!B87,0,1,5)))

There won't be any more than 5 options, and there are no empty cells in the middle of the data to filter out.

In one spreadsheet I have I used this as a named range definition, then specified the named range for the cells data validation source and it worked.  In this other spreadsheet however, it gave me the error described earlier.

However, it looks like when I enter the statement directly into the data validation source field and not in the name manager, it works as expected.

Am I taking the totally wrong approach?

答:
What is it that you want this formula to do? As written, it is returning a block of three horizontal cells. The #VALUE error is Excel's way of telling you "Hey, you're trying to return three cells, but I can't fit them all in the one cell that you are calling this formula from".

The reason you see a result in some places and not others is because of something called Implicit Intersection. Give it a spin on Google. But basically, it just returns whichever one of those three results corresponds to the column that the formula is entered into. If you copy that exact same formula to say row F you will see that it returns a #VALUE error there, because it doesn't know what cell it should return given the column you're calling it from doesn't match any of the cells it is returning. The fact that you don't know this indicates that the formula you're using doesn't in fact do what you think it does.

--UPDATE --

Okay, following your further clarificaiton it seems that you're talking about Cascading Dropdowns aka Dynamic Dropdowns. Lots of info on Google about how to set these up, but you may be interested in an approach I blogged about sometime back that not only provides this functionality, but also ensures that someone can't later on go and change the 'upstream' dropdown without first clearing the 'downstream' one should they want to make a change.

Note that those links talk about a slightly complicated method compared to others, but the method has it's advantages in that it also handles more levels than two, and your DV lists are easily maintained as they live in an Excel Table.

Body:
I've been struggling with this longer than I care to admit, but I have a fairly simple OFFSET function call which works on one sheet, but if I copy it to a different sheet it gives a #VALUE error.

On a sheet named "Deliverable" I have this formula in a cell:

=OFFSET(Deliverable!$B$72,1,0,,3)

and it works fine.

If I go to any other sheet and use the same exact formula, or use it in the Name Manager, it gives a #VALUE error.

If I leave off the final parameter indicated the number of columns I want, it does work:

=OFFSET(Deliverable!$B$72,1,0)

but of course isn't giving me the range I need.

Any idea what's going on with this?

I'm using Excel 2016 on Windows 7.

-- Updated Info --
In a nutshell, my spreadsheet has two cells which I'm using as dropdown lists, where the 2nd cell's list feeds off the selection in the first.  The data they are based on has this format:

OptionA     A     B     C     D
OptionB     A     B
OptionC     D     E     F

So the first dropdown uses a simple Data Validation source pointing to the column with OptionA, OptionB, etc.  Once that's chosen, the second dropdown list should contain the appropriate options for the one selected.  So if OptionB is selected, then the 2nd dropdown list should show A and B.

When I initially wrote this, the data validation source was just a simple VLOOKUP entry, but the lists often had blanks since the number of options varies for each entry.  Wanting to fix it up a bit, I ended up with this formula:
    =OFFSET(Deliverable!B72,Deliverable!B87,0,1,COUNTA(OFFSET(Deliverable!B72,Deliverable!B87,0,1,5)))

There won't be any more than 5 options, and there are no empty cells in the middle of the data to filter out.

In one spreadsheet I have I used this as a named range definition, then specified the named range for the cells data validation source and it worked.  In this other spreadsheet however, it gave me the error described earlier.

However, it looks like when I enter the statement directly into the data validation source field and not in the name manager, it works as expected.

Am I taking the totally wrong approach?


来源: stackexchange

问:
Multithreading not working - Create thread per loop index Java
I wrote the below code trying to run two threads for calling a function in a for loop, but the results have the same time as if I ran it sequentially without multiple threads. Any thoughts why the multithreading here is not working? Is there a better way to do it? Like for example if I wanted to have 10 threads, using my code this will mean I have to create 10 duplicate run() functions when creating the thread, I wonder if there is an easier way to set the number of threads? Also is it possible to create a number of threads depending on the loop counter so that each loop a thread is created to finish it so if I had 10 loops then 10 threads will run concurrently to finish the processing very fast?</p>

```<code>   private Thread t1 = new Thread(){
   public void run(){

            for (int i = 0; i < 2; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    };

    private Thread t2 = new Thread(){
        public void run(){

            for (int i = 2; i < 4; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            }
    };

 public Results getResults() throws IOException, SocketTimeoutException {

        t1.start();
        t2.start();
        try {
            t1.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            t2.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
</code>```

答:
```<code>public class MyThead extend Thread{
    private int initValue = 0;
    private int upperBound = 0;

    public MyThread(int init, int ub){
        this.initValue = init;
        this.upperBound = ub;
    }
    public void run(){
        for(int i = init; i < upperBound; i++){
            myfn(i);
        }
    }
}
</code>```

Create threads and start them:

```<code>List<Thread> threads = new ArrayList<>();
threads.add(new MyThread(0,2));
threads.add(new MyThread(2,4));

for(Thread t: threads){
    t.start()
}

for(Thread t: threads){
    t.join();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wrote the below code trying to run two threads for calling a function in a for loop, but the results have the same time as if I ran it sequentially without multiple threads. Any thoughts why the multithreading here is not working? Is there a better way to do it? Like for example if I wanted to have 10 threads, using my code this will mean I have to create 10 duplicate run() functions when creating the thread, I wonder if there is an easier way to set the number of threads? Also is it possible to create a number of threads depending on the loop counter so that each loop a thread is created to finish it so if I had 10 loops then 10 threads will run concurrently to finish the processing very fast?

   private Thread t1 = new Thread(){
   public void run(){

            for (int i = 0; i < 2; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    };

    private Thread t2 = new Thread(){
        public void run(){

            for (int i = 2; i < 4; i++)
            {
                try {
                    myfn(i);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            }
    };

 public Results getResults() throws IOException, SocketTimeoutException {

        t1.start();
        t2.start();
        try {
            t1.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            t2.join(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

Body:
public class MyThead extend Thread{
    private int initValue = 0;
    private int upperBound = 0;

    public MyThread(int init, int ub){
        this.initValue = init;
        this.upperBound = ub;
    }
    public void run(){
        for(int i = init; i < upperBound; i++){
            myfn(i);
        }
    }
}

Create threads and start them:

List<Thread> threads = new ArrayList<>();
threads.add(new MyThread(0,2));
threads.add(new MyThread(2,4));

for(Thread t: threads){
    t.start()
}

for(Thread t: threads){
    t.join();
}


问:
ValueError: Variable rnn/basic_rnn_cell/kernel already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope?
Any ideas how can I solve problem shown below? With the information that I found on the web it is associated with problem of reusing tensorflow scope however nothing works.

ValueError: Variable rnn/basic_rnn_cell/kernel already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:

  File "/code/backend/management/commands/RNN.py", line 370, in predict
    states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32)
  File "/code/backend/management/commands/RNN.py", line 499, in Command
    predict("string")
  File "/code/backend/management/commands/RNN.py", line 12, in <module>
    class Command(BaseCommand):
```

<p>I tried for instance something like this</p>

<pre class="lang-python prettyprint-override"><code>with tf.variable_scope('scope'):
 states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32)
</code>```

and this

with tf.variable_scope('scope', reuse = True ):
 states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32)
```

<p>and this</p>

<pre class="lang-python prettyprint-override"><code>with tf.variable_scope('scope', reuse = tf.AUTO_REUSE ):
 states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32)
</code>```

Any ideas?

答:
Does this happen when you run the model for the first time (upon opening a new python console)?

If not, you need to clear you computational graph. You can do that by putting this line at the beginning of your script.

```<code>tf.reset_default_graph()
</code>```

Body:
Any ideas how can I solve problem shown below? With the information that I found on the web it is associated with problem of reusing tensorflow scope however nothing works.

ValueError: Variable rnn/basic_rnn_cell/kernel already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope? Originally defined at:

  File "/code/backend/management/commands/RNN.py", line 370, in predict
    states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32)
  File "/code/backend/management/commands/RNN.py", line 499, in Command
    predict("string")
  File "/code/backend/management/commands/RNN.py", line 12, in <module>
    class Command(BaseCommand):

I tried for instance something like this

with tf.variable_scope('scope'):
 states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32)

and this

with tf.variable_scope('scope', reuse = True ):
 states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32)

and this

with tf.variable_scope('scope', reuse = tf.AUTO_REUSE ):
 states_series, current_state = tf.nn.dynamic_rnn(cell=cell, inputs=batchX_placeholder, dtype=tf.float32)

Any ideas?

Body:
Does this happen when you run the model for the first time (upon opening a new python console)?

If not, you need to clear you computational graph. You can do that by putting this line at the beginning of your script.

tf.reset_default_graph()


问:
Swift 4: Cannot subscript a value of type 'String' with an index of type 'CountablePartialRangeFrom<Int>'
So I have this swift code:

```<code>func didReceiveResponse(response:String) {
  ...
  let substr = response[11...]
</code>```

By my interpretation, substr should be a Substring referencing all characters after index 11 in the response string.

What actually happens is this compiler error:

Cannot subscript a value of type 'String' with an index of type 'CountablePartialRangeFrom<Int>'

This seems like it should be obvious, can anyone help please?

答:
Whoops. Seems I needed to just do this:</p>

```<code>let idx = response.index(response.startIndex, offsetBy: 11)
let substr = response[idx...]
</code>```

Body:
So I have this swift code:

func didReceiveResponse(response:String) {
  ...
  let substr = response[11...]

By my interpretation, substr should be a Substring referencing all characters after index 11 in the response string.

What actually happens is this compiler error:

Cannot subscript a value of type 'String' with an index of type 'CountablePartialRangeFrom<Int>'

This seems like it should be obvious, can anyone help please?

Body:
Whoops. Seems I needed to just do this:

let idx = response.index(response.startIndex, offsetBy: 11)
let substr = response[idx...]


问:
django admin Model edit form - How to filter foreignkeys to only related models
I have an account model in django which has a foreignkey to Payment and a onetoone to Address.

In the Account section in the admin, I can edit a specific model and edit the fields payment and address via a select widget.  However how can I filter the options so that it only shows related models. (ie not every address or payment from every user, only the ones from that user).

The RelatedOnlyFieldListFilter seems to only apply to the model list view. Is there a way to use this in the model edit view?

答:
What you are probably looking for is call inlines. It allows you to edit related object directly in the parent model form which in this case would be the Account model. Here is an example of implementation:

```<code>class Account(models.Model):
    name = models.CharField(max_length=100)

class Payment(models.Model):
    account= models.ForeignKey(Account, on_delete=models.CASCADE)
    amount= models.CharField(max_length=100)

class Adress(models.Model):
    account= models.OneToOneField(Account, on_delete=models.CASCADE)
    adress= models.CharField(max_length=100):

class AccountAdmin(admin.ModelAdmin):
    inlines = [
        Paymentinline,
        Adressinline,
    ]
</code>```

Note that this is not a complete implementation (you will need to construct both inlines), follow the documentation on inlines for further information but above are the basics to it.

Body:
What you are probably looking for is call inlines. It allows you to edit related object directly in the parent model form which in this case would be the Account model. Here is an example of implementation:

class Account(models.Model):
    name = models.CharField(max_length=100)

class Payment(models.Model):
    account= models.ForeignKey(Account, on_delete=models.CASCADE)
    amount= models.CharField(max_length=100)

class Adress(models.Model):
    account= models.OneToOneField(Account, on_delete=models.CASCADE)
    adress= models.CharField(max_length=100):

class AccountAdmin(admin.ModelAdmin):
    inlines = [
        Paymentinline,
        Adressinline,
    ]

Note that this is not a complete implementation (you will need to construct both inlines), follow the documentation on inlines for further information but above are the basics to it.


问:
C# Which Event should I use to display data in a textbox when I select an item in a listbox?
C# Which Event should I use to display data in a textbox when I select an item in a listbox?

I want to select an item in a list box (winforms) and then a textbox near by show some data related to that item but I don't know which event to use. I'll need to be able to click down the list and watch the textbox text update with each click.

Thanks

答: SelectedIndexChanged</p>

OwnerDisplayName: Steve

ContentLicense: CC BY-SA 2.5

Body: SelectedIndexChanged

OwnerDisplayName: gkrogers


问:
Django: how to use custom manager in get_previous_by_FOO()?
I have a simple model MyModel with a date field named publication_date. I also have a custom manager that filters my model based on this date field.

This custom manager is accessible by .published and the default one by .objects.

```<code>from datetime import date, datetime
from django.db import models

class MyModelManager(models.Manager):
    def get_query_set(self):
        q = super(MyModelManager, self).get_query_set()
        return q.filter(publication_date__lte=datetime.now())

class MyModel(models.Model):
    ...
    publication_date = models.DateField(default=date.today())

    objects = models.Manager()
    published = MyModelManager()
</code>```

This way, I got access to all objects in the admin but only to published ones in my views (using MyModel.published.all() queryset).

I also have

```<code>def get_previous(self):
    return self.get_previous_by_publication_date()

def get_next(self):
    return self.get_next_by_publication_date()
</code>```

which I use in my templates: when viewing an object I can link to the previous and next object using

```<code>{{ object.get_previous }}
</code>```

The problem is: this returns the previous object in the default queryset (objects) and not in my custom one (published).

I wonder how I can do to tell to this basic model functions (get_previous_by_FOO) to use my custom manager.
Or, if it's not possible, how to do the same thing with another solution.

Thanks in advance for any advice.

Edit

The view is called this way in my urlconf, using object_detail from the generic views.

```<code>(r'^(?P<slug>[\w-]+)$', object_detail,
    {
     'queryset': MyModel.published.all(),
     'slug_field': 'slug',
    },
    'mymodel-detail'
),
</code>```

I'm using Django 1.2.

答:
In fact, get_next_or_previous_by_FIELD() Django function (which is used by get_previous_by_publication_date...) uses the default_manager.

So I have adapted it to reimplement my own utility function

```<code>def _own_get_next_or_previous_by_FIELD(self, field, is_next):
    if not self.pk:
        raise ValueError("get_next/get_previous cannot be used on unsaved objects.")
    op = is_next and 'gt' or 'lt'
    order = not is_next and '-' or ''
    param = smart_str(getattr(self, field.attname))
    q = Q(**{'%s__%s' % (field.name, op): param})
    q = q|Q(**{field.name: param, 'pk__%s' % op: self.pk})
    qs = MyModel.published.filter(q).order_by('%s%s' % (order, field.name), '%spk' % order)
    try:
        return qs[0]
    except IndexError:

def get_previous(self):
    return self._own_get_next_or_previous_by_FIELD(MyModel._meta.fields[4], False)

def get_next(self):
    return self._own_get_next_or_previous_by_FIELD(MyModel._meta.fields[4], True)
</code>```

This is not a very clean solution, as I need to hardcode the queryset and the field used, but at least it works.

Body:
I have a simple model MyModel with a date field named publication_date. I also have a custom manager that filters my model based on this date field.

This custom manager is accessible by .published and the default one by .objects.

from datetime import date, datetime
from django.db import models

class MyModelManager(models.Manager):
    def get_query_set(self):
        q = super(MyModelManager, self).get_query_set()
        return q.filter(publication_date__lte=datetime.now())

class MyModel(models.Model):
    ...
    publication_date = models.DateField(default=date.today())

    objects = models.Manager()
    published = MyModelManager()

This way, I got access to all objects in the admin but only to published ones in my views (using MyModel.published.all() queryset).

I also have

def get_previous(self):
    return self.get_previous_by_publication_date()

def get_next(self):
    return self.get_next_by_publication_date()

which I use in my templates: when viewing an object I can link to the previous and next object using

{{ object.get_previous }}

The problem is: this returns the previous object in the default queryset (objects) and not in my custom one (published).

I wonder how I can do to tell to this basic model functions (get_previous_by_FOO) to use my custom manager.
Or, if it's not possible, how to do the same thing with another solution.

Thanks in advance for any advice.

Edit

The view is called this way in my urlconf, using object_detail from the generic views.

(r'^(?P<slug>[\w-]+)$', object_detail,
    {
     'queryset': MyModel.published.all(),
     'slug_field': 'slug',
    },
    'mymodel-detail'
),

I'm using Django 1.2.

Body:
In fact, get_next_or_previous_by_FIELD() Django function (which is used by get_previous_by_publication_date...) uses the default_manager.

So I have adapted it to reimplement my own utility function

def _own_get_next_or_previous_by_FIELD(self, field, is_next):
    if not self.pk:
        raise ValueError("get_next/get_previous cannot be used on unsaved objects.")
    op = is_next and 'gt' or 'lt'
    order = not is_next and '-' or ''
    param = smart_str(getattr(self, field.attname))
    q = Q(**{'%s__%s' % (field.name, op): param})
    q = q|Q(**{field.name: param, 'pk__%s' % op: self.pk})
    qs = MyModel.published.filter(q).order_by('%s%s' % (order, field.name), '%spk' % order)
    try:
        return qs[0]
    except IndexError:

def get_previous(self):
    return self._own_get_next_or_previous_by_FIELD(MyModel._meta.fields[4], False)

def get_next(self):
    return self._own_get_next_or_previous_by_FIELD(MyModel._meta.fields[4], True)

This is not a very clean solution, as I need to hardcode the queryset and the field used, but at least it works.


问:
Python shell automatically load changes
I really love python because I love interactive development. There's one area where python appears to fall short, however, and that's in the area of automatically reloading changed files. Basically, what I want to have happen is to be able to modify a python file on-disk and then have my running python instance automatically reload the changed module to allow me to immediately access my changes in the REPL so I can test them out. Basically, I want some sort of watch command.

I happen to use the bpython shell because I think it's the best one available, but this feature is so important to me that I'd be willing to switch to any other python shell that does it right. Is it possible?

答:
If you're trying to "test out" your code, perhaps you should be looking into doing automated unit tests instead of testing your code repeatedly and manually. It'll allow you to test more code quicker and waste less of your precious, precious development time.

Personally, I use unittest with py.test as the runner.

Title: Python shell automatically load changes


问:
Decrypting openssl aes-256-cbc using node.js?
I'm encrypting my file on the command line using:

```<code>openssl aes-256-cbc -e -in test.env -out test.env.encrypted
</code>```

and then trying to decrypt on node.js with:

```<code>crypto    = require('crypto')
algorithm = 'aes-256-cbc'
password  = 'test'

fs = require 'fs'
decrypt = (text) ->
  decipher = crypto.createDecipher(algorithm, password)
  dec = decipher.update(text, 'hex', 'utf8')
  dec += decipher.final('utf8')
  dec

file = fs.readFileSync './test.env.encrypted', 'utf-8'

console.log decrypt file
</code>```

But i'm getting the following error:

```<code>TypeError: Bad input string at Decipher.update (crypto.js:168:26) at decrypt (/Users/h/tmp/encrypt_test/test.coffee:10:18) at Object.<anonymous> (/Users/h/tmp/encrypt_test/test.coffee:16:13) at Object.<anonymous> (/Users/h/tmp/encrypt_test/test.coffee:1:1) at Module._compile (module.js:569:30) at Object.CoffeeScript.run (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/index.js:63:23) at compileScript (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:265:29) at compilePath (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:220:14) at Object.exports.run (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:141:20) at Object.<anonymous> (/usr/local/lib/node_modules/coffeescript/bin/coffee:15:45) at Module._compile (module.js:569:30) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Function.Module.runMain (module.js:605:10) at startup (bootstrap_node.js:158:16) at bootstrap_node.js:575:3
</code>```

What am i doing wrong?

UPDATE:

As per James note i'm now sending a "hex" string to my decrypt function:

```<code>crypto    = require('crypto')
algorithm = 'aes-256-cbc'
password  = 'test'

fs = require 'fs'

decrypt = (text) ->
  decipher = crypto.createDecipher(algorithm, password)
  dec = decipher.update(text, 'hex', 'utf8')
  dec += decipher.final('utf8')
  dec

file = fs.readFileSync './test.env.encrypted'

console.log decrypt file.toString('hex')
</code>```

But then it's yielding a new error:

```<code>Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
    at Decipher.final (crypto.js:181:26)
    at decrypt (/Users/h/tmp/encrypt_test/test.coffee:12:19)
    at Object.<anonymous> (/Users/h/tmp/encrypt_test/test.coffee:17:13)
    at Object.<anonymous> (/Users/h/tmp/encrypt_test/test.coffee:1:1)
    at Module._compile (module.js:569:30)
    at Object.CoffeeScript.run (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/index.js:63:23)
    at compileScript (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:265:29)
    at compilePath (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:220:14)
    at Object.exports.run (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:141:20)
    at Object.<anonymous> (/usr/local/lib/node_modules/coffeescript/bin/coffee:15:45)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3
</code>```

File was encrypted using:

```<code>openssl aes-256-cbc -e -in test.env -out test.env.encrypted
</code>```

with

```<code>test
</code>```

as password

答:
Your call to decipher.update expects a hex encoded string but you're passing a utf-8 string.

Either change your readFileSync to read with hex encoding or change the update call to expect utf-8 input.

Body:
I'm encrypting my file on the command line using:

openssl aes-256-cbc -e -in test.env -out test.env.encrypted

and then trying to decrypt on node.js with:

crypto    = require('crypto')
algorithm = 'aes-256-cbc'
password  = 'test'

fs = require 'fs'
decrypt = (text) ->
  decipher = crypto.createDecipher(algorithm, password)
  dec = decipher.update(text, 'hex', 'utf8')
  dec += decipher.final('utf8')
  dec

file = fs.readFileSync './test.env.encrypted', 'utf-8'

console.log decrypt file

But i'm getting the following error:

TypeError: Bad input string at Decipher.update (crypto.js:168:26) at decrypt (/Users/h/tmp/encrypt_test/test.coffee:10:18) at Object.<anonymous> (/Users/h/tmp/encrypt_test/test.coffee:16:13) at Object.<anonymous> (/Users/h/tmp/encrypt_test/test.coffee:1:1) at Module._compile (module.js:569:30) at Object.CoffeeScript.run (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/index.js:63:23) at compileScript (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:265:29) at compilePath (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:220:14) at Object.exports.run (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:141:20) at Object.<anonymous> (/usr/local/lib/node_modules/coffeescript/bin/coffee:15:45) at Module._compile (module.js:569:30) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Function.Module.runMain (module.js:605:10) at startup (bootstrap_node.js:158:16) at bootstrap_node.js:575:3

What am i doing wrong?

UPDATE:

As per James note i'm now sending a "hex" string to my decrypt function:

crypto    = require('crypto')
algorithm = 'aes-256-cbc'
password  = 'test'

fs = require 'fs'

decrypt = (text) ->
  decipher = crypto.createDecipher(algorithm, password)
  dec = decipher.update(text, 'hex', 'utf8')
  dec += decipher.final('utf8')
  dec

file = fs.readFileSync './test.env.encrypted'

console.log decrypt file.toString('hex')

But then it's yielding a new error:

Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
    at Decipher.final (crypto.js:181:26)
    at decrypt (/Users/h/tmp/encrypt_test/test.coffee:12:19)
    at Object.<anonymous> (/Users/h/tmp/encrypt_test/test.coffee:17:13)
    at Object.<anonymous> (/Users/h/tmp/encrypt_test/test.coffee:1:1)
    at Module._compile (module.js:569:30)
    at Object.CoffeeScript.run (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/index.js:63:23)
    at compileScript (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:265:29)
    at compilePath (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:220:14)
    at Object.exports.run (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:141:20)
    at Object.<anonymous> (/usr/local/lib/node_modules/coffeescript/bin/coffee:15:45)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

File was encrypted using:

openssl aes-256-cbc -e -in test.env -out test.env.encrypted

with

test

as password


问:
what is this strange "script" doing?
I am doing some test then find below code would pop up a window:

```<code><a href="script:test">test</a>
</code>```

looks like it is trying to open an application.
Can anyone tell me what is the usage/purpose of this "script"?
looks like FF, Chrome, and IE all support it.

答: Trying to open an application? That script is just a hyperlink, it does not tell anything else in the script, just that it will open a link into site that tells "test"</p>

Title: what is this strange "script" doing?

Body:
I am doing some test then find below code would pop up a window:

test

looks like it is trying to open an application.
Can anyone tell me what is the usage/purpose of this "script"?
looks like FF, Chrome, and IE all support it.


问:
PIL ImageGrab to capture the selected window in Python
How can I use ImageGrab.grab()) in a specific manner to capture the selected window rather than the whole screen or boundary box?

For a better understanding, I am currently using this line below, which basically captures the given boundary box:

```<code>        screen =  np.array(ImageGrab.grab(bbox=(0,40,800,640)))
</code>```

Thanks!

答: After finding out of a package, called win32gui I have successfully solved this issue. Please refer to this link: Get window position & size with python</p>

Body:
How can I use ImageGrab.grab()) in a specific manner to capture the selected window rather than the whole screen or boundary box?

For a better understanding, I am currently using this line below, which basically captures the given boundary box:

        screen =  np.array(ImageGrab.grab(bbox=(0,40,800,640)))

Thanks!


问:
Smooth MultiPlayer movement
i am developing a multiplayer roleplaying game, (No, its not a mmorpg. ;)

My current setup is like this.

Client tells the server "I want to move forward"/"I want to move backwards", the server then updates your entity, and informs all clients in the area about the change. The server is also updating each entity every 20ms and sending updates every 100ms to the clients, these updates contains position, velocity, rotation etc.

So far so good, however i have nothing in store for smoothing the movement between the packets on the client side, and i must say, i can not get it working. I have been reading up on prediction, interpolation, deadreackoning but its all a big mess for me.

So right now i am just doing something like "Position = Packet.Position", which causes a very stuttering movement.

So, what i want help with is, how do i get a more smooth movement? Have been looking at the XNA Prediction Sample, but i could not get it right.

Thanks //F

答: Read Valve's description of their multiplayer protocol.  It should be instructive, and gives a very clear example on how you do the prediction/interpolation.</p>

Title: Smooth MultiPlayer movement


问:
Verilog error: not a valid l-value
I'm trying to test if a wire(s) is on or not to signify if there is an error/overflow in my alu code. Given  this code:

```<code>output reg[3:0]x;                       // line 149
output wire error;
output wire overflow;

always @* begin
    if(error || overflow) begin
        assign x = 4'b1111;             // line 155
        assign error = ~error;
        assign overflow = ~overflow;
    end else begin
        assign x = opcode;
    end
end
</code>```

I get following error messages:

uut is my instantiation unit in my testbench called main

答:
Your using the assign incorrectly.  That can be used outside of a always process, but not inside of one.

Also, the type wire, is required for an assign

```<code>wire [3:0] x;
assign x = 4'b1111;
</code>```

Inside the always process, remove the assign statement and just say

```<code>reg [3:0] x;  // Note that this is assigned as a reg now
 always @* begin
    if(blah) begin
       x = 4'b1111;
    end else begin
       x = opcode;
    end
 end
</code>```

Title: Verilog error: not a valid l-value

Body:
I'm trying to test if a wire(s) is on or not to signify if there is an error/overflow in my alu code. Given  this code:

output reg[3:0]x;                       // line 149
output wire error;
output wire overflow;

always @* begin
    if(error || overflow) begin
        assign x = 4'b1111;             // line 155
        assign error = ~error;
        assign overflow = ~overflow;
    end else begin
        assign x = opcode;
    end
end

I get following error messages:

uut is my instantiation unit in my testbench called main

Body:
Your using the assign incorrectly.  That can be used outside of a always process, but not inside of one.

Also, the type wire, is required for an assign

wire [3:0] x;
assign x = 4'b1111;

Inside the always process, remove the assign statement and just say

reg [3:0] x;  // Note that this is assigned as a reg now
 always @* begin
    if(blah) begin
       x = 4'b1111;
    end else begin
       x = opcode;
    end
 end


问:
accepts_nested_attributes_for keeps form fields from showing
When I use accepts_nested_attributes_for the corresponding fields no longer show in my view.

```<code>class Survey < ActiveRecord::Base
  has_many :questions
  accepts_nested_attributes_for :questions
end

class Question < ActiveRecord::Base
  belongs_to :survey
end
</code>```

Then in my view:

```<code><%= form_for @survey do |f| %>
  <%= f.fields_for :questions do |question_fields| %>
    <%= question_fields.text_area :text %>
  <% end %>
<% end %>
</code>```

If I remove accepts_nested_attributes_for then the text_area shows, but if I keep it...nothing gets renders.

I'm running Rails 3.0.3

答:
Did you build the questions , in the controller ?

Something like

 @survey.questions.build

This builds one related question, so only one text area will show up. run it in a loop like

 2.times { @survey.questions.build }

It will appear 2 times.

Body:
When I use accepts_nested_attributes_for the corresponding fields no longer show in my view.

class Survey < ActiveRecord::Base
  has_many :questions
  accepts_nested_attributes_for :questions
end

class Question < ActiveRecord::Base
  belongs_to :survey
end

Then in my view:

<%= form_for @survey do |f| %>
  <%= f.fields_for :questions do |question_fields| %>
    <%= question_fields.text_area :text %>
  <% end %>
<% end %>

If I remove accepts_nested_attributes_for then the text_area shows, but if I keep it...nothing gets renders.

I'm running Rails 3.0.3


问:
Check javascript compatibility with Internet explorer
I have some javascript code that does not run in IE 11. Is there a quick way to check where the incompatibly is other than going through the code line by line to see what commands and statements are supported by that version of Internet Explorer?</p>

答:
I don't remember an "online code checking", but the most similar maybe are this two websites, can I use? and for Ecmascript.

Hope it helps!


问:
Appium cannot find view elements with it's accessibilityId's
I'm using Appium (Mobile App Automation for Testing) to test an iOS app.
Appium finds view on to test by accessibility identifier but when I run test with appium app (inspector) it only sees the view elements with image and it declare image names as accessibility elements though I set all view elements accessibility id's programmatically.

What can I do instead of findingViewByXpath?

答: The issue is, you have to run your project on Simulator or on device after you set view elements accessibilityId's. Just build project is not enough to update changes on Appium side.</p>


问:
Rank based on row number SQL Server 2008 R2
I want to group rank my table data by rowcount.  First 12 rows that are ordered by date for each ProductID would get value = 1.  Next 12 rows would get value = 2 assigned and so on.

How table structure looks:

```<code>For ProductID = 1267 are below associated dates:
02-01-2016
03-01-2016
.
. (skipping months..table has one date per month)
.
12-01-2016
02-01-2017
.
.
.
02-01-2018
</code>```

Body:
I want to group rank my table data by rowcount.  First 12 rows that are ordered by date for each ProductID would get value = 1.  Next 12 rows would get value = 2 assigned and so on.

How table structure looks:

For ProductID = 1267 are below associated dates:
02-01-2016
03-01-2016
.
. (skipping months..table has one date per month)
.
12-01-2016
02-01-2017
.
.
.
02-01-2018

Body:
Use row_number() over() with some arithmetic to calculate groups of 12 ordered by date (per productid). Change the sort to ASCendng or DESCendng to suit your need.

select *
, (11 + row_number() over(partition by productid order by somedate DESC)) / 12 as rnk
from mytable
GO

myTableID | productid      | somedate            | rnk
--------: | :------------- | :------------------ | :--
        9 | 123456         | 2018-11-12 08:24:25 | 1
        8 | 123456         | 2018-10-02 12:29:04 | 1
        7 | 123456         | 2018-09-09 02:39:30 | 1
        2 | 123456         | 2018-09-02 08:49:37 | 1
        1 | 123456         | 2018-07-04 12:25:06 | 1
        5 | 123456         | 2018-06-06 11:38:50 | 1
       12 | 123456         | 2018-05-23 21:12:03 | 1
       18 | 123456         | 2018-04-02 03:59:16 | 1
        3 | 123456         | 2018-01-02 03:42:24 | 1
       17 | 123456         | 2017-11-29 03:19:32 | 1
       10 | 123456         | 2017-11-10 00:45:41 | 1
       13 | 123456         | 2017-11-05 09:53:38 | 1
       16 | 123456         | 2017-10-20 15:39:42 | 2
        4 | 123456         | 2017-10-14 19:25:30 | 2
       20 | 123456         | 2017-09-21 21:31:06 | 2
        6 | 123456         | 2017-04-06 22:10:58 | 2
       14 | 123456         | 2017-03-24 23:35:52 | 2
       19 | 123456         | 2017-01-22 05:07:23 | 2
       11 | 123456         | 2016-12-13 19:17:08 | 2
       15 | 123456         | 2016-12-02 03:22:32 | 2

dbfiddle here


问:
Using matplotlib to plot a distribution of time occurrences. I would like the x axis to have hours (12:00 PM) rather than integers (12)
Here's my plot, which is generated using the following code:

```<code>bins = np.linspace(0,24,25)
plt.hist(hours,bins, edgecolor='black', linewidth = 1.2, color = 'red')
</code>```

I would like the x axis to show 24 entries, from 12:00AM to 11:00 PM ideally rotated left 90 degrees.

I see two paths: convert the actual data to time values so the histogram reads in time values or simply add a custom x axis with 12:00AM, 1:00 AM, etc. What's the easiest / cleanest approach here? I'm not familiar with how to do either. For reference, "hours" is a int64 array.

答:
Here's a working example:

```<code>import numpy as np
import matplotlib.pyplot as plt

bins = np.arange(0,25)
hours = np.random.rand(50)*25

fig, ax = plt.subplots()

labels = []
for i in bins:
    if i<12:
        labels.append("{}:00AM".format(i))
    elif i == 12:
        labels.append("12:00PM")
    else:
        labels.append("{}:00PM".format(i-12))

ax.hist(hours, bins)
ax.set_xticks(bins + 0.5) # 0.5 is half of the "1" auto width
ax.set_xticklabels(labels, rotation='vertical')
fig.subplots_adjust(bottom = 0.2) # makes space for the vertical
                                  #labels.
plt.show()
</code>```

which gives:

I've changed the linspace to arange as it returns integers

Body:
Here's my plot, which is generated using the following code:

bins = np.linspace(0,24,25)
plt.hist(hours,bins, edgecolor='black', linewidth = 1.2, color = 'red')

I would like the x axis to show 24 entries, from 12:00AM to 11:00 PM ideally rotated left 90 degrees.

I see two paths: convert the actual data to time values so the histogram reads in time values or simply add a custom x axis with 12:00AM, 1:00 AM, etc. What's the easiest / cleanest approach here? I'm not familiar with how to do either. For reference, "hours" is a int64 array.

Body:
Here's a working example:

import numpy as np
import matplotlib.pyplot as plt

bins = np.arange(0,25)
hours = np.random.rand(50)*25

fig, ax = plt.subplots()

labels = []
for i in bins:
    if i<12:
        labels.append("{}:00AM".format(i))
    elif i == 12:
        labels.append("12:00PM")
    else:
        labels.append("{}:00PM".format(i-12))

ax.hist(hours, bins)
ax.set_xticks(bins + 0.5) # 0.5 is half of the "1" auto width
ax.set_xticklabels(labels, rotation='vertical')
fig.subplots_adjust(bottom = 0.2) # makes space for the vertical
                                  #labels.
plt.show()

which gives:

I've changed the linspace to arange as it returns integers


问:
strange issue with jQuery
I have a very strange issue with jQuery.

The problem:

```<code>$("#button-prev").attr("disabled", "disabled");
</code>```

This doesn't work. If I check with Firebug I see disabled="" as element attribute

But for example this

```<code>$("#button-prev").attr("disablea", "disabled");
</code>```

works as you should expect. Anyone an idea what it could be?

答:
In plain ol' JavaScript, it's a simple as

```<code>document.getElementById('button-prev').disabled = true;
</code>```

This is one of the few occassions where I think it would be easier not to use jQuery

Title: strange issue with jQuery

Body:
I have a very strange issue with jQuery.

The problem:

$("#button-prev").attr("disabled", "disabled");

This doesn't work. If I check with Firebug I see disabled="" as element attribute

But for example this

$("#button-prev").attr("disablea", "disabled");

works as you should expect. Anyone an idea what it could be?

Body:
In plain ol' JavaScript, it's a simple as

document.getElementById('button-prev').disabled = true;

This is one of the few occassions where I think it would be easier not to use jQuery


问:
Racket pattern matching of lists
I am trying to do pattern matching with lists, but for some reason I get an unexpected match when I do the following:

```<code>> (define code '(h1 ((id an-id-here)) Some text here))
> (define code-match-expr '(pre ([class brush: python]) ...))
> (match code
    [code-match-expr #t]
    [_ #f])
#t
</code>```

Question: Why does code match code-match-expr?

Practical use-case

I tried this in the Racket REPL, because I actually want to solve another practical problem: using Pollen's pygments wrapping functions to highlight code, which will be output as HTML later on. For this purpose I wrote the following code, where the problem occurs:

```<code>(define (read-post-from-file path)
  (Post-from-content (replace-code-xexprs (parse-markdown path))))

(define (replace-code-xexprs list-of-xexprs)
  ;; define known languages
  (define KNOWN-LANGUAGE-SYMBOLS
    (list 'python
          'racket
          'html
          'css
          'javascript
          'erlang
          'rust))
  ;; check if it matches for a single language's match expression
  ;; if it mathces any language, return that language's name as a symbol
  (define (get-matching-language an-xexpr)
    (define (matches-lang-match-expr? an-xexpr lang-symbol)
      (display "XEXPR:") (displayln an-xexpr)
      (match an-xexpr
        [`(pre ([class brush: ,lang-symbol]) (code () ,more ...)) lang-symbol]
        [`(pre ([class brush: ,lang-symbol]) ,more ...) lang-symbol]
        [_ #f]))

    (ormap (lambda (lang-symbol)
             ;; (display "trying to match ")
             ;; (display an-xexpr)
             ;; (display " against ")
             ;; (displayln lang-symbol)
             (matches-lang-match-expr? an-xexpr lang-symbol))
           KNOWN-LANGUAGE-SYMBOLS))

  ;; replace code in an xexpr with highlightable code
  ;; TODO: What happens if the code is in a lower level of the xexpr?
  (define (replace-code-in-single-xexpr an-xexpr)
    (let ([matching-language (get-matching-language an-xexpr)])
      (cond [matching-language (code-highlight an-xexpr matching-language)]
            [else an-xexpr])))

  ;; apply the check to all xexpr
  (map replace-code-in-single-xexpr list-of-xexprs))

(define (code-highlight language code)
  (highlight language code))
</code>```

In this example I am parsing a markdown file which has the following content:

```<code># Code Demo

```python
def hello():
    print("Hello World!")
```
</code>```

And I get the following xexprs:

1.

```<code>(h1 ((id code-demo)) Code Demo)
</code>```

2.

```<code>(pre ((class brush: python)) (code () def hello():
    print("Hello World!")))
</code>```

However, none of those match for some reason.

答:
match is syntax and does not evaluate the pattern. Since code-match-expr is a symbol it will bind the whole expression (result of evaluating code) to the variable code-match-expr and evaluate the rest of the expressions as the pattern matches. The result will always be #t.

Notice that the second pattern, the symbol _, is the same pattern. It also matches the whole expression, but _ is special in the way that it does not get bound like code-match-expr does.

It's important that your defined variable code-match-expr is never used, but since the match binds a variable with the same name your original binding will be shadowed in the consequent of the match.

Code that works as you intended might look like:

(define (test code)
  (match code
    [`(pre ([class brush: python]) ,more ...) #t]
    [_ #f]))

(test '(h1 ((id an-id-here)) Some text here))
; ==> #f

(test '(pre ((class brush: python))))
; ==> #t

(test '(pre ((class brush: python)) a b c))
; ==> #t
```

<p>As you see the pattern <code>,more ...</code> means <strong>zero or more</strong> and what kind of brackets is ignored since in Racket <code>[]</code> is the same as <code>()</code> and <code>{}</code>.</p>

<p><strong>EDIT</strong></p>

<p>You still got it a little backwards. In this code:</p>

```(define (matches-lang-match-expr? an-xexpr lang-symbol)
  (display "XEXPR:") (displayln an-xexpr)
  (match an-xexpr
    [`(pre ([class brush: ,lang-symbol]) (code () ,more ...)) lang-symbol]
    [`(pre ([class brush: ,lang-symbol]) ,more ...) lang-symbol]
    [_ #f]))
```

<p>When a pattern is macthed, since <code>lang-symbol</code> is unquoted it will match <strong>anything</strong> atomic and be bound to that as a variable in that clause. It will have <strong>nothing</strong> to do with the bound variable by the same name as a <code>match</code> does not use variables, it creates them. You return the variable. Thus:</p>

```(matches-lang-match-expr? '(pre ([class brush: jiffy]) bla bla bla) 'ignored-argument)
; ==> jiffy
```

<p>Here is something that does what you want:</p>

``` (define (get-matching-language an-xexpr)
    (define (get-language an-xexpr)
      (match an-xexpr
        [`(pre ([class brush: ,lang-symbol]) (code () ,more ...)) lang-symbol]
        [`(pre ([class brush: ,lang-symbol]) ,more ...) lang-symbol]
        [_ #f]))
    (let* ((matched-lang-symbol (get-language an-xexpr))
           (in-known-languages (memq matched-lang-symbol KNOWN-LANGUAGE-SYMBOLS)))
      (and in-known-languages (car in-known-languages))))
```

Again.. match abuses quasiquote to something completely different than creating list structure. It uses them to match literals and capture the unqoted  symbols as variables.

Title: Racket pattern matching of lists

Body:
I am trying to do pattern matching with lists, but for some reason I get an unexpected match when I do the following:

> (define code '(h1 ((id an-id-here)) Some text here))
> (define code-match-expr '(pre ([class brush: python]) ...))
> (match code
    [code-match-expr #t]
    [_ #f])
#t

Question: Why does code match code-match-expr?

Practical use-case

I tried this in the Racket REPL, because I actually want to solve another practical problem: using Pollen's pygments wrapping functions to highlight code, which will be output as HTML later on. For this purpose I wrote the following code, where the problem occurs:

(define (read-post-from-file path)
  (Post-from-content (replace-code-xexprs (parse-markdown path))))

(define (replace-code-xexprs list-of-xexprs)
  ;; define known languages
  (define KNOWN-LANGUAGE-SYMBOLS
    (list 'python
          'racket
          'html
          'css
          'javascript
          'erlang
          'rust))
  ;; check if it matches for a single language's match expression
  ;; if it mathces any language, return that language's name as a symbol
  (define (get-matching-language an-xexpr)
    (define (matches-lang-match-expr? an-xexpr lang-symbol)
      (display "XEXPR:") (displayln an-xexpr)
      (match an-xexpr
        [`(pre ([class brush: ,lang-symbol]) (code () ,more ...)) lang-symbol]
        [`(pre ([class brush: ,lang-symbol]) ,more ...) lang-symbol]
        [_ #f]))

    (ormap (lambda (lang-symbol)
             ;; (display "trying to match ")
             ;; (display an-xexpr)
             ;; (display " against ")
             ;; (displayln lang-symbol)
             (matches-lang-match-expr? an-xexpr lang-symbol))
           KNOWN-LANGUAGE-SYMBOLS))

  ;; replace code in an xexpr with highlightable code
  ;; TODO: What happens if the code is in a lower level of the xexpr?
  (define (replace-code-in-single-xexpr an-xexpr)
    (let ([matching-language (get-matching-language an-xexpr)])
      (cond [matching-language (code-highlight an-xexpr matching-language)]
            [else an-xexpr])))

  ;; apply the check to all xexpr
  (map replace-code-in-single-xexpr list-of-xexprs))

(define (code-highlight language code)
  (highlight language code))

In this example I am parsing a markdown file which has the following content:

# Code Demo

```python
def hello():
    print("Hello World!")
```

And I get the following xexprs:

1.

(h1 ((id code-demo)) Code Demo)

2.

(pre ((class brush: python)) (code () def hello():
    print("Hello World!")))

However, none of those match for some reason.

Body:
match is syntax and does not evaluate the pattern. Since code-match-expr is a symbol it will bind the whole expression (result of evaluating code) to the variable code-match-expr and evaluate the rest of the expressions as the pattern matches. The result will always be #t.

Notice that the second pattern, the symbol _, is the same pattern. It also matches the whole expression, but _ is special in the way that it does not get bound like code-match-expr does.

It's important that your defined variable code-match-expr is never used, but since the match binds a variable with the same name your original binding will be shadowed in the consequent of the match.

Code that works as you intended might look like:

(define (test code)
  (match code
    [`(pre ([class brush: python]) ,more ...) #t]
    [_ #f]))

(test '(h1 ((id an-id-here)) Some text here))
; ==> #f

(test '(pre ((class brush: python))))
; ==> #t

(test '(pre ((class brush: python)) a b c))
; ==> #t

As you see the pattern ,more ... means zero or more and what kind of brackets is ignored since in Racket [] is the same as () and {}.

EDIT

You still got it a little backwards. In this code:

(define (matches-lang-match-expr? an-xexpr lang-symbol)
  (display "XEXPR:") (displayln an-xexpr)
  (match an-xexpr
    [`(pre ([class brush: ,lang-symbol]) (code () ,more ...)) lang-symbol]
    [`(pre ([class brush: ,lang-symbol]) ,more ...) lang-symbol]
    [_ #f]))

When a pattern is macthed, since lang-symbol is unquoted it will match anything atomic and be bound to that as a variable in that clause. It will have nothing to do with the bound variable by the same name as a match does not use variables, it creates them. You return the variable. Thus:

(matches-lang-match-expr? '(pre ([class brush: jiffy]) bla bla bla) 'ignored-argument)
; ==> jiffy

Here is something that does what you want:

 (define (get-matching-language an-xexpr)
    (define (get-language an-xexpr)
      (match an-xexpr
        [`(pre ([class brush: ,lang-symbol]) (code () ,more ...)) lang-symbol]
        [`(pre ([class brush: ,lang-symbol]) ,more ...) lang-symbol]
        [_ #f]))
    (let* ((matched-lang-symbol (get-language an-xexpr))
           (in-known-languages (memq matched-lang-symbol KNOWN-LANGUAGE-SYMBOLS)))
      (and in-known-languages (car in-known-languages))))

Again.. match abuses quasiquote to something completely different than creating list structure. It uses them to match literals and capture the unqoted  symbols as variables.


问:
NPM Invalid Package during deployment found @types
I'm trying to run my first application with azure's continuous development, this is app from standard template from Visual Studio 2017 MVC net core 2.0, using React. I just pushed this app to my github, on branch configured with azure to auto deploy, and deploy log i can see this:

```<code>Command: "D:\home\site\deployments\tools\deploy.cmd"
Handling ASP.NET Core Web Application deployment.
  Restore completed in 680.87 ms for D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj.
  Restore completed in 1.08 sec for D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj.
Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  PortfolioKJ -> D:\home\site\repository\PortfolioKJ\bin\Release\netcoreapp2.0\PortfolioKJ.dll
EXEC : npm ERR! error : Invalid Package: expected types/react-hot-loader but found @types/react-hot-loader [D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj]
  npm ERR!     at D:\Program Files (x86)\npm\1.4.28\node_modules\npm\lib\cache\add-local-tarball.js:161:14
  npm ERR!     at process._tickCallback (node.js:448:13)
  npm ERR! If you need help, you may report this *entire* log,
  npm ERR! including the npm and node versions, at:
  npm ERR!     <http://github.com/npm/npm/issues>

  npm ERR! System Windows_NT 6.2.9200
  npm ERR! command "node" "D:\\Program Files (x86)\\npm\\1.4.28\\node_modules\\npm\\bin\\npm-cli.js" "install"
  npm ERR! cwd D:\home\site\repository\PortfolioKJ
  npm ERR! node -v v0.10.40
  npm ERR! npm -v 1.4.28
  npm
D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj(39,5): error MSB3073: The command "npm install" exited with code 1.
Failed exitCode=1, command=dotnet publish "D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj" --output "D:\local\Temp\8d52bb32bb3bc7e" --configuration Release
An error has occurred during web site deployment.
\r\nD:\Program Files (x86)\SiteExtensions\Kudu\67.61109.3117\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd"
</code>```

I realy don't know what i can do now. I was hoping that if everything is standard, it could run without issues.

Here is tsconfig.json

```<code>{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "jsx": "react",
    "experimentalDecorators": true,
    "sourceMap": true,
    "skipDefaultLibCheck": true,
    "strict": true,
    "lib": ["es6", "dom"],
    "types": ["webpack-env"]
  },
  "exclude": [
      "bin",
      "node_modules"
  ]
}
</code>```

On my local PC everything works great.

答:
Focus in on the error message:

Invalid Package: expected types/react-hot-loader but found @types/react-hot-loader

This will happen if you have types/react-hot-loader was mentioned in some package.json.

Fix

Make sure all references to types are prefixed with @ i.e. @types. Obvious place to check is package.json for simple JavaScript / TypeScript projects

More

Since you are using ASP.Net build tooling you might need to fiddle with msbuild / proj files. If not, there might be a bug in the template or azure auto deploy code.

Body:
I'm trying to run my first application with azure's continuous development, this is app from standard template from Visual Studio 2017 MVC net core 2.0, using React. I just pushed this app to my github, on branch configured with azure to auto deploy, and deploy log i can see this:

Command: "D:\home\site\deployments\tools\deploy.cmd"
Handling ASP.NET Core Web Application deployment.
  Restore completed in 680.87 ms for D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj.
  Restore completed in 1.08 sec for D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj.
Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  PortfolioKJ -> D:\home\site\repository\PortfolioKJ\bin\Release\netcoreapp2.0\PortfolioKJ.dll
EXEC : npm ERR! error : Invalid Package: expected types/react-hot-loader but found @types/react-hot-loader [D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj]
  npm ERR!     at D:\Program Files (x86)\npm\1.4.28\node_modules\npm\lib\cache\add-local-tarball.js:161:14
  npm ERR!     at process._tickCallback (node.js:448:13)
  npm ERR! If you need help, you may report this *entire* log,
  npm ERR! including the npm and node versions, at:
  npm ERR!     <http://github.com/npm/npm/issues>

  npm ERR! System Windows_NT 6.2.9200
  npm ERR! command "node" "D:\\Program Files (x86)\\npm\\1.4.28\\node_modules\\npm\\bin\\npm-cli.js" "install"
  npm ERR! cwd D:\home\site\repository\PortfolioKJ
  npm ERR! node -v v0.10.40
  npm ERR! npm -v 1.4.28
  npm
D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj(39,5): error MSB3073: The command "npm install" exited with code 1.
Failed exitCode=1, command=dotnet publish "D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj" --output "D:\local\Temp\8d52bb32bb3bc7e" --configuration Release
An error has occurred during web site deployment.
\r\nD:\Program Files (x86)\SiteExtensions\Kudu\67.61109.3117\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd"

I realy don't know what i can do now. I was hoping that if everything is standard, it could run without issues.

Here is tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "jsx": "react",
    "experimentalDecorators": true,
    "sourceMap": true,
    "skipDefaultLibCheck": true,
    "strict": true,
    "lib": ["es6", "dom"],
    "types": ["webpack-env"]
  },
  "exclude": [
      "bin",
      "node_modules"
  ]
}

On my local PC everything works great.


问:
How to Create a Unique Int for Each Person Added
I am working on an app right now where a person will be able to add different people to a list and then reuse those people. After they select a person, they can move on to a screen where you check a bunch of boxes such as "carrot" or "potato". Each person that is added needs to have a unique "carrot" or "potato" int so it can be used later to count up all the amount of times that carrot or potato has been checked off.

How do I go about doing the int creating whenever a new person is added? I know what to do from there but I honestly have no idea what to do about this.

So if I have a person created named "nick" I can create an int called "carrotnick". I need that id to be displayed later on without me knowing that there is a nick on the end, only the carrot part. So it can't be completely random. Still needs to be displayed later on somehow.

答: Use sqlite and a table with auto incremental field so for each person which be added to table there is a unique id so you can either get ids after app restarted </p>


问:
Broken Javascript Code
I'm trying to create a website where three things happen, but I am stuck.

(1) When the button “ADD” button is clicked it will create a new paragraph
and add it to the  output. The contents of the paragraph should come from the text area that is below the [ADD] button.

(2) If the “delete” button is pressed I need to delete the first paragraph in the div.

(3) If the user tries to delete when there are no paragraphs, create an “alert" that says:"No Paragraphs to delete".

I got my JS to put each paragraph into the div, but I'm not really sure how to delete it... Any help would be much appreciated.

window.onload = function() {
  var button = document.getElementById("add");
  button.onclick = insertItem;
}

function insertItem() {
  var added = document.getElementById("output");
  var textToAdd = document.getElementById("input");
  if (textToAdd.value != "") {
    var newp = document.createElement("p");
    newp.innerHTML = textToAdd.value;
    added.appendChild(newp);
  }
}

var deletebutton = document.getElementsByTagName("delete");
deletebutton.onclick = deleteItem;

function deleteItem() {
  var output = document.getElementById("output");
  var pars = output.getElementsByTagName("p");
  if (pars.length > 0) {
    output.removeChild(pars[0]);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#output {
  border: blue 5px solid;
  padding: 10px;
  margin-bottom: 10px;
  margin-top: 10px;
  width: 50%;
}

#output p {
  padding: 10px;
  border: black 1px dashed;
}</code>```

 TASK 3 - Creating, Appending and Deleting Nodes in the DOM Tree

 Type in text below, click add to add as paragraph. <button id="add"> Add </button>

  <textarea id="input" rows="10" cols="60">
    </textarea>

  <button id="delete">Delete Last Paragraph</button>

 Added Paragraphs

```

答:
You're fetching the delete button wrong. You're using getElementsByTagName instead of by id.

When deleting, you will probably delete the first
 you have in your markup that doesnt belong to your output. To fix this you could simply fetch all children of your output div and remove the first one:

```<code>function deleteItem() {
    let output = document.getElementById('output')
    if (output.hasChildNodes()) {
        let outputs = output.childNodes
        outputs[0].remove()
    }
}
</code>```

Title: Broken Javascript Code

Body:
I'm trying to create a website where three things happen, but I am stuck.

(1) When the button “ADD” button is clicked it will create a new paragraph
and add it to the  output. The contents of the paragraph should come from the text area that is below the [ADD] button.

(2) If the “delete” button is pressed I need to delete the first paragraph in the div.

(3) If the user tries to delete when there are no paragraphs, create an “alert" that says:"No Paragraphs to delete".

I got my JS to put each paragraph into the div, but I'm not really sure how to delete it... Any help would be much appreciated.

window.onload = function() {
  var button = document.getElementById("add");
  button.onclick = insertItem;
}

function insertItem() {
  var added = document.getElementById("output");
  var textToAdd = document.getElementById("input");
  if (textToAdd.value != "") {
    var newp = document.createElement("p");
    newp.innerHTML = textToAdd.value;
    added.appendChild(newp);
  }
}

var deletebutton = document.getElementsByTagName("delete");
deletebutton.onclick = deleteItem;

function deleteItem() {
  var output = document.getElementById("output");
  var pars = output.getElementsByTagName("p");
  if (pars.length > 0) {
    output.removeChild(pars[0]);
  }
}

#output {
  border: blue 5px solid;
  padding: 10px;
  margin-bottom: 10px;
  margin-top: 10px;
  width: 50%;
}

#output p {
  padding: 10px;
  border: black 1px dashed;
}

 TASK 3 - Creating, Appending and Deleting Nodes in the DOM Tree

 Type in text below, click add to add as paragraph. <button id="add"> Add </button>

  <textarea id="input" rows="10" cols="60">
    </textarea>

  <button id="delete">Delete Last Paragraph</button>

 Added Paragraphs

Body:
You're fetching the delete button wrong. You're using getElementsByTagName instead of by id.

When deleting, you will probably delete the first <p> you have in your markup that doesnt belong to your output. To fix this you could simply fetch all children of your output div and remove the first one:

function deleteItem() {
    let output = document.getElementById('output')
    if (output.hasChildNodes()) {
        let outputs = output.childNodes
        outputs[0].remove()
    }
}


问:
Rename columns using function input in dplyr
I know there are many similar questions regarding renaming columns in R, but I still have not found an elegant way to achieve this simple task, which can be easily done in Python.

Here is a simple function to convert GIS dataframe into Spatial Points. But first I want to rename coordinate columns into "lon" and "lat". Some data labels them "X" and "Y", while other may call "long" and "lat". So I want users to specify what were column names for "lon" and "lat". I am using dplyr. However, following will not work.

```<code>library("magrittr")
library("tidyverse")
ToSpatialPoint <- function(data, lon_col="long",lat_col="lati"){
    data %<>% rename(lon=lon_col,lat=lat_col) %<>% distinct(lon,lat) %<>% filter(!is.na(lon),!is.na(lat))
    processed_pts <- SpatialPoints(coords=cbind(lon=data$lon,lat=data$lat), proj4string = CRS("+init=epsg:4326"))
    return(processed_pts)
}
</code>```

I receive this error:

```<code>Error: `lon_col`, `lat_col` contains unknown variables
</code>```

答:
Here's an example, note that the new name goes on the left, and the current name goes on the right. You also don't need c() or quotes.

```<code>require(dplyr)

mtcars %>% rename(miles_per_gallon=mpg, horsepower=hp)

                  miles_per_gallon cyl disp horsepower drat    wt  qsec vs am
Mazda RX4                     21.0   6  160        110 3.90 2.620 16.46  0  1
Mazda RX4 Wag                 21.0   6  160        110 3.90 2.875 17.02  0  1
Datsun 710                    22.8   4  108         93 3.85 2.320 18.61  1  1
Hornet 4 Drive                21.4   6  258        110 3.08 3.215 19.44  1  0
Hornet Sportabout             18.7   8  360        175 3.15 3.440 17.02  0  0
Valiant                       18.1   6  225        105 2.76 3.460 20.22  1  0
</code>```

Using your example:

```<code>data %>% dplyr::rename(lon = lon_col, lat = lat_col)
</code>```

Body:
I know there are many similar questions regarding renaming columns in R, but I still have not found an elegant way to achieve this simple task, which can be easily done in Python.

Here is a simple function to convert GIS dataframe into Spatial Points. But first I want to rename coordinate columns into "lon" and "lat". Some data labels them "X" and "Y", while other may call "long" and "lat". So I want users to specify what were column names for "lon" and "lat". I am using dplyr. However, following will not work.

library("magrittr")
library("tidyverse")
ToSpatialPoint <- function(data, lon_col="long",lat_col="lati"){
    data %<>% rename(lon=lon_col,lat=lat_col) %<>% distinct(lon,lat) %<>% filter(!is.na(lon),!is.na(lat))
    processed_pts <- SpatialPoints(coords=cbind(lon=data$lon,lat=data$lat), proj4string = CRS("+init=epsg:4326"))
    return(processed_pts)
}

I receive this error:

Error: `lon_col`, `lat_col` contains unknown variables

Body:
Here's an example, note that the new name goes on the left, and the current name goes on the right. You also don't need c() or quotes.

require(dplyr)

mtcars %>% rename(miles_per_gallon=mpg, horsepower=hp)

                  miles_per_gallon cyl disp horsepower drat    wt  qsec vs am
Mazda RX4                     21.0   6  160        110 3.90 2.620 16.46  0  1
Mazda RX4 Wag                 21.0   6  160        110 3.90 2.875 17.02  0  1
Datsun 710                    22.8   4  108         93 3.85 2.320 18.61  1  1
Hornet 4 Drive                21.4   6  258        110 3.08 3.215 19.44  1  0
Hornet Sportabout             18.7   8  360        175 3.15 3.440 17.02  0  0
Valiant                       18.1   6  225        105 2.76 3.460 20.22  1  0

Using your example:

data %>% dplyr::rename(lon = lon_col, lat = lat_col)


问:
Unwrapping JSON from Itunes API - IOS App
Having an issue with my program. I would appreciate it if someone could help out. I have tried for weeks to parse the JSON files fetched from the iTunes API
(itunes.apple.com/search?term=song+you+want+to+search&entity=songTrack).

However, my answers are never displayed on my tableview and an error always shows up in the terminal:

```
"2017-11-14 17:25:28.809190+0100 Itunes Learning[32409:6240818] [MC] Lazy loading NSBundle MobileCoreServices.framework
2017-11-14 17:25:28.810264+0100 Itunes Learning[32409:6240818] [MC] Loaded MobileCoreServices.framework
2017-11-14 17:25:28.823734+0100 Itunes Learning[32409:6240818] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/cyprianzander/Library/Developer/CoreSimulator/Devices/D52FD9D5-B6E4-4CE0-99E4-6E0EE15A680D/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
Could not cast value of type '__NSDictionaryI' (0x103b911d8) to 'NSArray' (0x103b90d28).
2017-11-14 17:25:29.875534+0100 Itunes Learning[32409:6240900] Could not cast value of type '__NSDictionaryI' (0x103b911d8) to 'NSArray' (0x103b90d28).
(lldb) "
```

This is approximately how the JSON file is set up:

{“resultCount” : 50, “results”: [ {“trackName”:”name”, ”artistName”:”name2”}, {“trackName”:”name3”, “artistName”:”name4”} ] }

(An array of objects inside an array - meaning the first object is on the far outside).

I have tried my function with another API, which did work. I have the feeling that the main reason as to why this happens, is because the iTunes API JSON file is very complex. It is an assortment of very long objects inside an array, which is inside a smaller list of objects. However, the other one was only and array of objects.

Here is my code: (I have noticed that the problem occurs while parsing the data I need. The only thing I need to know is how to properly unwrap my JSON file)

```<code>func parseData(searchTerm: String) {
    fetchedSong = []
    let itunesSearchTerm = searchTerm.replacingOccurrences(of: " ", with: "+", options: .caseInsensitive, range: nil)
    let escapedSearchTerm = itunesSearchTerm.addingPercentEncoding(withAllowedCharacters: [])!
    let urlString = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&entity=song"
    let url = URL(string: urlString)!
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let error = error {
            // If there is an error in the web request, print it to the console
            print(error)
            return
        }

        else {
            do {
                let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                print(fetchedData)
                for eachFetchedSong in fetchedData {
                    let eachSong = eachFetchedSong as! [String: Any]
                    let song = eachSong["trackName"] as! String
                    let artist = eachSong["artistName"] as! String
                    self.fetchedSong.append(songs(song: song, artist : artist))

                }
                self.SongTableView.reloadData()

            }
            catch {
                print("An error occured while decoding the JSON object")
            }

        }
    }.resume()
}
</code>```

If anyone could help me, I would be extremely happy, especially because I have been stuck with this for three weeks, continuously trying different techniques (this one seemed the most successful).

答:
Your JSON data is not an array. It is a dictionary with two key/value pairs. The first is the key "resultCount" with a value of 50, and the second is the key "results" with an array as its value.

Never use as! when parsing JSON, since this will crash your app if you get an unexpected result. Don't use .mutableLeaves unless you can explain to us what it does and why you need it. Don't use NSArray in your Swift code.

Handling one error and crashing on others is pointless. I'd write

```<code>if let fetchedDict = try? JSONSerialization(...) as? [String:Any],
   let fetchedArray = fetchedDict ["results"] as? [[String:Any]] {
    for dict in fetchedArray {
        if let song = dict ["trackName"] as? String,
           let artist = dict ["artistName"] as? String {
           ...
        }
    }
}
</code>```

Body:
Having an issue with my program. I would appreciate it if someone could help out. I have tried for weeks to parse the JSON files fetched from the iTunes API
(itunes.apple.com/search?term=song+you+want+to+search&entity=songTrack).

However, my answers are never displayed on my tableview and an error always shows up in the terminal:

"2017-11-14 17:25:28.809190+0100 Itunes Learning[32409:6240818] [MC] Lazy loading NSBundle MobileCoreServices.framework
2017-11-14 17:25:28.810264+0100 Itunes Learning[32409:6240818] [MC] Loaded MobileCoreServices.framework
2017-11-14 17:25:28.823734+0100 Itunes Learning[32409:6240818] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/cyprianzander/Library/Developer/CoreSimulator/Devices/D52FD9D5-B6E4-4CE0-99E4-6E0EE15A680D/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
Could not cast value of type '__NSDictionaryI' (0x103b911d8) to 'NSArray' (0x103b90d28).
2017-11-14 17:25:29.875534+0100 Itunes Learning[32409:6240900] Could not cast value of type '__NSDictionaryI' (0x103b911d8) to 'NSArray' (0x103b90d28).
(lldb) "

This is approximately how the JSON file is set up:

{“resultCount” : 50, “results”: [ {“trackName”:”name”, ”artistName”:”name2”}, {“trackName”:”name3”, “artistName”:”name4”} ] }

(An array of objects inside an array - meaning the first object is on the far outside).

I have tried my function with another API, which did work. I have the feeling that the main reason as to why this happens, is because the iTunes API JSON file is very complex. It is an assortment of very long objects inside an array, which is inside a smaller list of objects. However, the other one was only and array of objects.

Here is my code: (I have noticed that the problem occurs while parsing the data I need. The only thing I need to know is how to properly unwrap my JSON file)

func parseData(searchTerm: String) {
    fetchedSong = []
    let itunesSearchTerm = searchTerm.replacingOccurrences(of: " ", with: "+", options: .caseInsensitive, range: nil)
    let escapedSearchTerm = itunesSearchTerm.addingPercentEncoding(withAllowedCharacters: [])!
    let urlString = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&entity=song"
    let url = URL(string: urlString)!
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let error = error {
            // If there is an error in the web request, print it to the console
            print(error)
            return
        }

        else {
            do {
                let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
                print(fetchedData)
                for eachFetchedSong in fetchedData {
                    let eachSong = eachFetchedSong as! [String: Any]
                    let song = eachSong["trackName"] as! String
                    let artist = eachSong["artistName"] as! String
                    self.fetchedSong.append(songs(song: song, artist : artist))

                }
                self.SongTableView.reloadData()

            }
            catch {
                print("An error occured while decoding the JSON object")
            }

        }
    }.resume()
}

If anyone could help me, I would be extremely happy, especially because I have been stuck with this for three weeks, continuously trying different techniques (this one seemed the most successful).

Body:
Your JSON data is not an array. It is a dictionary with two key/value pairs. The first is the key "resultCount" with a value of 50, and the second is the key "results" with an array as its value.

Never use as! when parsing JSON, since this will crash your app if you get an unexpected result. Don't use .mutableLeaves unless you can explain to us what it does and why you need it. Don't use NSArray in your Swift code.

Handling one error and crashing on others is pointless. I'd write

if let fetchedDict = try? JSONSerialization(...) as? [String:Any],
   let fetchedArray = fetchedDict ["results"] as? [[String:Any]] {
    for dict in fetchedArray {
        if let song = dict ["trackName"] as? String,
           let artist = dict ["artistName"] as? String {
           ...
        }
    }
}


答:
script is being used as a protocol. No applications handle the script protocol, so clicking it does nothing useful.

You can register a custom protocol handler and if the user accepts it, your application will be allowed to open all links of that type (there are only a few permitted protocols):

```<code>window.navigator.registerProtocolHandler('web+test', 'http://example.org/?handler=%s', 'Test Protocol');
</code>```

Only example.org will be allowed to run the above code, but if you open your dev tools while visiting http://example.org/ and run the above code, you will get a dialog asking you to allow or deny the protocol association. If you accept it, click the following link on any website:

```<code><a href="web+test:hello">test</a>
</code>```

It will redirect to http://example.org/?handler=hello

Title: what is this strange "script" doing?

Body:
I am doing some test then find below code would pop up a window:

test

looks like it is trying to open an application.
Can anyone tell me what is the usage/purpose of this "script"?
looks like FF, Chrome, and IE all support it.

Body:
script is being used as a protocol. No applications handle the script protocol, so clicking it does nothing useful.

You can register a custom protocol handler and if the user accepts it, your application will be allowed to open all links of that type (there are only a few permitted protocols):

window.navigator.registerProtocolHandler('web+test', 'http://example.org/?handler=%s', 'Test Protocol');

Only example.org will be allowed to run the above code, but if you open your dev tools while visiting http://example.org/ and run the above code, you will get a dialog asking you to allow or deny the protocol association. If you accept it, click the following link on any website:

<a href="web+test:hello">test</a>

It will redirect to http://example.org/?handler=hello


问:
Python Multidimensional Array as a single List
Sure, you can have nested lists to represent multidimensional arrays, but that seems costly...

```<code>[[0, 1], [2, 3]]
</code>```

Is there some way to "encode" and "decode" the coordinate into a single number, and use that number to lookup the corresponding element?

```<code>[0, 1, 2, 3]
</code>```

This needs to work with n-dimensions, not just two, and the best I could come up with for encoding is:

```<code>def getcellindex(self, location):
  cindex = 0
  cdrop = self.gridsize # where self.gridsize is the number of cells
  for index in xrange(self.numdimensions): # where self.numdimensions is the number of dimensions
    # where self.dimensions is a tuple of the different sizes of the corresponding dimension
    cdrop /= self.dimensions[index]
    cindex += cdrop * location[index]
  return cindex
</code>```

There're probably ways to optimize this, but more importantly, how do I reverse the process?  And, does this function work?

答:
A well known bijection:</p>

```<code>
from itertools import tee

def _basis(dimensions):
    # compute products of subtuple entries
    return tuple(reduce(lambda x,y: x*y, dimensions[:i]) for i in xrange(1, len(dimensions)+1))

def coordinate(n, dimensions):
    basis = _basis(dimensions)
    residues = [n % b for b in basis]
    it2, it1 = tee(basis)
    for x in it2:
        break
    return (residues[0],) + tuple((m2-m1)/b in m2, m1, b in zip(it2, it1, basis))

def number(c, dimensions):
    basis = _basis(dimensions)
    return sum(x*b for x, b in zip(c, basis))

</code>```

Body:
Sure, you can have nested lists to represent multidimensional arrays, but that seems costly...

[[0, 1], [2, 3]]

Is there some way to "encode" and "decode" the coordinate into a single number, and use that number to lookup the corresponding element?

[0, 1, 2, 3]

This needs to work with n-dimensions, not just two, and the best I could come up with for encoding is:

def getcellindex(self, location):
  cindex = 0
  cdrop = self.gridsize # where self.gridsize is the number of cells
  for index in xrange(self.numdimensions): # where self.numdimensions is the number of dimensions
    # where self.dimensions is a tuple of the different sizes of the corresponding dimension
    cdrop /= self.dimensions[index]
    cindex += cdrop * location[index]
  return cindex

There're probably ways to optimize this, but more importantly, how do I reverse the process?  And, does this function work?

Body:
A well known bijection:

from itertools import tee

def _basis(dimensions):
    # compute products of subtuple entries
    return tuple(reduce(lambda x,y: x*y, dimensions[:i]) for i in xrange(1, len(dimensions)+1))

def coordinate(n, dimensions):
    basis = _basis(dimensions)
    residues = [n % b for b in basis]
    it2, it1 = tee(basis)
    for x in it2:
        break
    return (residues[0],) + tuple((m2-m1)/b in m2, m1, b in zip(it2, it1, basis))

def number(c, dimensions):
    basis = _basis(dimensions)
    return sum(x*b for x, b in zip(c, basis))


问:
Not able to create new TinkerGraph in Tinkerpop3
I am trying to create a new tinker graph. But it is giving following exception

i am very new to graph databases. I just have installed tinkerpop3 on ubuntu linux. can some one help me if i am missing any thing, Thanks.

```<code> gremlin> g = TinkerGraphFactory.createTinkerGraph()

 No such property: TinkerGraphFactory for class: groovysh_evaluate
    Display stack trace? [yN] y
    groovy.lang.MissingPropertyException: No such property: TinkerGraphFactory for class: groovysh_evaluate
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:51)
        at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
        at groovysh_evaluate.run(groovysh_evaluate:3)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.codehaus.groovy.tools.shell.Interpreter.evaluate(Interpreter.groovy:68)
        at org.codehaus.groovy.tools.shell.Groovysh.execute(Groovysh.groovy:159)
        at org.codehaus.groovy.tools.shell.Shell.leftShift(Shell.groovy:121)
        at org.codehaus.groovy.tools.shell.ShellRunner.work(ShellRunner.groovy:93)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.super$2$work(InteractiveShellRunner.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:130)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuper0(ScriptBytecodeAdapter.java:150)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.work(InteractiveShellRunner.groovy:123)
        at org.codehaus.groovy.tools.shell.ShellRunner.run(ShellRunner.groovy:57)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.super$2$run(InteractiveShellRunner.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:130)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuper0(ScriptBytecodeAdapter.java:150)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.run(InteractiveShellRunner.groovy:83)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at com.tinkerpop.gremlin.console.Console.<init>(Console.groovy:99)
        at java.lang.invoke.MethodHandle.invokeWithArguments(MethodHandle.java:636)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at com.tinkerpop.gremlin.console.Console.main(Console.groovy:230)
</code>```

答:
For 3.3, you need to use g = TinkerFactory.createModern()

For more details, refer Apache TinkerPop Getting Started

Hope this helps

Body:
I am trying to create a new tinker graph. But it is giving following exception

i am very new to graph databases. I just have installed tinkerpop3 on ubuntu linux. can some one help me if i am missing any thing, Thanks.

 gremlin> g = TinkerGraphFactory.createTinkerGraph()

 No such property: TinkerGraphFactory for class: groovysh_evaluate
    Display stack trace? [yN] y
    groovy.lang.MissingPropertyException: No such property: TinkerGraphFactory for class: groovysh_evaluate
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:51)
        at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
        at groovysh_evaluate.run(groovysh_evaluate:3)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.codehaus.groovy.tools.shell.Interpreter.evaluate(Interpreter.groovy:68)
        at org.codehaus.groovy.tools.shell.Groovysh.execute(Groovysh.groovy:159)
        at org.codehaus.groovy.tools.shell.Shell.leftShift(Shell.groovy:121)
        at org.codehaus.groovy.tools.shell.ShellRunner.work(ShellRunner.groovy:93)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.super$2$work(InteractiveShellRunner.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:130)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuper0(ScriptBytecodeAdapter.java:150)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.work(InteractiveShellRunner.groovy:123)
        at org.codehaus.groovy.tools.shell.ShellRunner.run(ShellRunner.groovy:57)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.super$2$run(InteractiveShellRunner.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:130)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuper0(ScriptBytecodeAdapter.java:150)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.run(InteractiveShellRunner.groovy:83)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at com.tinkerpop.gremlin.console.Console.<init>(Console.groovy:99)
        at java.lang.invoke.MethodHandle.invokeWithArguments(MethodHandle.java:636)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at com.tinkerpop.gremlin.console.Console.main(Console.groovy:230)


问:
why is loop stuck
Only problems remaining now are that my choice while loop is infinite since the break statements dont seem to be breaking out of the loop at all, so the program doesn't read the answer loop.  Also, "Invalid Entry" displays every other incorrect input instead of displaying everytime an invalid character is entered

```<code>#include <iostream>
#include <cctype>
using namespace std;

int getAges(int age, const int SIZE);
char getChoice();
void displayInOrder(int numbers[], const int SIZE, char choice);
void displayInReverse(int numbers[], const int SIZE, char choice);

int main()
{
const int SIZE = 5;
int numbers[SIZE] = { 1, 2 ,3 ,4, 5 };
char answer = 0;
int age = 0;
char choice = 0;

while (choice = getChoice())
{
    if (toupper(choice) == 'O')
    {
        displayInOrder(numbers, SIZE, choice);
        break;
    }
    else if (toupper(choice) == 'R')
    {
        displayInReverse(numbers, SIZE, choice);
        break;
    }
    else
    {
        cout << "Invalid entry! - Must be O or R\n\n";
        break;
    }
}

while (toupper(answer) == 'Y')
{
    system("cls");

    age = getAges(age, SIZE);
    choice = getChoice();
    displayInOrder(numbers, SIZE, choice);
    displayInReverse(numbers, SIZE, choice);

    cout << "Run program again (Y or N)?  ";
    cin >> answer;

  if (toupper(answer) == 'N')
    {
        exit();
    }
}
return 0;
}

int getAges(int age, const int SIZE)
{
cout << "Enter " << SIZE << " ages: \n\n";
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
return age;
}

char getChoice()
{
char choice;
cout << "How do you want to see the ages displayed? \n\n Enter O for In Order, or R for In Reverse.\n\n";
cin >> choice;

return choice;

}

void displayInOrder(int numbers[], const int SIZE, char answer)
{
    cout << "Here are the ages in order: \n\n";
    for (int i = 0; i < SIZE; i++)
    {
        cout << numbers[i] << endl;
    }
}

void displayInReverse(int numbers[], const int SIZE, char answer)
{
    cout << "Here are the ages in reverse order: \n\n";
    for (int i = SIZE - 1; i >= 0; i--)
    {
        cout << numbers[i] << endl;
    }
}
</code>```

答:
1."Invalid Entry" displays every other incorrect input: you have a getChoice() call inside the while loop, here:

```<code>else
{
    cout << "Invalid entry! - Must be O or R\n\n";
    choice = getChoice();
}
</code>```

which is followed by a getChoice() call in the

```<code>while (choice = getChoice())
</code>```

Hence the previous getChoice() is not processed.

2."I'm not sure how to close the program if the user enters N for answer", You should think about if you can ever reach the second while loop and where you are setting the answer variable or basically where you are taking the user input for ending the program? You should see if it can it be taken care of in the first while loop ?

Title: why is loop stuck

Body:
Only problems remaining now are that my choice while loop is infinite since the break statements dont seem to be breaking out of the loop at all, so the program doesn't read the answer loop.  Also, "Invalid Entry" displays every other incorrect input instead of displaying everytime an invalid character is entered

#include <iostream>
#include <cctype>
using namespace std;

int getAges(int age, const int SIZE);
char getChoice();
void displayInOrder(int numbers[], const int SIZE, char choice);
void displayInReverse(int numbers[], const int SIZE, char choice);

int main()
{
const int SIZE = 5;
int numbers[SIZE] = { 1, 2 ,3 ,4, 5 };
char answer = 0;
int age = 0;
char choice = 0;

while (choice = getChoice())
{
    if (toupper(choice) == 'O')
    {
        displayInOrder(numbers, SIZE, choice);
        break;
    }
    else if (toupper(choice) == 'R')
    {
        displayInReverse(numbers, SIZE, choice);
        break;
    }
    else
    {
        cout << "Invalid entry! - Must be O or R\n\n";
        break;
    }
}

while (toupper(answer) == 'Y')
{
    system("cls");

    age = getAges(age, SIZE);
    choice = getChoice();
    displayInOrder(numbers, SIZE, choice);
    displayInReverse(numbers, SIZE, choice);

    cout << "Run program again (Y or N)?  ";
    cin >> answer;

  if (toupper(answer) == 'N')
    {
        exit();
    }
}
return 0;
}

int getAges(int age, const int SIZE)
{
cout << "Enter " << SIZE << " ages: \n\n";
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
return age;
}

char getChoice()
{
char choice;
cout << "How do you want to see the ages displayed? \n\n Enter O for In Order, or R for In Reverse.\n\n";
cin >> choice;

return choice;

}

void displayInOrder(int numbers[], const int SIZE, char answer)
{
    cout << "Here are the ages in order: \n\n";
    for (int i = 0; i < SIZE; i++)
    {
        cout << numbers[i] << endl;
    }
}

void displayInReverse(int numbers[], const int SIZE, char answer)
{
    cout << "Here are the ages in reverse order: \n\n";
    for (int i = SIZE - 1; i >= 0; i--)
    {
        cout << numbers[i] << endl;
    }
}

Body:
1."Invalid Entry" displays every other incorrect input: you have a getChoice() call inside the while loop, here:

else
{
    cout << "Invalid entry! - Must be O or R\n\n";
    choice = getChoice();
}

which is followed by a getChoice() call in the

while (choice = getChoice())

Hence the previous getChoice() is not processed.

2."I'm not sure how to close the program if the user enters N for answer", You should think about if you can ever reach the second while loop and where you are setting the answer variable or basically where you are taking the user input for ending the program? You should see if it can it be taken care of in the first while loop ?