问:
Why doesn't my Django template render a ModelForm's id or pk field?
In Django 1.10, I'm prepopulating a ModelForm in a template using a record from the database in order to edit that record in the form. However, when I want to render the HTML for the form, it doesn't show the id (or pk) fields. I want to put the id in a hidden <input> tag so when the form submits the backend knows which record to edit when the form is submitted. My web app doesn't have the id in the URL.

Here is my models.py:

```<code>from django.db import models

class MyModel(models.Model):
    name = models.CharField(max_length=50)
    phone = models.CharField(max_length=50)
</code>```

In the database, I've added one MyModel record with name 'Alice' and phone '212-555-5555'. The id/primary key is 1.

Here is my forms.py:

```<code>from django import forms
from . import models

class TestForm(forms.ModelForm):
    class Meta:
        model = models.MyModel
        fields = ['id', 'name', 'phone']
</code>```

Here is my views.py:

```<code>from django.shortcuts import render
from . import forms, models

def test_page(request):
    m = models.MyModel.objects.get(name='Alice')
    prepopulatedForm = forms.TestForm(instance=m)
    return render(request, 'testproject/test_template.html', {'form': prepopulatedForm})
</code>```

Here is my test_template.html:

```<code><h1>Test Page</h1>
{{ form }}
</code>```

This renders the form on the page, prepopulated with 'Alice' and '212-555-5555':

```<code><h1>Test Page</h1>
<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" maxlength="50" name="name" type="text" value="Alice" required /></td></tr>
<tr><th><label for="id_phone">Phone:</label></th><td><input id="id_phone" maxlength="50" name="phone" type="text" value="212-555-5555" required /></td></tr>
</code>```

My question is, why doesn't the id / primary key column appear in this form? I can't get it to render when I use this for the template either:

```<code><h1>Test Page</h1>
{{ form.id }}
{{ form.name }}
{{ form.phone }}
</code>```

This renders a blank where the id <input> should be:

```<code><h1>Test Page</h1>

<input id="id_name" maxlength="50" name="name" type="text" value="Alice" required />
<input id="id_phone" maxlength="50" name="phone" type="text" value="212-555-5555" required />
</code>```

I can see from running python manage.py shell that the record is in fact there:

```<code>>>> from testproject import models
>>> m = models.MyModel.objects.get(name='Alice')
>>> m.id
1
</code>```

In forms.py, setting fields to ['id', 'name', 'phone'] doesn't cause any errors, nor does ['pk', 'name', 'phone']. However, if I purposefully add a non-existent field name like ['NOT_REAL_FIELD', 'name', 'phone'], then python manage.py runserver will produce an error:

```<code>  File "C:\Users\Al\venvs\tas_env\lib\site-packages\django\forms\models.py", line 257, in __new__
    raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (NOT_REAL_FIELD) specified for MyModel
</code>```

So I know that 'id'/'pk' must be a legitimate field to put in the ModelForm.

Why doesn't my Django template render a ModelForm's id or pk field?

Eventually, I'd like to include the primary key as a hidden input in the form so that the record in the database can be edited. Also note, I don't care about ModelAdmin since I'm trying to display this in a template viewable by users, not in the admin panel. It's fine that the pk is read-only; it just needs to render in the template.

答:
How about accessing the id using {{ form.initial.id }}?

From what I can tell in looking the ModelForm metaclass, form.initial is populated a bit differently than the creation of form properties (e.g. form.name or form.phone). So basically it is in the weeds of the django metaclass magic...

To be a bit more specific. It appears that when creating a form, model_to_dict is called to pull data out of the model instance that is passed in. But it isn't until fields_for_model is called that the form instance has the model fields accessible as class attributes. I would guess that id is somehow being excluded from the fields being considered in fields_for_model. It looks like the non-editable field exception you referenced is raised here as well.

Body:
In Django 1.10, I'm prepopulating a ModelForm in a template using a record from the database in order to edit that record in the form. However, when I want to render the HTML for the form, it doesn't show the id (or pk) fields. I want to put the id in a hidden <input> tag so when the form submits the backend knows which record to edit when the form is submitted. My web app doesn't have the id in the URL.

Here is my models.py:

from django.db import models

class MyModel(models.Model):
    name = models.CharField(max_length=50)
    phone = models.CharField(max_length=50)

In the database, I've added one MyModel record with name 'Alice' and phone '212-555-5555'. The id/primary key is 1.

Here is my forms.py:

from django import forms
from . import models

class TestForm(forms.ModelForm):
    class Meta:
        model = models.MyModel
        fields = ['id', 'name', 'phone']

Here is my views.py:

from django.shortcuts import render
from . import forms, models

def test_page(request):
    m = models.MyModel.objects.get(name='Alice')
    prepopulatedForm = forms.TestForm(instance=m)
    return render(request, 'testproject/test_template.html', {'form': prepopulatedForm})

Here is my test_template.html:

Test Page

{{ form }}

This renders the form on the page, prepopulated with 'Alice' and '212-555-5555':

Test Page

Name:	<input id="id_name" maxlength="50" name="name" type="text" value="Alice" required />

Phone:	<input id="id_phone" maxlength="50" name="phone" type="text" value="212-555-5555" required />

My question is, why doesn't the id / primary key column appear in this form? I can't get it to render when I use this for the template either:

Test Page

{{ form.id }}
{{ form.name }}
{{ form.phone }}

This renders a blank where the id <input> should be:

Test Page

<input id="id_name" maxlength="50" name="name" type="text" value="Alice" required />
<input id="id_phone" maxlength="50" name="phone" type="text" value="212-555-5555" required />

I can see from running python manage.py shell that the record is in fact there:

>>> from testproject import models
>>> m = models.MyModel.objects.get(name='Alice')
>>> m.id
1

In forms.py, setting fields to ['id', 'name', 'phone'] doesn't cause any errors, nor does ['pk', 'name', 'phone']. However, if I purposefully add a non-existent field name like ['NOT_REAL_FIELD', 'name', 'phone'], then python manage.py runserver will produce an error:

  File "C:\Users\Al\venvs\tas_env\lib\site-packages\django\forms\models.py", line 257, in __new__
    raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (NOT_REAL_FIELD) specified for MyModel

So I know that 'id'/'pk' must be a legitimate field to put in the ModelForm.

Why doesn't my Django template render a ModelForm's id or pk field?

Eventually, I'd like to include the primary key as a hidden input in the form so that the record in the database can be edited. Also note, I don't care about ModelAdmin since I'm trying to display this in a template viewable by users, not in the admin panel. It's fine that the pk is read-only; it just needs to render in the template.


来源: stackexchange

问:
Textarea without scrollbar
Hi
I do want to create a textarea without scrollbar just like in facebook and twitter, and the creation of the textarea that changes its height when we click on it.
thank you</p>

答: You can find an explanation over here http://www.dazecoop.com/22-10-2008/jquery-textarea-auto-grow-auto-height you just need to get the plugin ;)</p>

ContentLicense: CC BY-SA 2.5

Title: Textarea without scrollbar


问:
Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4
I have an error message on Django 1.4:

```<code>dictionary update sequence element #0 has length 1; 2 is required
</code>```

It happened when I tried using a template tag like: {% for v in values %}:

```<code>dictionary update sequence element #0 has length 1; 2 is required

Request Method:     GET
Request URL:    ...
Django Version:     1.4.5
Exception Type:     ValueError
Exception Value:

dictionary update sequence element #0 has length 1; 2 is required

Exception Location:     /usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__, line 21
Python Executable:  /usr/bin/uwsgi-core
Python Version:     2.7.3
Python Path:

['/var/www/',
 '.',
 '',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PIL',
 '/usr/lib/pymodules/python2.7']

Server time:    sam, 13 Jul 2013 16:15:45 +0200
Error during template rendering

In template /var/www/templates/app/index.html, error at line 172
dictionary update sequence element #0 has length 1; 2 is required

172     {% for product in products %}

Traceback Switch to copy-and-paste view

/usr/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response

                            response = callback(request, *callback_args, **callback_kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/contrib/auth/decorators.py in _wrapped_view

                    return view_func(request, *args, **kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/views/decorators/http.py in inner

                return func(request, *args, **kwargs)

    ...
▶ Local vars
./app/views.py in index

            context_instance=RequestContext(request))

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/shortcuts/__init__.py in render_to_response

        return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader.py in render_to_string

            return t.render(context_instance)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                return self._render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render

            return self.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render

            return compiled_parent._render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render

            return self.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render

                result = block.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/defaulttags.py in render

            len_values = len(values)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/core/paginator.py in __len__

            return len(self.object_list)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in __len__

                    self._result_cache = list(self.iterator())

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in iterator

                        obj = model(*row[index_start:aggregate_start])

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/base.py in __init__

                    setattr(self, field.attname, val)

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __set__

                value = self.field._attribute_class(value, self.field, obj)

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__

            super(HStoreDictionary, self).__init__(value, **params)

    ...
▶ Local vars
</code>```

It happens too when I try to access on a hstore queryset:

```<code>Traceback (most recent call last):
File "manage.py", line 14, in <module>
    execute_manager(settings)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 459, in execute_manager
    utility.execute()

File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)

File "/home/name/workspace/project/app/data/commands/my_command.py", line 60, in handle
    item_id = tmp[0].id,

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 207, in __getitem__
    return list(qs)[0]

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 87, in __len__
    self._result_cache.extend(self._iter)

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 301, in iterator
    obj = model(*row[index_start:aggregate_start])

File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 300, in __init__
    setattr(self, field.attname, val)

File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 38, in __set__
    value = self.field._attribute_class(value, self.field, obj)

File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 21, in __init__
    super(HStoreDictionary, self).__init__(value, **params)

ValueError: dictionary update sequence element #0 has length 1; 2 is required
</code>```

The code is:

```<code>tmp = Item.objects.where(HE("kv").contains({'key':value}))

if tmp.count() > 0:

    item_id = tmp[0].id,
</code>```

I'm just trying to access the value.  I don't understand the "update sequence" message.  When I use a cursor instead of hstore queryset,  the function works. The error comes on template rendering too.  I just restarted uwsgi and everything works well, but the error comes back later.

答:
Solution»

Pass a keyword argument name with value as your view name e.g home or home-view etc. to url() function.

Throws Error»

url(r'^home$', 'common.views.view1', 'home'),

Correct»

url(r'^home$', 'common.views.view1', name='home'),

ContentLicense: CC BY-SA 4.0

Body:
I have an error message on Django 1.4:

dictionary update sequence element #0 has length 1; 2 is required

It happened when I tried using a template tag like: {% for v in values %}:

dictionary update sequence element #0 has length 1; 2 is required

Request Method:     GET
Request URL:    ...
Django Version:     1.4.5
Exception Type:     ValueError
Exception Value:

dictionary update sequence element #0 has length 1; 2 is required

Exception Location:     /usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__, line 21
Python Executable:  /usr/bin/uwsgi-core
Python Version:     2.7.3
Python Path:

['/var/www/',
 '.',
 '',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-linux2',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PIL',
 '/usr/lib/pymodules/python2.7']

Server time:    sam, 13 Jul 2013 16:15:45 +0200
Error during template rendering

In template /var/www/templates/app/index.html, error at line 172
dictionary update sequence element #0 has length 1; 2 is required

172     {% for product in products %}

Traceback Switch to copy-and-paste view

/usr/lib/python2.7/dist-packages/django/core/handlers/base.py in get_response

                            response = callback(request, *callback_args, **callback_kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/contrib/auth/decorators.py in _wrapped_view

                    return view_func(request, *args, **kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/views/decorators/http.py in inner

                return func(request, *args, **kwargs)

    ...
▶ Local vars
./app/views.py in index

            context_instance=RequestContext(request))

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/shortcuts/__init__.py in render_to_response

        return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader.py in render_to_string

            return t.render(context_instance)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                return self._render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render

            return self.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render

            return compiled_parent._render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in _render

            return self.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/loader_tags.py in render

                result = block.nodelist.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/base.py in render

                    bit = self.render_node(node, context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/debug.py in render_node

                return node.render(context)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/template/defaulttags.py in render

            len_values = len(values)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/core/paginator.py in __len__

            return len(self.object_list)

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in __len__

                    self._result_cache = list(self.iterator())

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/query.py in iterator

                        obj = model(*row[index_start:aggregate_start])

    ...
▶ Local vars
/usr/lib/python2.7/dist-packages/django/db/models/base.py in __init__

                    setattr(self, field.attname, val)

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __set__

                value = self.field._attribute_class(value, self.field, obj)

    ...
▶ Local vars
/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py in __init__

            super(HStoreDictionary, self).__init__(value, **params)

    ...
▶ Local vars

It happens too when I try to access on a hstore queryset:

Traceback (most recent call last):
File "manage.py", line 14, in <module>
    execute_manager(settings)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 459, in execute_manager
    utility.execute()

File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)

File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)

File "/home/name/workspace/project/app/data/commands/my_command.py", line 60, in handle
    item_id = tmp[0].id,

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 207, in __getitem__
    return list(qs)[0]

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 87, in __len__
    self._result_cache.extend(self._iter)

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 301, in iterator
    obj = model(*row[index_start:aggregate_start])

File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 300, in __init__
    setattr(self, field.attname, val)

File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 38, in __set__
    value = self.field._attribute_class(value, self.field, obj)

File "/usr/local/lib/python2.7/dist-packages/djorm_hstore/fields.py", line 21, in __init__
    super(HStoreDictionary, self).__init__(value, **params)

ValueError: dictionary update sequence element #0 has length 1; 2 is required

The code is:

tmp = Item.objects.where(HE("kv").contains({'key':value}))

if tmp.count() > 0:

    item_id = tmp[0].id,

I'm just trying to access the value.  I don't understand the "update sequence" message.  When I use a cursor instead of hstore queryset,  the function works. The error comes on template rendering too.  I just restarted uwsgi and everything works well, but the error comes back later.

ContentLicense: CC BY-SA 3.0


问:
Error when creating multiple columns in one table with same values
When I try to exeecute the folliwng in SQL, I get error, I am trying to add multiple columns with same value to one table.

```<code>CREATE TABLE IF NOT EXISTS `vendor` (
  `product_id` varchar(255) NOT NULL
), `Vendor_SKU_or_Stock_Number` varchar(255) NOT NULL
), `Brand_Name` varchar(255) NOT NULL
), `Image_URL5`varchar(255) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

ERROR: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' Vendor_SKU_or_Stock_Number varchar(255) NOT NULL
), Brand_Name varchar(255)' at line 13

Please help

答:
Try this</p>

```<code>CREATE TABLE IF NOT EXISTS vendor (
  product_id varchar(255) NOT NULL,
vendor_SKU_or_Stock_Number varchar(255) NOT NULL,
brand_Name varchar(255) NOT NULL,
image_URL5 varchar(255) NOT NULL) ENGINE=InnoDB DEFAULT CHARACTER SET=latin1;
</code>```

Body:
When I try to exeecute the folliwng in SQL, I get error, I am trying to add multiple columns with same value to one table.

CREATE TABLE IF NOT EXISTS `vendor` (
  `product_id` varchar(255) NOT NULL
), `Vendor_SKU_or_Stock_Number` varchar(255) NOT NULL
), `Brand_Name` varchar(255) NOT NULL
), `Image_URL5`varchar(255) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ERROR: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' Vendor_SKU_or_Stock_Number varchar(255) NOT NULL
), Brand_Name varchar(255)' at line 13

Please help

Body:
Try this

CREATE TABLE IF NOT EXISTS vendor (
  product_id varchar(255) NOT NULL,
vendor_SKU_or_Stock_Number varchar(255) NOT NULL,
brand_Name varchar(255) NOT NULL,
image_URL5 varchar(255) NOT NULL) ENGINE=InnoDB DEFAULT CHARACTER SET=latin1;


问:
Issue with tracing down the array in Java recursion function
I have an issue with recursion in Java. The question is as such:

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

The code for the above problem is recursive and is as mentioned below:

```<code>public List<String> generateParenthesis(int n) {
    ArrayList<String> result = new ArrayList<String>();
    dfs(result, "", n, n);
    return result;
}

public void dfs(ArrayList<String> result, String s, int left, int right){
    if(left > right)
        return;

    if(left==0&&right==0){
        result.add(s);
        return;
    }

    if(left>0){
        dfs(result, s+"(", left-1, right);
    }

    if(right>0){
        dfs(result, s+")", left, right-1);
    }
}
</code>```

I have been able to trace the program upto a particular point, but I am unable to trace it down totally.

if n=2

```<code>left=2;right=2;
result="(())",
__________
| s=""   |
| l=2    |
| r=2    |
|        |
|        |
|________|
    |
    V
__________
| s=(    |
| l 1    |
| r 2    |
|        |
|        |
|________|
    |
    V
__________
| s=((   |
| l 0    |
| r 2    |
|        |
|        |
|________|
    |
    V
__________
| s=(()  |
| l 0    |
| r 1    |
|        |
|        |
|________|
    |
    V
__________
| s= (())|
| l=0    |
| r=0    |
|        |
|        |
|________|
</code>```

how would the program work after what I have mentioned above? Can someone help me tracing it? Thanks.

答:
From where you left off:

```<code>__________
| s=(    |
| l=1    |
| r=2    |
|        |
|        |
|________|
    |
    V
__________
| s=()   |
| l 1    |
| r 1    |
|        |
|        |
|________|
    |
    V
__________
| s=()(  |
| l 0    |
| r 1    |
|        |
|        |
|________|
    |
    V
__________
| s=()() |
| l 0    |
| r 0    |
|        |
|        |
|________|
</code>```

If you're using eclipse or any other IDE, it should be easy to set a breakpoint and go through how your program runs line by line (showing all your variables and how they change). If you haven't learned debugging yet, I would encourage you to google it and learn how to debug programs.

What your program is actually doing:

```<code>left (l=1, r=2)
  left (l=0, r=2)
    right (l=0, r=1)
      right (l=0, r=0)
        add result to s (l=0, r=0)
    *here you break out of 3 recursive functions and values of l,r reset to (l=1, r=2)*
  right (l=1, r=1)
    left (l=0, r=1)
      right (l=0, r=0)
      add result to s (l=0, r=0)
</code>```

Body:
I have an issue with recursion in Java. The question is as such:

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

The code for the above problem is recursive and is as mentioned below:

public List<String> generateParenthesis(int n) {
    ArrayList<String> result = new ArrayList<String>();
    dfs(result, "", n, n);
    return result;
}

public void dfs(ArrayList<String> result, String s, int left, int right){
    if(left > right)
        return;

    if(left==0&&right==0){
        result.add(s);
        return;
    }

    if(left>0){
        dfs(result, s+"(", left-1, right);
    }

    if(right>0){
        dfs(result, s+")", left, right-1);
    }
}

I have been able to trace the program upto a particular point, but I am unable to trace it down totally.

if n=2

left=2;right=2;
result="(())",
__________
| s=""   |
| l=2    |
| r=2    |
|        |
|        |
|________|
    |
    V
__________
| s=(    |
| l 1    |
| r 2    |
|        |
|        |
|________|
    |
    V
__________
| s=((   |
| l 0    |
| r 2    |
|        |
|        |
|________|
    |
    V
__________
| s=(()  |
| l 0    |
| r 1    |
|        |
|        |
|________|
    |
    V
__________
| s= (())|
| l=0    |
| r=0    |
|        |
|        |
|________|

how would the program work after what I have mentioned above? Can someone help me tracing it? Thanks.

Body:
From where you left off:

__________
| s=(    |
| l=1    |
| r=2    |
|        |
|        |
|________|
    |
    V
__________
| s=()   |
| l 1    |
| r 1    |
|        |
|        |
|________|
    |
    V
__________
| s=()(  |
| l 0    |
| r 1    |
|        |
|        |
|________|
    |
    V
__________
| s=()() |
| l 0    |
| r 0    |
|        |
|        |
|________|

If you're using eclipse or any other IDE, it should be easy to set a breakpoint and go through how your program runs line by line (showing all your variables and how they change). If you haven't learned debugging yet, I would encourage you to google it and learn how to debug programs.

What your program is actually doing:

left (l=1, r=2)
  left (l=0, r=2)
    right (l=0, r=1)
      right (l=0, r=0)
        add result to s (l=0, r=0)
    *here you break out of 3 recursive functions and values of l,r reset to (l=1, r=2)*
  right (l=1, r=1)
    left (l=0, r=1)
      right (l=0, r=0)
      add result to s (l=0, r=0)


问:
How to deal with dependencies with "provided" scope in OSGi
There are lots of tutorials, which shows how to cope with dependencies of the OSGi project and how should they be converted to the bundle. After more than one day research, I have still not found how to deal with the dependencies with provided scope.

Let me give an example. I am currently using Dropbox (dropbox-core-sdk 3.0) and it has two dependencies (com.google.android and javax.servlet) with provided scope. When I use the techniques such as maven-bundle-plugin or bnd, it only downloads the artifacts and its transitive dependencies. However, I need also provided dependencies in order to be able to import my project to the OSGi container.

I am using maven-bundle-plugin and my pom.xml looks like:

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <Bundle-SymbolicName>${project.artifactId};singleton:=true</Bundle-SymbolicName>
                    <Bundle-Version>${project.version}</Bundle-Version>
                    <Export-Package>*</Export-Package>
                    <Embed-Transitive>true</Embed-Transitive>
                    <Embed-Dependency>*</Embed-Dependency>
                </instructions>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

even if Embed-Dependency says include everything, only the dependencies + transitive dependencies are in the jar. However, I want the provided-scoped jars are also in the jar.

Is there any way to download dependencies with provided scope. If not, how to deal with this situation?

答: I would have to defer to the Maven BND experts out there, but I don't think you can include provided dependencies through a Maven build. Since it is unlikely you will be using the Android components outside of your bundle, couldn't you just manually download the needed Jars and place them in your bundle (Bundle-Classpath)?</p>

Body:
There are lots of tutorials, which shows how to cope with dependencies of the OSGi project and how should they be converted to the bundle. After more than one day research, I have still not found how to deal with the dependencies with provided scope.

Let me give an example. I am currently using Dropbox (dropbox-core-sdk 3.0) and it has two dependencies (com.google.android and javax.servlet) with provided scope. When I use the techniques such as maven-bundle-plugin or bnd, it only downloads the artifacts and its transitive dependencies. However, I need also provided dependencies in order to be able to import my project to the OSGi container.

I am using maven-bundle-plugin and my pom.xml looks like:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <Bundle-SymbolicName>${project.artifactId};singleton:=true</Bundle-SymbolicName>
                    <Bundle-Version>${project.version}</Bundle-Version>
                    <Export-Package>*</Export-Package>
                    <Embed-Transitive>true</Embed-Transitive>
                    <Embed-Dependency>*</Embed-Dependency>
                </instructions>
            </configuration>
        </plugin>
    </plugins>
</build>

even if Embed-Dependency says include everything, only the dependencies + transitive dependencies are in the jar. However, I want the provided-scoped jars are also in the jar.

Is there any way to download dependencies with provided scope. If not, how to deal with this situation?


问:
Adobe flash cs6 Output window closes automatically while executing Filesteam operation in .exe file but it works fine in flash debug mode
I am using adobe flash cs6 for creating a desktop application. In that application iam using flash.filesystem.filestream to save a text file
(I dont want to use FileReference because I don't want show the save dialog box )
When I call the new FileStream() in the exported .swf or .exe file, the app stopped running and it closes the window.
here is my sample code while executing this line
var fileStream : FileStream = new FileStream();
the window closed automatically but this code work fine in Preview mode
( ctrl + Enter) iam using
Target: AIR 2.5;
Script: ActionScript 3.0
in publish settings.

sample.as

```<code>package{
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;

public class SampleClass {
    public function generateReport (text : String) : void
    {
        var fileMode:String = (FileMode.APPEND);
        var fileStream : FileStream = new FileStream();
        var file:File = File.desktopDirectory.resolvePath("sample.txt");
        fileStream.open (file, fileMode);
        fileStream.writeMultiByte (text, File.systemCharset);
        fileStream.close ();
    }

}
</code>```

}

Is there any way to solve this problem ?
Thank you very much!

Pravin

答:
I have no idea what content of text is, but from that .writeMultiByte (text, File.systemCharset); I assume you wanted to write non-English alphabetic chars?

Best just use .writeUTFBytes since that handles both English & foreign alphabets.

Anycase... See if this code re-fix SampleClass.as works for you (tested with no crashing .exe) :

```<code>package{

import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;

import flash.display.MovieClip;

public class SampleClass extends MovieClip {

    public function SampleClass ()
    {
        generateReport("test Chinese : 你好 世界 ... test Urdu : ہیلو دنیا ... test Russian : Привет мир");
    }

    public function generateReport (text : String) : void
    {
        var fileMode:String = "append"; //not... String = (FileMode.APPEND);
        var fileStream : FileStream = new FileStream();
        var file:File = File.desktopDirectory.resolvePath("sample.txt");

        fileStream.open (file, fileMode);
        //fileStream.writeMultiByte (text, File.systemCharset); //trying non-English chars??
        fileStream.writeUTFBytes(text); //UTF is Unicode so can handle non-English chars
        fileStream.close();
        //trace("Text Done... check file \"sample.txt\" in Desktop");
    }

} //end Class
} //end Package
</code>```

Body:
I am using adobe flash cs6 for creating a desktop application. In that application iam using flash.filesystem.filestream to save a text file
(I dont want to use FileReference because I don't want show the save dialog box )
When I call the new FileStream() in the exported .swf or .exe file, the app stopped running and it closes the window.
here is my sample code while executing this line
var fileStream : FileStream = new FileStream();
the window closed automatically but this code work fine in Preview mode
( ctrl + Enter) iam using
Target: AIR 2.5;
Script: ActionScript 3.0
in publish settings.

sample.as

package{
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;

public class SampleClass {
    public function generateReport (text : String) : void
    {
        var fileMode:String = (FileMode.APPEND);
        var fileStream : FileStream = new FileStream();
        var file:File = File.desktopDirectory.resolvePath("sample.txt");
        fileStream.open (file, fileMode);
        fileStream.writeMultiByte (text, File.systemCharset);
        fileStream.close ();
    }

}

}

Is there any way to solve this problem ?
Thank you very much!

Pravin

Body:
I have no idea what content of text is, but from that .writeMultiByte (text, File.systemCharset); I assume you wanted to write non-English alphabetic chars?

Best just use .writeUTFBytes since that handles both English & foreign alphabets.

Anycase... See if this code re-fix SampleClass.as works for you (tested with no crashing .exe) :

package{

import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;

import flash.display.MovieClip;

public class SampleClass extends MovieClip {

    public function SampleClass ()
    {
        generateReport("test Chinese : 你好 世界 ... test Urdu : ہیلو دنیا ... test Russian : Привет мир");
    }

    public function generateReport (text : String) : void
    {
        var fileMode:String = "append"; //not... String = (FileMode.APPEND);
        var fileStream : FileStream = new FileStream();
        var file:File = File.desktopDirectory.resolvePath("sample.txt");

        fileStream.open (file, fileMode);
        //fileStream.writeMultiByte (text, File.systemCharset); //trying non-English chars??
        fileStream.writeUTFBytes(text); //UTF is Unicode so can handle non-English chars
        fileStream.close();
        //trace("Text Done... check file \"sample.txt\" in Desktop");
    }

} //end Class
} //end Package


问:
How to programmaticaly change the path of a msaccess linked table
I´m looking for a solution to do so using c#.

I have 2 msaccess db and I copy them to user´s machine at the firt execution of the system. Between these dbs I have a linked table which I need to change the path to the user folder.

I´ve looked around but I couldn´t find anything.

Any help will be appreciated.

答:
I had this problem some time ago while using VBA, which is probably easier to interface with Access than using C#.

However, after trying out several unreliable options I ended up just dropping the link and creating it from scratch. I would first retrieve all options used by the linked table, replace the database location and create a new linked table with those options, imitatng the old link.

After a quick search I found ADO.NET way for creating a linked table and How can I link an external Access table via .NET? that should help you with doing that in C#.


问:
IOError: No files found based on the file pattern
I'm trying to run the examples found in the Python SDK. However, this errors out with the stacktrace as follows. Note: The first pipeline does create the "./names" file, but the second pipeline does not seem to be able to read from it.

```<code>No handlers could be found for logger "oauth2client.contrib.multistore_file"
Traceback (most recent call last):
  File "example.py", line 17, in <module>
    | 'save' >> beam.io.WriteToText(greetings_file))
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/textio.py", line 391, in __init__
    skip_header_lines=skip_header_lines)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/textio.py", line 88, in __init__
    validate=validate)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/filebasedsource.py", line 97, in __init__
    self._validate()
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/filebasedsource.py", line 173, in _validate
    'No files found based on the file pattern %s' % self._pattern)
IOError: No files found based on the file pattern ./names
</code>```

The sample code is below:

```<code>import apache_beam as beam
def add_greeting(name, messages):
    for msg in messages:
        yield '%s %s' % (msg, name)

names_file = './names'
greetings_file = './greetings'

p = beam.Pipeline('DirectRunner')
(p | 'add names' >> beam.Create(['Ann', 'Joe'])
   | 'save' >> beam.io.WriteToText(names_file))
p.run()

(p
 | 'load names' >> beam.io.ReadFromText(names_file)
 | 'add greetings' >> beam.FlatMap(add_greetings, ['Hello', 'Hola'])
 | 'save' >> beam.io.WriteToText(greetings_file))
p.run()
</code>```

Environment: I'm running this on a google cloud shell

```<code>$ pip list --local --format=columns | grep dataflow
google-cloud-dataflow              0.6.0
</code>```

答:
When a pipeline runs, the runners in Beam don't wait for it to finish, so you should add a call to wait_until_finish() after calling p.run().

Also, Beam pipelines have deferred execution, so when you define new steps for your pipeline, they are added to a graph that is executed fully every time you run your pipeline. This means, in short, that you need to create a new Pipeline object if you want a pipeline that runs different steps.

This should work:

```<code>p = beam.Pipeline('DirectRunner')
(p | 'add names' >> beam.Create(['Ann', 'Joe'])
   | 'save' >> beam.io.WriteToText('./names'))
p.run().wait_until_finish()

p = beam.Pipeline('DirectRunner')
(p
 | 'load names' >> beam.io.ReadFromText('./names*')
 | 'add greetings' >> beam.FlatMap(add_greeting, ['Hello', 'Hola'])
 | 'save' >> beam.io.WriteToText(greetings_file))
p.run().wait_until_finish()
</code>```

Body:
I'm trying to run the examples found in the Python SDK. However, this errors out with the stacktrace as follows. Note: The first pipeline does create the "./names" file, but the second pipeline does not seem to be able to read from it.

No handlers could be found for logger "oauth2client.contrib.multistore_file"
Traceback (most recent call last):
  File "example.py", line 17, in <module>
    | 'save' >> beam.io.WriteToText(greetings_file))
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/textio.py", line 391, in __init__
    skip_header_lines=skip_header_lines)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/textio.py", line 88, in __init__
    validate=validate)
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/filebasedsource.py", line 97, in __init__
    self._validate()
  File "/usr/local/lib/python2.7/dist-packages/apache_beam/io/filebasedsource.py", line 173, in _validate
    'No files found based on the file pattern %s' % self._pattern)
IOError: No files found based on the file pattern ./names

The sample code is below:

import apache_beam as beam
def add_greeting(name, messages):
    for msg in messages:
        yield '%s %s' % (msg, name)

names_file = './names'
greetings_file = './greetings'

p = beam.Pipeline('DirectRunner')
(p | 'add names' >> beam.Create(['Ann', 'Joe'])
   | 'save' >> beam.io.WriteToText(names_file))
p.run()

(p
 | 'load names' >> beam.io.ReadFromText(names_file)
 | 'add greetings' >> beam.FlatMap(add_greetings, ['Hello', 'Hola'])
 | 'save' >> beam.io.WriteToText(greetings_file))
p.run()

Environment: I'm running this on a google cloud shell

$ pip list --local --format=columns | grep dataflow
google-cloud-dataflow              0.6.0

Body:
When a pipeline runs, the runners in Beam don't wait for it to finish, so you should add a call to wait_until_finish() after calling p.run().

Also, Beam pipelines have deferred execution, so when you define new steps for your pipeline, they are added to a graph that is executed fully every time you run your pipeline. This means, in short, that you need to create a new Pipeline object if you want a pipeline that runs different steps.

This should work:

p = beam.Pipeline('DirectRunner')
(p | 'add names' >> beam.Create(['Ann', 'Joe'])
   | 'save' >> beam.io.WriteToText('./names'))
p.run().wait_until_finish()

p = beam.Pipeline('DirectRunner')
(p
 | 'load names' >> beam.io.ReadFromText('./names*')
 | 'add greetings' >> beam.FlatMap(add_greeting, ['Hello', 'Hola'])
 | 'save' >> beam.io.WriteToText(greetings_file))
p.run().wait_until_finish()


问:
Styling of Select2 dropdown select boxes
I'm using Select2 in a project to style some select boxes in a search form. I managed to change the gradient background of the arrow container to a black gradient:

.select2-container .select2-choice .select2-arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
}
```

I would like the arrow to be white, but unfortunately Select2 is using a background image for the different icons instead of font-awesome or something similar, so there's no way to just change the color with CSS.

What would be the easiest way to make the arrow white instead of the default grey? Do I really have to replace the background png (select2.png and select2x2.png) with my own? Or is there an easier method?

Another question I have is how to change the height of the select boxes. I know how to change the height of the dropdown box in opened state, but I want to change the height of the selectbox in closed state. Any ideas?

答:
This is how i changed placeholder arrow color, the 2 classes are for dropdown open and dropdown closed, you need to change the #fff to the color you want:</p>

```<code>.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b {
    border-color: transparent transparent #fff transparent !important;
  }
  .select2-container--default .select2-selection--single .select2-selection__arrow b {
    border-color: #fff transparent transparent transparent !important;
  }
</code>```

Body:
I'm using Select2 in a project to style some select boxes in a search form. I managed to change the gradient background of the arrow container to a black gradient:

.select2-container .select2-choice .select2-arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
}

I would like the arrow to be white, but unfortunately Select2 is using a background image for the different icons instead of font-awesome or something similar, so there's no way to just change the color with CSS.

What would be the easiest way to make the arrow white instead of the default grey? Do I really have to replace the background png (select2.png and select2x2.png) with my own? Or is there an easier method?

Another question I have is how to change the height of the select boxes. I know how to change the height of the dropdown box in opened state, but I want to change the height of the selectbox in closed state. Any ideas?

Body:
This is how i changed placeholder arrow color, the 2 classes are for dropdown open and dropdown closed, you need to change the #fff to the color you want:

.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b {
    border-color: transparent transparent #fff transparent !important;
  }
  .select2-container--default .select2-selection--single .select2-selection__arrow b {
    border-color: #fff transparent transparent transparent !important;
  }


问:
ScrollView with GradientColor
I am trying to make scroll view with gradient background color, but it shows me gradient color only and could not see scroll view! No error waning.</p>

```<code>    mainScrollView.frame = view.frame
    imageArray = [#imageLiteral(resourceName: "business-improvement"), #imageLiteral(resourceName: "IMG_3601"), #imageLiteral(resourceName: "IMG_4261"), #imageLiteral(resourceName: "IMG_4264")]

    for i in 0..<imageArray.count{

        let imageView = UIImageView()
        imageView.image = imageArray[i]
        imageView.contentMode = .scaleAspectFit
        let xPosition = self.view.frame.width * CGFloat(i)
        imageView.frame = CGRect(x: xPosition, y:0, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)

        let mainScrollView = CAGradientLayer()
        self.view.backgroundColor = UIColor(red: 0.01, green:0.34, blue: 0.38, alpha: 1.0)
        mainScrollView.frame = self.view.bounds
        let color1 = UIColor(red: 0.11, green:0.04, blue: 0.32, alpha: 1.0).cgColor
        let color2 = UIColor(red: 0.0, green:0.18, blue: 0.20, alpha: 1.0).cgColor
        mainScrollView.colors = [color1, color2]
        mainScrollView.frame = CGRect(x: 0, y: 0, width: 375, height: 690)
        self.view.layer.addSublayer(mainScrollView)
</code>```

答:
I try the same and this works for me :</p>

```<code> self.MyItem.applyGradient_2(colours: [UIColor(red:0.09, green:0.91, blue:0.65, alpha:1.0), UIColor(red:0.08, green:0.92, blue:0.43, alpha:1.0)])

extension UIView {
    func applyGradient_2(colours: [UIColor]) -> Void {
        self.applyGradient_(colours: colours, locations: nil)
    }

    func applyGradient_(colours: [UIColor], locations: [NSNumber]?) -> Void {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colours.map { $0.cgColor }
        gradient.locations = locations
        self.layer.insertSublayer(gradient, at: 0)
    }
}
</code>```

Title: ScrollView with GradientColor

Body:
I am trying to make scroll view with gradient background color, but it shows me gradient color only and could not see scroll view! No error waning.

    mainScrollView.frame = view.frame
    imageArray = [#imageLiteral(resourceName: "business-improvement"), #imageLiteral(resourceName: "IMG_3601"), #imageLiteral(resourceName: "IMG_4261"), #imageLiteral(resourceName: "IMG_4264")]

    for i in 0..<imageArray.count{

        let imageView = UIImageView()
        imageView.image = imageArray[i]
        imageView.contentMode = .scaleAspectFit
        let xPosition = self.view.frame.width * CGFloat(i)
        imageView.frame = CGRect(x: xPosition, y:0, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)

        let mainScrollView = CAGradientLayer()
        self.view.backgroundColor = UIColor(red: 0.01, green:0.34, blue: 0.38, alpha: 1.0)
        mainScrollView.frame = self.view.bounds
        let color1 = UIColor(red: 0.11, green:0.04, blue: 0.32, alpha: 1.0).cgColor
        let color2 = UIColor(red: 0.0, green:0.18, blue: 0.20, alpha: 1.0).cgColor
        mainScrollView.colors = [color1, color2]
        mainScrollView.frame = CGRect(x: 0, y: 0, width: 375, height: 690)
        self.view.layer.addSublayer(mainScrollView)

Body:
I try the same and this works for me :

 self.MyItem.applyGradient_2(colours: [UIColor(red:0.09, green:0.91, blue:0.65, alpha:1.0), UIColor(red:0.08, green:0.92, blue:0.43, alpha:1.0)])

extension UIView {
    func applyGradient_2(colours: [UIColor]) -> Void {
        self.applyGradient_(colours: colours, locations: nil)
    }

    func applyGradient_(colours: [UIColor], locations: [NSNumber]?) -> Void {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colours.map { $0.cgColor }
        gradient.locations = locations
        self.layer.insertSublayer(gradient, at: 0)
    }
}


问:
iOS crash reporting, e.g. during beta testing
I'll be ready to start beta testing my iPhone app in the next month, and I guess I should be expecting it to crash once or twice. It would be nice to get the crash report -- and whatever supporting info I can -- back to the mothership. Ideally, this would require little to no work on the part of the beta testers.

There are tools and methods. So far for me, the most promising contender is CrashKit. I've also looked at Crash Reporter. And I've reviewed these Craig Hockenberry posts ("debugging with backups", "symbolicatifination") from 2008.

Am I overlooking something obvious? Any further advice, folks?

答:
Check out the iOS notifier for Airbrake.

http://airbrakeapp.com/


问:
Count of dates "This Month" to appear in a text box in Access Report
This seems simple but I haven't been able to find it anywhere. I just want to have a simple text box with a formula that pulls the count of dates for THIS MONTH from a specific field to populate on my Access Report.

Basically just trying to show for this month how many
Construction Starts: _______
Construction Completes: ________

Can any one help me with this?

Thanks,

Charles

答:
As Gustav provided this code works for producing a simple value counting the number of date fields in THIS MONTH. Just adapt what is in quotes to your table/fields. </p>

<p>=DCount("*","YourTable","[YourDateField] Between DateSerial(Year(Date()),Month(Date()),1) And DateSerial(Year(Date()),Month(Date())+1,0)")</p>

Body:
As Gustav provided this code works for producing a simple value counting the number of date fields in THIS MONTH. Just adapt what is in quotes to your table/fields.

=DCount("*","YourTable","[YourDateField] Between DateSerial(Year(Date()),Month(Date()),1) And DateSerial(Year(Date()),Month(Date())+1,0)")


问:
Building a manual sandbox for malware analysis
I want to build a manual sandbox to analyze malwares on Windows systems. I  mean a manual environment, not something automated like Cuckoo Sandbox.

There are many tools and I selected some of them, but I can't really see if each of this tool is worth it or not. Can you say me what you think and if these tools are useful for my sandbox?

First I consider some of them are unavoidables like IDA, winDBG, Wireshark, npcap, an HTTP Proxy like Fiddler, the Sysinternals suite, Volatility, maybe Foremost.

Then there are others tools I never really tried but which seems to be interesting. About static analysis, I have spotted the following tools and I would like to have an eventual feedback about it : Log-MD (a tool which look at the system using advanced Windows audit policies), Cerbero Profiler, Pestudio, Unpacker (it seems it is an automated tool to unpack binaries, seems faster but I am bit skeptical but I'm not a RE specialist, if you know this tool...), oledump.py by Didier Stevens (to identify various elements like heuristic patterns, IP, strings)...

About dynamic analysis, I noted Hook Analyzer (statically analyze elements with heuristic patterns and allow you to hook applications), Malheur (detect "malicious behavior"), ViperMonkey (detect VBA macro in Microsoft Office documents and emulate their behavior.

Do you have any recommandations about my setup and tools I could have forgotten? I want to analyze classic malicious elements (PE, PDF, various scripts, Office documents, ...).

About malware evasion, is there a risk a malware refuse to be analyzed while detecting RE and analysis tools?

Finally should I use Internet in the sandbox? Most of malwares today use C&C server and I see that some sandboxes are built with simulators like iNetSim but since the connection is not real, will I lost some information?

Thank's!

答:
You might want to consider the SEE framework to build your analysis platform.

Its plugins based design will allow you to integrate scanning tools in a pretty flexible manner.

Bear in mind that lots of malware inspect the execution environment and, if any RE tool will be spotted, will refuse to run.

For what concerns the Internet connection, it depends on how much information you want to gather. It is indeed true that lots of malware communicate with C&C nowadays, yet they must ensure their persistence on the target machine.

Therefore, the injection mechanism will still be executed even if Internet connection is absent. My 2 cents on the matter is to run without Internet by default and activate it only when necessary.


问:
Ionic prevent phone sleeping only when app is running
The Insomnia plugin promises to keep devices awake with window.plugins.insomnia.keepAwake(), until such time as window.plugins.insomnia.allowSleepAgain() is called.

But for some apps it only makes sense for the device to stay awake while the app is active. If the user pauses the app and forgets they have left it going in the background, it would be nice to allow sleep rather than decimate their battery level.

Typically actions required on app pause are handled through the pause event:

```<code>function onDeviceReady() {
    document.addEventListener("pause", onPause, false);
}

function onPause() {
    window.plugins.insomnia.allowSleepAgain();
}
</code>```

But according to Cordova docs, the Pause handler on iOS can't call anything native - which would include the Insomnia plugin.

How to achieve the desired functionality?

答:
You can use allowSleepAgain() with a $timeout and reinit the delay everytime you do something with keepAwakeforMinutes().

```<code>var keepAwakeforMinutes = function(minutes){
    // when an action is done,
    // cancel the last allowSleepAgain() $timeout if exists to create a new longer one
    if ($rootScope.sleeping){
        // alert("cancel previous timeout");
        $timeout.cancel( $rootScope.sleeping );
    }

    // be awake for the next minutes by creating a new timeout
    $window.plugins.insomnia.keepAwake();
    $rootScope.sleeping = $timeout(function() {
        // timeout ended
        $window.plugins.insomnia.allowSleepAgain();
    }, 60000*minutes); // awake for the next minutes
}
</code>```

Body:
The Insomnia plugin promises to keep devices awake with window.plugins.insomnia.keepAwake(), until such time as window.plugins.insomnia.allowSleepAgain() is called.

But for some apps it only makes sense for the device to stay awake while the app is active. If the user pauses the app and forgets they have left it going in the background, it would be nice to allow sleep rather than decimate their battery level.

Typically actions required on app pause are handled through the pause event:

function onDeviceReady() {
    document.addEventListener("pause", onPause, false);
}

function onPause() {
    window.plugins.insomnia.allowSleepAgain();
}

But according to Cordova docs, the Pause handler on iOS can't call anything native - which would include the Insomnia plugin.

How to achieve the desired functionality?

Body:
You can use allowSleepAgain() with a $timeout and reinit the delay everytime you do something with keepAwakeforMinutes().

var keepAwakeforMinutes = function(minutes){
    // when an action is done,
    // cancel the last allowSleepAgain() $timeout if exists to create a new longer one
    if ($rootScope.sleeping){
        // alert("cancel previous timeout");
        $timeout.cancel( $rootScope.sleeping );
    }

    // be awake for the next minutes by creating a new timeout
    $window.plugins.insomnia.keepAwake();
    $rootScope.sleeping = $timeout(function() {
        // timeout ended
        $window.plugins.insomnia.allowSleepAgain();
    }, 60000*minutes); // awake for the next minutes
}


问:
Query string (URL) lead to 403
Please help me on this.Already tried disable mode_security module through .htaccess no use.

PHP Version 5.6.30

Apache redirect the request to 403 page if pass parameter below.

&test[object_type]=0

The name (object_type) leads to 403 page.

eg:http://www.cudec.com.my/?test[object_type]=0 ✖ NOT WORKING LEADS TO 403

eg:http://www.cudec.com.my/?test[object_types]=0 ✓ WORKING

答:
Will update this post to a full answer as soon as I got more information to work with ;)

I tried to call the 403-URL:

```<code>You don't have permission to access / on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.
</code>```

You ensured that ModSecurity is the one replying with 403? Looks more like the folder permissions are insufficient.

Check if your DocumentRoot is at least readable for users (an 'r' at the last triple or 4 in the last byte).

If it's really ModSecurity, have a look into /var/log/apache2/modsecurity_audit.log and you should see which rule (by ID) is the one throwing 403 and also the reason (Error-Msg in the rule) why.

Does http://www.cudec.com.my/?test[object_types]=0 return the expected result?

The parameter doesn't seem to be interpretated when using &test[object_type] instead of &test[object_types] and the target ressource / seems to have insufficient rights, same for the error-pages...

Title: Query string (URL) lead to 403

Body:
Will update this post to a full answer as soon as I got more information to work with ;)

I tried to call the 403-URL:

You don't have permission to access / on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

You ensured that ModSecurity is the one replying with 403? Looks more like the folder permissions are insufficient.

Check if your DocumentRoot is at least readable for users (an 'r' at the last triple or 4 in the last byte).

If it's really ModSecurity, have a look into /var/log/apache2/modsecurity_audit.log and you should see which rule (by ID) is the one throwing 403 and also the reason (Error-Msg in the rule) why.

Does http://www.cudec.com.my/?test[object_types]=0 return the expected result?

The parameter doesn't seem to be interpretated when using &test[object_type] instead of &test[object_types] and the target ressource / seems to have insufficient rights, same for the error-pages...


问:
How to find logic operators in string with regex?
Lets say logic expression looks like this:

```<code>(A || B) && (C | D)
</code>```

I would like to write regular expression that searches for both || and | characters inside the expression.

This is regex I currently use to find most of the other logic operators:

```<code>/AND|OR|and|or|XOR|&&|<=|<|>|>=|!=|==|&|OR*|!/gi
</code>```

So how to update currently looking regex to search for these two operators also?

Please note that it must be in similar form like it is now with operators divided with | sign (thats where my troubles come from i guess).

I tried doing it like this:

```<code>/AND|OR|and|or|XOR|&&|<=|<|>|>=|!=|==|&|OR*|!|\/[|]\/|\/(|)*\//gi
</code>```

But it doesn't matches my logic expression.

答:
try this:

```<code>AND|OR|and|or|XOR|&&|<=|<|>|>=|!=|==|&|OR*|!|[||]{2}|\|
</code>```

Also you can test out these regexes, over here: http://regexr.com/

Body:
Lets say logic expression looks like this:

(A || B) && (C | D)

I would like to write regular expression that searches for both || and | characters inside the expression.

This is regex I currently use to find most of the other logic operators:

/AND|OR|and|or|XOR|&&|<=|<|>|>=|!=|==|&|OR*|!/gi

So how to update currently looking regex to search for these two operators also?

Please note that it must be in similar form like it is now with operators divided with | sign (thats where my troubles come from i guess).

I tried doing it like this:

/AND|OR|and|or|XOR|&&|<=|<|>|>=|!=|==|&|OR*|!|\/[|]\/|\/(|)*\//gi

But it doesn't matches my logic expression.

Body:
try this:

AND|OR|and|or|XOR|&&|<=|<|>|>=|!=|==|&|OR*|!|[||]{2}|\|

Also you can test out these regexes, over here: http://regexr.com/


问:
Create assignment executable script
Whats going on so for my unix/linux class the teacher wants us to create a create_assignment executable to use for all of our work or he takes off points. I have been trying for a week now and asked the teacher twice and it hasn't helped at all. so when I type ./create_assignment assignment3 it is suppose to make assignment 3 with a header I know I'm suppose to use chmod +x create_assignment to make it executable. I got it to make a create_assignment executable one time but it wouldnt do anything so I need to be shown how to make it executable and make it create the new assignment, I can post pictures if needed. </p>

答: I am guessing you tried chmod u+x  to make it executable?</p>

Title: Create assignment executable script


问:
Is there any Python3 compatible module to read/write IPTC-data?
I've already tried IPTCInfo3.
But after successful installation with

```<code>pip3 install IPTCInfo
</code>```

i get an import error:

```<code>Python 3.5.2 (default, Oct 11 2016, 04:59:56)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin

from iptcinfo import IPTCInfo

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
ImportError: No module named 'iptcinfo'
</code>```

答:
pip install IPTCinfo is what you don't want - it's the python2 only package. What you linked to isn't on PyPI, but that doesn't mean you can't install it!

Download the zip file from github, extract it, and in the resulting folder run:
python setup.py install. I ran into an issue with the file naming, not sure if it was just a result of something I had done though - you can just open up setup.py and change py_modules=['iptcinfo3'], to py_modules=['iptcinfo'], if you get the same issue about there being no iptcinfo3 module.

From there you should be able to import as you normally would. I just ran a command for it and it worked.

Body:
I've already tried IPTCInfo3.
But after successful installation with

pip3 install IPTCInfo

i get an import error:

Python 3.5.2 (default, Oct 11 2016, 04:59:56)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin

from iptcinfo import IPTCInfo

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
ImportError: No module named 'iptcinfo'


问:
Qt moc_mainwindow
I'm developing an application (with OpenCV) where I created a scroll bar and functions related but finally I deleted the scroll bar. The following error occures :

moc_mainwindow.cpp:-1: erreur : undefined reference to MainWindow::on_verticalScrollBar_actionTriggered(int)'

moc_mainwindow.cpp:-1: erreur : undefined reference to MainWindow::on_verticalScrollBar_sliderPressed()'

:-1: erreur : release/moc_mainwindow.o: bad reloc address 0x4 in section `.data'

collect2.exe:-1: erreur : error: ld returned 1 exit status

Thanks for help

答:
The errors undefined reference to `MainWindow::...' are caused by the fact that you have functions declared in mainwindow.h but not defined anywhere.

To fix this either define them in mainwindow.cpp or remove their declarations from mainwindow.h. If you do not have use for them obviously you should remove them.

Now about "Qt shows an error about functions over sth that does'nt exist yet" you might be referring to QMetaObject::connectSlotsByName: No matching signal for ....

This might happen if you have one or more slots named on_<objectName>_<signalName> (e.g on_verticalScrollBar_sliderPressed and on_verticalScrollBar_sliderPressed) but the object objectName does not exist or it exists but has no signal named signalName.

This is caused by QMetaObject::connectSlotsByName() which is called inside the call to ui->setupUi(). This function will try to connect every slot matching the on_<objectName>_<signalName> syntax and will write warnings to stderr (or the debug output) when it fails.

Also I strongly suggest you do not use QMetaObject::connectSlotsByName() and the on_<objectName>_<signalName> syntax. If you use .ui files you cannot prevent the call to QMetaObject::connectSlotsByName() as it is in generated code but if you do not use the syntax it will have no effect.
Instead you should connect signals and slots explicitly in your code.

See:

[QTBUG-49749] connectSlotsByName() misconnects slots when multiple children have the same name

"Proposal to change connectSlotsByName behavior" in Qt developer mailing list

Title: Qt moc_mainwindow


问:
How do I reset master and keep my branch in git?
Suppose I do

```<code>$ git checkout master
$ touch foo.py
$ git commit -m "oops" foo.py
$ git checkout -b new_branch
$ touch bar.py
$ git commit -m "changes" bar.py
</code>```

Now when I try to push back changes on new_branch, I get

```<code>Local branch 'master' is ahead of remote branch 'origin/master'
</code>```

How do I reset master while not losing my changes (foo.py, bar.py) on new_branch?

I read the git reset page, and it looked like it might involve --keep, but I couldn't tell.

答:
This can be very confusing initially, and what you needed was a proper introduction to how Git implements branches; but at this point we'll use the retrofit method. :-)  The trick to understanding all this is that Git's commits are permanent and unchanging, but its branches—or more precisely, branch names—are temporary, and in fact mostly irrelevant.

There are three things that matter when you are building a new commit (they are HEAD, the index, and the work-tree), but once you have the commit built and committed, it's quite permanent and it is very hard to get Git to lose it entirely.  It's easy enough to accidentally misplace it, though, so let's try to avoid that. :-)

If we ignore the branch names entirely, we can draw a graph of the commits that exist in your repository.  Given what you have done—making two new commits—let's draw them like this, where round os represent commits, and A and B are your two new commits:

```<code>...--o--o--o
            \
             A
              \
               B
</code>```

We could draw them all on one line, but I want to leave room to write labels in on the right.  Commit A is your "oops", and B is your "changes".

The main noteworthy thing about this graph drawing is that each commit points to (stores the hash ID of) its predecessor commit.  This means that commit B points back to commit A.  Commit A points back to the next-most-recent commit, which points back still further, and so on.

Now we add the labels—the branch names.  The last boring commit o still probably has a label origin/master.  Commit A has the label master, and commit B has the label new_branch, so let's draw these in:

```<code>...--o--o--o   <-- origin/master
            \
             A   <-- master
              \
               B   <-- new_branch (HEAD)
</code>```

This is what branch names are and do for you: they are pointers to commits; they remember each commit's big ugly hash ID for you.

When you are on some branch and make a new commit, the branch name comes along for the ride.  The special name HEAD remembers which branch you're on, so that Git knows which name to move to the new commit.  (We needed this temporarily at least, when master and new_branch briefly both pointed to commit A.)

What you want to do now is move master back to point to the last of the boring o commits.  To do so, you can use git reset, which lets you move a name in an arbitrary way:

```<code>git checkout master
git reset --hard origin/master
</code>```

This assumes (see final section below) that origin/master really does point to the last of the boring o commits.  The git reset --hard says: Wipe out my current index and work-tree, and move my current branch—according to HEAD—so that it points to the commit I name here.  We must git checkout master first, so that HEAD names master.  Then the git reset does this:

```<code>...--o--o--o   <-- master (HEAD), origin/master
            \
             A
              \
               B   <-- new_branch
</code>```

So now your two new commits A and B are found only via new_branch and not via master.

(There are several more things that branch names do for you.  In particular, they protect commits from being removed by Git's "garbage collector".  If a commit has any name by which we can find it, it's protected.  If it has no name, it's no longer protected.  There are some semi-hidden names that protect everything for a while—at least 30 days by default—to make sure commits don't get trashed accidentally, but finding them through these reflog names is annoying, so we try not to rely on it so much.

The branch names are also used for git push, so there they matter a fair bit.)

(I mention "trashing" the index and work-tree above, which isn't completely true.  The git reset command, used the way we're using it here, has three jobs it can do:

move the current branch

reset the index

reset the work-tree

It always does the first, optionally adds the second job, and then optionally adds the third.  The --hard mode does all three, the --mixed mode does the first two, and the --soft mode does only one.  To understand them all properly, we would have to look closely at the definitions of index and work-tree and I'll leave that for other SO questions/answers.  The key item here, though, is that you don't want to git reset --hard until you have everything saved away in commits.)

What if there's no origin/master (or it points back too far)?

We assumed, above, that there was a handy label—a so-called remote-tracking branch—identifying the commit we want to git reset our master to point-to.  If we don't have this label, or it points to an even earlier commit, we must locate that commit some other way.

There are a lot of ways to do this.  The most straightforward is to go by its hash ID.  If you run git log while on some branch, you see each commit that is "on" or "contained in" that branch, normally in Git's usual backwards-going order.  For instance, we might git log and see commit B, with its big ugly hash ID, then commit A with its hash ID, and then that boring commit o with its big ugly hash ID.

We can use the raw hash ID:

```<code>git checkout master && git reset --hard <hash-id>
</code>```

if we don't have the label.  If we do have the label, we should probably just use it.

You might remember to get help from "A DOG" with git log:

```<code>git log --all --decorate --oneline --graph
</code>```

The all makes Git show all branches and all remote-tracking branches (and everything else: tags, the "stash", notes, etc).  The decorate option attaches the label names to commits.  The oneline option makes the output show just one line for each commit, and the graph option makes Git try to draw the commit graph.

Body:
Suppose I do

$ git checkout master
$ touch foo.py
$ git commit -m "oops" foo.py
$ git checkout -b new_branch
$ touch bar.py
$ git commit -m "changes" bar.py

Now when I try to push back changes on new_branch, I get

Local branch 'master' is ahead of remote branch 'origin/master'

How do I reset master while not losing my changes (foo.py, bar.py) on new_branch?

I read the git reset page, and it looked like it might involve --keep, but I couldn't tell.

Body:
This can be very confusing initially, and what you needed was a proper introduction to how Git implements branches; but at this point we'll use the retrofit method. :-)  The trick to understanding all this is that Git's commits are permanent and unchanging, but its branches—or more precisely, branch names—are temporary, and in fact mostly irrelevant.

There are three things that matter when you are building a new commit (they are HEAD, the index, and the work-tree), but once you have the commit built and committed, it's quite permanent and it is very hard to get Git to lose it entirely.  It's easy enough to accidentally misplace it, though, so let's try to avoid that. :-)

If we ignore the branch names entirely, we can draw a graph of the commits that exist in your repository.  Given what you have done—making two new commits—let's draw them like this, where round os represent commits, and A and B are your two new commits:

...--o--o--o
            \
             A
              \
               B

We could draw them all on one line, but I want to leave room to write labels in on the right.  Commit A is your "oops", and B is your "changes".

The main noteworthy thing about this graph drawing is that each commit points to (stores the hash ID of) its predecessor commit.  This means that commit B points back to commit A.  Commit A points back to the next-most-recent commit, which points back still further, and so on.

Now we add the labels—the branch names.  The last boring commit o still probably has a label origin/master.  Commit A has the label master, and commit B has the label new_branch, so let's draw these in:

...--o--o--o   <-- origin/master
            \
             A   <-- master
              \
               B   <-- new_branch (HEAD)

This is what branch names are and do for you: they are pointers to commits; they remember each commit's big ugly hash ID for you.

When you are on some branch and make a new commit, the branch name comes along for the ride.  The special name HEAD remembers which branch you're on, so that Git knows which name to move to the new commit.  (We needed this temporarily at least, when master and new_branch briefly both pointed to commit A.)

What you want to do now is move master back to point to the last of the boring o commits.  To do so, you can use git reset, which lets you move a name in an arbitrary way:

git checkout master
git reset --hard origin/master

This assumes (see final section below) that origin/master really does point to the last of the boring o commits.  The git reset --hard says: Wipe out my current index and work-tree, and move my current branch—according to HEAD—so that it points to the commit I name here.  We must git checkout master first, so that HEAD names master.  Then the git reset does this:

...--o--o--o   <-- master (HEAD), origin/master
            \
             A
              \
               B   <-- new_branch

So now your two new commits A and B are found only via new_branch and not via master.

(There are several more things that branch names do for you.  In particular, they protect commits from being removed by Git's "garbage collector".  If a commit has any name by which we can find it, it's protected.  If it has no name, it's no longer protected.  There are some semi-hidden names that protect everything for a while—at least 30 days by default—to make sure commits don't get trashed accidentally, but finding them through these reflog names is annoying, so we try not to rely on it so much.

The branch names are also used for git push, so there they matter a fair bit.)

(I mention "trashing" the index and work-tree above, which isn't completely true.  The git reset command, used the way we're using it here, has three jobs it can do:

move the current branch

reset the index

reset the work-tree

It always does the first, optionally adds the second job, and then optionally adds the third.  The --hard mode does all three, the --mixed mode does the first two, and the --soft mode does only one.  To understand them all properly, we would have to look closely at the definitions of index and work-tree and I'll leave that for other SO questions/answers.  The key item here, though, is that you don't want to git reset --hard until you have everything saved away in commits.)

What if there's no origin/master (or it points back too far)?

We assumed, above, that there was a handy label—a so-called remote-tracking branch—identifying the commit we want to git reset our master to point-to.  If we don't have this label, or it points to an even earlier commit, we must locate that commit some other way.

There are a lot of ways to do this.  The most straightforward is to go by its hash ID.  If you run git log while on some branch, you see each commit that is "on" or "contained in" that branch, normally in Git's usual backwards-going order.  For instance, we might git log and see commit B, with its big ugly hash ID, then commit A with its hash ID, and then that boring commit o with its big ugly hash ID.

We can use the raw hash ID:

git checkout master && git reset --hard <hash-id>

if we don't have the label.  If we do have the label, we should probably just use it.

You might remember to get help from "A DOG" with git log:

git log --all --decorate --oneline --graph

The all makes Git show all branches and all remote-tracking branches (and everything else: tags, the "stash", notes, etc).  The decorate option attaches the label names to commits.  The oneline option makes the output show just one line for each commit, and the graph option makes Git try to draw the commit graph.


问:
SignalR class method callback and 'this'
I had a similar question but not the same. This one focuses on the new ES6 class keyword and how to handle this. SignalR is calling a class method. When inside that class method 'this' refers to the SignalR hub not the class instance itself. How can I get the class instance inside this class member that SignalR called using the new ES6 classes?</p>

```<code>class gameLoad {
    constructor(){

    }

    init(){
        // create the network object and hook it's functions update for loading
        this.network = $.connection.testHub;
        this.network.client.hello = this.sayHello;
    }

    // this is called from signalR and 'this' now refers to the signalR hub inside this function. how can I get the class instance?
    sayHello(){
        console.log(this);    // 'this' refers to signalR object not gameLoad object
    }

    create(){
        var self = this;
        $.connection.hub.start().done(function () {
            console.log("Started!")
            console.log("Calling server function.");

            // make our first network call which will turn around and call client.hello which is bound to this classes sayHello() member function
            self.network.server.hello();
        });
    }
}
</code>```

答:
When using classes, it's best to use arrow functions so that you have 'this' properly set.

In your example, you assign sayHello to client's hello method.  You will need to bind gameLoad to it at that time:

```<code>this.network.client.hello = this.sayHello.bind(gameLoad);
</code>```

Alternatively, you can convert sayHello into an arrow function:

```<code>sayHello = () => {
</code>```

Body:
I had a similar question but not the same. This one focuses on the new ES6 class keyword and how to handle this. SignalR is calling a class method. When inside that class method 'this' refers to the SignalR hub not the class instance itself. How can I get the class instance inside this class member that SignalR called using the new ES6 classes?

class gameLoad {
    constructor(){

    }

    init(){
        // create the network object and hook it's functions update for loading
        this.network = $.connection.testHub;
        this.network.client.hello = this.sayHello;
    }

    // this is called from signalR and 'this' now refers to the signalR hub inside this function. how can I get the class instance?
    sayHello(){
        console.log(this);    // 'this' refers to signalR object not gameLoad object
    }

    create(){
        var self = this;
        $.connection.hub.start().done(function () {
            console.log("Started!")
            console.log("Calling server function.");

            // make our first network call which will turn around and call client.hello which is bound to this classes sayHello() member function
            self.network.server.hello();
        });
    }
}

Body:
When using classes, it's best to use arrow functions so that you have 'this' properly set.

In your example, you assign sayHello to client's hello method.  You will need to bind gameLoad to it at that time:

this.network.client.hello = this.sayHello.bind(gameLoad);

Alternatively, you can convert sayHello into an arrow function:

sayHello = () => {


问:
inserting text into SQL from a drop down list in C#
Help is very much needed and appreciated. I am working on a project that requires me to select a value from a drop down menu, and insert it into my database. The drop down list is loaded through a stored proc and data binding, and works well. But when I press the button to insert the data, it will ONLY insert the default text -- Select Chemical -- , or if that is not there, it will insert whatever is in the first selection. It never sees the other items.

My CONTENT Code:

```<code><table width="95%" style="padding-left:200px; padding-top:50px">
    <tr>
        <td style="font-size:large; font-weight:bold; padding-bottom:50px">
            <asp:DropDownList ID="ChemLot" runat="server">
            </asp:DropDownList>
        </td>
    </tr>
    <tr>
         <td colspan="2" align="center" >
            <asp:Label ID="lblchemMessage" runat="server" Visible="false" />
        </td>
    </tr>
    <tr>
        <td colspan="2" align="center" >
        <br />
        <br />
             <asp:Button ID="AddChemLots" OnClick= "AddChemLot2" Text="Add New Chemical Lot" Font-Bold="true" runat="server" Height="50px" Width="250px" BackColor="Azure" />
        </td>

    </tr>
</table>
</code>```

The Code BEHIND:

```<code>protected void AddChemLot2(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        String chemical = ChemLot.SelectedItem.Text.ToString();
        SqlConnection m_sqlConnection;
        string m_connectionString = ConfigurationManager.ConnectionStrings["ChemicalConnectionString"].ConnectionString;

        using (m_sqlConnection = new SqlConnection(m_connectionString))
        using (SqlCommand cmd = new SqlCommand("Insert_Chem"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = m_sqlConnection;
                m_sqlConnection.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@ChemName", chemical);
            }

            int check = cmd.ExecuteNonQuery();
            m_sqlConnection.Close();
</code>```

My Page_Load:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        LoadList();
    }
}

public void LoadList()
{
    string constr = ConfigurationManager.ConnectionStrings["ChemicalConnectionString"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Load_Chem"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                ChemLot.DataSource = cmd.ExecuteReader();
                ChemLot.DataTextField = "Chemical";
                ChemLot.DataBind();
                con.Close();
            }
        }
</code>```

答:
You should use SelectedItem.Value or SelectedValue instead like

```<code>String chemical = ChemLot.SelectedItem.Value.ToString();
</code>```

Additional: There is no point in checking the below condition inside event handler since it will always be true

```<code>if (Page.IsPostBack)
{
</code>```

As I see from your current edit: you have below. You haven't specified the DataValueField at all anywhere.

```<code>ChemLot.DataTextField = "Chemical";
ChemLot.DataBind();
</code>```

You should specify both

```<code>ChemLot.DataTextField = "Chemical";
ChemLot.DataValueField = <something>;
ChemLot.DataBind();
</code>```

Body:
Help is very much needed and appreciated. I am working on a project that requires me to select a value from a drop down menu, and insert it into my database. The drop down list is loaded through a stored proc and data binding, and works well. But when I press the button to insert the data, it will ONLY insert the default text -- Select Chemical -- , or if that is not there, it will insert whatever is in the first selection. It never sees the other items.

My CONTENT Code:

            <asp:DropDownList ID="ChemLot" runat="server">
            </asp:DropDownList>

            <asp:Label ID="lblchemMessage" runat="server" Visible="false" />

             <asp:Button ID="AddChemLots" OnClick= "AddChemLot2" Text="Add New Chemical Lot" Font-Bold="true" runat="server" Height="50px" Width="250px" BackColor="Azure" />

The Code BEHIND:

protected void AddChemLot2(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        String chemical = ChemLot.SelectedItem.Text.ToString();
        SqlConnection m_sqlConnection;
        string m_connectionString = ConfigurationManager.ConnectionStrings["ChemicalConnectionString"].ConnectionString;

        using (m_sqlConnection = new SqlConnection(m_connectionString))
        using (SqlCommand cmd = new SqlCommand("Insert_Chem"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = m_sqlConnection;
                m_sqlConnection.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@ChemName", chemical);
            }

            int check = cmd.ExecuteNonQuery();
            m_sqlConnection.Close();

My Page_Load:

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        LoadList();
    }
}

public void LoadList()
{
    string constr = ConfigurationManager.ConnectionStrings["ChemicalConnectionString"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Load_Chem"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                ChemLot.DataSource = cmd.ExecuteReader();
                ChemLot.DataTextField = "Chemical";
                ChemLot.DataBind();
                con.Close();
            }
        }

Body:
You should use SelectedItem.Value or SelectedValue instead like

String chemical = ChemLot.SelectedItem.Value.ToString();

Additional: There is no point in checking the below condition inside event handler since it will always be true

if (Page.IsPostBack)
{

As I see from your current edit: you have below. You haven't specified the DataValueField at all anywhere.

ChemLot.DataTextField = "Chemical";
ChemLot.DataBind();

You should specify both

ChemLot.DataTextField = "Chemical";
ChemLot.DataValueField = <something>;
ChemLot.DataBind();


问:
Prepared statements using MySQL not inserting POST values to database table
I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.

The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly

Main script:

```<code><?php

include connect.db;

//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";

//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
    $stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
    $stmt->bind_param("ssss", $type, $username, $password, $email);
    $stmt->execute();
    $stmt->close();
    echo "User Registered";
}
else {
    echo "Username, password or email are already used";
}

?>
</code>```

Connection Script:

```<code><?php
//Identifies the databases details.

//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";

/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
    die("Connection failed: " . mysqli_connect_error());
}

?>
</code>```

edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.

答:
Try to see the errors </p>

```<code>error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}
</code>```

Body:
I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.

The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly

Main script:

<?php

include connect.db;

//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";

//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
    $stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
    $stmt->bind_param("ssss", $type, $username, $password, $email);
    $stmt->execute();
    $stmt->close();
    echo "User Registered";
}
else {
    echo "Username, password or email are already used";
}

?>

Connection Script:

<?php
//Identifies the databases details.

//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";

/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
    die("Connection failed: " . mysqli_connect_error());
}

?>

edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.

Body:
Try to see the errors

error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}


问:
What is the topic path in microsoft service bus?
For this method:

```<code>public static SubscriptionClient CreateFromConnectionString(string connectionString, string topicPath, string name)
</code>```

What is the topicPath?

MSDN says it is "The full pathname of the topic."

What is the pathname?

There are code examples, but I have yet to find one that explain this little detail.

答:
Topic path is the same string that was used as topic's name to create it. See examples here: https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-how-to-use-topics-subscriptions

Note ASB names are subject to some limitations: https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-quotas

Body:
For this method:

public static SubscriptionClient CreateFromConnectionString(string connectionString, string topicPath, string name)

What is the topicPath?

MSDN says it is "The full pathname of the topic."

What is the pathname?

There are code examples, but I have yet to find one that explain this little detail.


问:
phpStorm 7 update docblock
Is there a way to ask phpStorm to update the contents of a docblock? eg if I have the following code

```<code>//-------------------------------------------------------------------------
/**
 * @param string $url
 * @return $this
 */
public function setBaseUrl($url)
{
    $this->baseUrl = $url;
    return $this;
}
</code>```

and add another parameter

```<code>//-------------------------------------------------------------------------
/**
 * @param string $url
 * @return $this
 */
public function setBaseUrl($url, $anotherParameter)
{
    $this->baseUrl = $url;
    return $this;
}
</code>```

is there a way to ask phpStorm to create the @param $anotherParameter in my docblock? (in a single keystroke or by menu selection)?

答: In the new version of PHPStorm 2016.x you need to place your cursor in the missing variable name and press alt + enter then hit again enter to add the missing param to the doc block. If you need to remove a parameter you need to go to the extra param and press the same key strokes.

Title: phpStorm 7 update docblock

Body:
Is there a way to ask phpStorm to update the contents of a docblock? eg if I have the following code

//-------------------------------------------------------------------------
/**
 * @param string $url
 * @return $this
 */
public function setBaseUrl($url)
{
    $this->baseUrl = $url;
    return $this;
}

and add another parameter

//-------------------------------------------------------------------------
/**
 * @param string $url
 * @return $this
 */
public function setBaseUrl($url, $anotherParameter)
{
    $this->baseUrl = $url;
    return $this;
}

is there a way to ask phpStorm to create the @param $anotherParameter in my docblock? (in a single keystroke or by menu selection)?