问:
CodeIgniter - Display HTML DOM using Ajax
I use CodeIgniter as my PHP framework and use jQuery/AJAX to process requests. If I would return data from an AJAX request, and would like to append it to my page with HTML elements on it, where should the HTML elements be included?

In the Model? Where you handle SQL queries.

```<code>class Item_model extendes CI_Model {

    public function getAll()
    {
        $html = '';
        $query = $this->db->query("SELECT col1 FROM table1");
        foreach ($query->result() as $row)
        {
            $html .= '<span>'.$row->col1.'</span>';
        }
        return json_encode(array('html' => $html));
    }
</code>```

Or in the Controller?

```<code>class Item extends CI_Controller {

    public function item_list()
    {
        $html = '';
        $data = $this->Item_model->getAll();
        foreach($data as $dataitem){
            $html .= '<span>'.$dataitem['col1'].'</span>';
        }

        echo json_encode(array('html' => $html));

    }
</code>```

Or in the Javascript?

```<code>success: function(result){

    $.each(result.col1, function(k, v) {
        $("#div").append('<span>'+v+'</span>');
    });

}
</code>```

I've been thinking of the standard/conventional way to do it. But if I have to guess, I would go for the controller.

答:
Should be in the Javascript. It will avoid redundant data(span tag) transactions.

Over all process as follows,

Send your ajax request from view to controller, then pass the inputs to the model to do the DB operations and return the DB result array to the controller. Echo the result array after json_encoded.

view->controller->model->controller->view

Body:
I use CodeIgniter as my PHP framework and use jQuery/AJAX to process requests. If I would return data from an AJAX request, and would like to append it to my page with HTML elements on it, where should the HTML elements be included?

In the Model? Where you handle SQL queries.

class Item_model extendes CI_Model {

    public function getAll()
    {
        $html = '';
        $query = $this->db->query("SELECT col1 FROM table1");
        foreach ($query->result() as $row)
        {
            $html .= ''.$row->col1.'';
        }
        return json_encode(array('html' => $html));
    }

Or in the Controller?

class Item extends CI_Controller {

    public function item_list()
    {
        $html = '';
        $data = $this->Item_model->getAll();
        foreach($data as $dataitem){
            $html .= ''.$dataitem['col1'].'';
        }

        echo json_encode(array('html' => $html));

    }

Or in the Javascript?

success: function(result){

    $.each(result.col1, function(k, v) {
        $("#div").append(''+v+'');
    });

}

I've been thinking of the standard/conventional way to do it. But if I have to guess, I would go for the controller.


来源: stackexchange

问:
Output full difference between expected and actual list in assertj
I am using groovy, assertj, junit and gradle. I have a test that contains assertion like that

```<code>assertThat(actualLongList).isEqualTo(expectedLongList)
</code>```

When I run gradle test and those lists are not equal, it generates a test report with an exception like that

```<code>org.junit.ComparisonFailure: expected:<...ent2",
"element3",
"element4",
"element5]"]> but was:<...ent2",
"element4,
"element5",
"element6]"]>
</code>```

Can I somehow configure exception output format so it will fully output both lists?

```<code> org.junit.ComparisonFailure: expected:
<["element1",
"element2",
"element3",
"element3",
"element4",]> but was:,
<["element1",
"element2",
"element4",
"element5",
"element6",]>
</code>```

答:
That's how org.junit.ComparisonFailure#getMessage() works (see javadoc).
If you want to have a full (better ?) description, you can use containsOnlyElementsOf (or any containsXxxElementsOf you see fit), you will get something like:

java.lang.AssertionError:
Expecting:
  <["element1",
    "element2",
    "element3",
    "element4",
    "element5",
    "element6",
    "element7",
    "element8",
    "element9"]>
to contain only:
  <["element1",
    "element2",
    "element3",
    "element4",
    "element5",
    "element6",
    "element7",
    "element8",
    "element0"]>
elements not found:
  <["element0"]>
and elements not expected:
  <["element9"]>

ContentLicense: CC BY-SA 3.0

Body:
I am using groovy, assertj, junit and gradle. I have a test that contains assertion like that

assertThat(actualLongList).isEqualTo(expectedLongList)

When I run gradle test and those lists are not equal, it generates a test report with an exception like that

org.junit.ComparisonFailure: expected:<...ent2",
"element3",
"element4",
"element5]"]> but was:<...ent2",
"element4,
"element5",
"element6]"]>

Can I somehow configure exception output format so it will fully output both lists?

 org.junit.ComparisonFailure: expected:
<["element1",
"element2",
"element3",
"element3",
"element4",]> but was:,
<["element1",
"element2",
"element4",
"element5",
"element6",]>


问:
SSL/TLS dynamic key generation
On this project of mine I needed to implement secure connection using SSL/TLS between a client and a server. I found a good article about that so I've managed to do my task without any problem.

This is the article.

My question is pretty simple but I cannot find an answer anywhere. In this particular case, my clients have the same key in the SSL protocol which is created through tutorial on a previous link and put in some kind of a file. Potential problem in this process is that someone can access that file and since every client has that key, someone can listen to all connections.

What I wanted to ask, is there any chance to dynamically generate keys every time some client wants to access the server and put the generated key in the server truststore?

UPDATE

```<code>public static final String PATH_TO_ANDROID_KEYSTORE = "and/client.bks";
public static final String PATH_TO_ANDROID_TRUSTSTORE = "and/clienttruststore.bks";

String pathToKeyStore = PATH_TO_ANDROID_KEYSTORE;
String pathToTrustStore = PATH_TO_ANDROID_TRUSTSTORE;

KeyStore keyStoreKeys = KeyStore.getInstance(keyStoreType);
keyStoreKeys.load(Gdx.files.internal(pathToKeyStore).read(), passphrase);

KeyStore keyStoreTrust = KeyStore.getInstance(keyStoreType);
keyStoreTrust.load(Gdx.files.internal(pathToTrustStore).read(), passphrase);

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStoreKeys, passphrase);

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStoreTrust);
</code>```

This is the client code and seems like clients have exported server's certificates in their truststores but they actually use the same private key that is generated only once in the keystore using openssl tool.

答:
In this particular case, my clients have the same key in the SSL protocol which is created through tutorial on a previous link and put in some kind of a file.

Unclear. Do you mean they share the same private key? If so, that is a flaw in your system design. Every client should have its own private key. Otherwise the private key isn't, err, private. And access to that key should be via a keystore whose password only the applicion knows, which provides at least another line of defence.

If you just mean that they all have an exported copy of the server's certificate, in their truststores, there is no security risk attached to that at all: it is perfectly normal.

Potential problem in this process is that someone can access that file and since every client has that key, someone can listen to all connections.

No they can't. SSL is immune to man-in-the-middle attacks provided you don't compromise your server's private key, but if you're talking about client private keys they can masquerade as a real client even if they aren't, if they can break through the keystore-password barrier.

What I wanted to ask, is there any chance to dynamically generate keys every time some client wants to access the server and put the generated key in the server truststore?

Not securely, and not online. If your genuine clients can do it, so can an attacker. That's why trust material must be distributed offline.

Title: SSL/TLS dynamic key generation

Body:
On this project of mine I needed to implement secure connection using SSL/TLS between a client and a server. I found a good article about that so I've managed to do my task without any problem.

This is the article.

My question is pretty simple but I cannot find an answer anywhere. In this particular case, my clients have the same key in the SSL protocol which is created through tutorial on a previous link and put in some kind of a file. Potential problem in this process is that someone can access that file and since every client has that key, someone can listen to all connections.

What I wanted to ask, is there any chance to dynamically generate keys every time some client wants to access the server and put the generated key in the server truststore?

UPDATE

public static final String PATH_TO_ANDROID_KEYSTORE = "and/client.bks";
public static final String PATH_TO_ANDROID_TRUSTSTORE = "and/clienttruststore.bks";

String pathToKeyStore = PATH_TO_ANDROID_KEYSTORE;
String pathToTrustStore = PATH_TO_ANDROID_TRUSTSTORE;

KeyStore keyStoreKeys = KeyStore.getInstance(keyStoreType);
keyStoreKeys.load(Gdx.files.internal(pathToKeyStore).read(), passphrase);

KeyStore keyStoreTrust = KeyStore.getInstance(keyStoreType);
keyStoreTrust.load(Gdx.files.internal(pathToTrustStore).read(), passphrase);

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStoreKeys, passphrase);

TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStoreTrust);

This is the client code and seems like clients have exported server's certificates in their truststores but they actually use the same private key that is generated only once in the keystore using openssl tool.


问:
how to use gem cancancan in layouts/application (in rails) ? it doesn't has controller to add authorize_resource?
how to use gem cancancan in layouts/application (rails) ?   it doesn't has controller to add authorize_resource ?
I want to use gems cancancan and rolify to manage layouts/application
navagation.</p>

答:
it needn't add authorize_resource to controller.

just add some code:(app/views/layouts/application.html.erb)

  .......(yeild)

app/models/ability.rb

class Ability
  include CanCan::Ability

def initialize(user)
    if user.blank?
      cannot :manage, :all

    elsif user.has_role? :admin
      can :manage, :all
  end
end

Then,  only the user which role is "admin" can see (yeild).


问:
Issue with Facebook integration with AWS Lex : Give bot access to facebook friends
I have created, built and published a sample lex bot.

I followed steps in this link to deploy bot on Facebook messenger. ( by creatign facebook page, fb app and adding webhook etc)
 http://docs.aws.amazon.com/lex/latest/dg/fb-bot-association.html

For creating FB app and page I used my Facebook credentials.

Issue:
I am able to interact with bot from facebook messenger ( with my facebook account)  and getting desired response from bot

However, when my facebook friend interacts with bot using his facebook account, he doesn't get any response.

Am I missing something here ?

答: I think your Facebook App is in development mode, so you need to add your friend as a Tester in the role tab, or let Facebook approve your App.</p>


问:
using lexical this in ES6
I was learning about lexical this in ES6, and I countered this example :

```<code>let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : function(){
    for(let car of cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

person.toString();
</code>```

so let's say I want to convert the toString function to an array function so I'll have this :

```<code>let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : () => {
    for(let car of cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

person.toString();
</code>```

in this example cars is undefined, why I'm getting that, and how can I call cars from the person object in that example.

the same goes for this :

```<code>let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : () => {
    cars.forEach(car => console.log(`${this.name} has ${car}`));
  }
}

person.toString();
</code>```

答:
Because of your arrow function that your this apply to your object which the function you called.

correct

```<code>let person = {
  name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : function() {
   this.cars.forEach(car=>{
        console.log(`${this.name} has ${car}`)
    })
  }
}

person.toString();
</code>```

The last arrow function in foreach is apply this of your object that why you didn't need to use clourse like this.cars.forEach(...)(this.name).

Title: using lexical this in ES6

Body:
I was learning about lexical this in ES6, and I countered this example :

let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : function(){
    for(let car of cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

person.toString();

so let's say I want to convert the toString function to an array function so I'll have this :

let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : () => {
    for(let car of cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

person.toString();

in this example cars is undefined, why I'm getting that, and how can I call cars from the person object in that example.

the same goes for this :

let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : () => {
    cars.forEach(car => console.log(`${this.name} has ${car}`));
  }
}

person.toString();

Body:
Because of your arrow function that your this apply to your object which the function you called.

correct

let person = {
  name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : function() {
   this.cars.forEach(car=>{
        console.log(`${this.name} has ${car}`)
    })
  }
}

person.toString();

The last arrow function in foreach is apply this of your object that why you didn't need to use clourse like this.cars.forEach(...)(this.name).


问:
django.db.utils.OperationalError: no such table: bookmarks_mytag
I am getting django.db.utils.OperationalError: no such table: bookmarks_mytag trying to install a django project.
The repo is at http://bitbucket.org/codyc54321/bookwormbud.git

We did

```<code>touch db.sqlite3
python manage.py migrate
</code>```

and it blows up:

```<code>(bookwormbuddy) john@john-Precision-3510:~/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca$ python manage.py runserver
Performing system checks...

Unhandled exception in thread started by <function wrapper at 0x7f7adbb5e140>
Traceback (most recent call last):
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    self.check(display_num_errors=True)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver
    return check_method()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookwormbud/urls.py", line 24, in <module>
    url(r'^',           include('bookmarks.urls',   namespace='bookmarks')),
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 50, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/urls.py", line 4, in <module>
    from bookmarks import views
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/views.py", line 24, in <module>
    from bookmarks.forms        import ArticleForm, TagForm, TagSelectForm, EditArticleForm, AddedDateCalendarForm, LastViewedDateCalendarForm
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 120, in <module>
    class TagSelectForm(forms.ModelForm):
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 127, in TagSelectForm
    choices=get_tag_choices()
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 112, in get_tag_choices
    if tags:
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 258, in __nonzero__
    return type(self).__bool__(self)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 254, in __bool__
    self._fetch_all()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 1118, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 886, in execute_sql
    raise original_exception
django.db.utils.OperationalError: no such table: bookmarks_mytag
^C(bookwormbuddy) john@john-Precision-3510:~/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca$ touch db.sqlite3
(bookwormbuddy) john@john-Precision-3510:~/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca$ python manage.py migrate
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 327, in execute
    self.check()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 62, in _run_checks
    issues.extend(super(Command, self)._run_checks(**kwargs))
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver
    return check_method()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookwormbud/urls.py", line 24, in <module>
    url(r'^',           include('bookmarks.urls',   namespace='bookmarks')),
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 50, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/urls.py", line 4, in <module>
    from bookmarks import views
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/views.py", line 24, in <module>
    from bookmarks.forms        import ArticleForm, TagForm, TagSelectForm, EditArticleForm, AddedDateCalendarForm, LastViewedDateCalendarForm
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 120, in <module>
    class TagSelectForm(forms.ModelForm):
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 127, in TagSelectForm
    choices=get_tag_choices()
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 112, in get_tag_choices
    if tags:
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 258, in __nonzero__
    return type(self).__bool__(self)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 254, in __bool__
    self._fetch_all()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 1118, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 886, in execute_sql
    raise original_exception
django.db.utils.OperationalError: no such table: bookmarks_mytag
</code>```

The project installs immediately on a different laptop, but I don't remember how it was set up. The sqlite db has been deleted and remade empty as it was said to do on SO. Any help appreciated, thank you

答: Did you try running python manage.py makemigrations before migrate?

Body:
I am getting django.db.utils.OperationalError: no such table: bookmarks_mytag trying to install a django project.
The repo is at http://bitbucket.org/codyc54321/bookwormbud.git

We did

touch db.sqlite3
python manage.py migrate

and it blows up:

(bookwormbuddy) john@john-Precision-3510:~/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca$ python manage.py runserver
Performing system checks...

Unhandled exception in thread started by <function wrapper at 0x7f7adbb5e140>
Traceback (most recent call last):
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper
    fn(*args, **kwargs)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    self.check(display_num_errors=True)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver
    return check_method()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookwormbud/urls.py", line 24, in <module>
    url(r'^',           include('bookmarks.urls',   namespace='bookmarks')),
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 50, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/urls.py", line 4, in <module>
    from bookmarks import views
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/views.py", line 24, in <module>
    from bookmarks.forms        import ArticleForm, TagForm, TagSelectForm, EditArticleForm, AddedDateCalendarForm, LastViewedDateCalendarForm
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 120, in <module>
    class TagSelectForm(forms.ModelForm):
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 127, in TagSelectForm
    choices=get_tag_choices()
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 112, in get_tag_choices
    if tags:
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 258, in __nonzero__
    return type(self).__bool__(self)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 254, in __bool__
    self._fetch_all()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 1118, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 886, in execute_sql
    raise original_exception
django.db.utils.OperationalError: no such table: bookmarks_mytag
^C(bookwormbuddy) john@john-Precision-3510:~/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca$ touch db.sqlite3
(bookwormbuddy) john@john-Precision-3510:~/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca$ python manage.py migrate
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 327, in execute
    self.check()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 62, in _run_checks
    issues.extend(super(Command, self)._run_checks(**kwargs))
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config
    return check_resolver(resolver)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver
    return check_method()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check
    for pattern in self.url_patterns:
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
    return import_module(self.urlconf_name)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookwormbud/urls.py", line 24, in <module>
    url(r'^',           include('bookmarks.urls',   namespace='bookmarks')),
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 50, in include
    urlconf_module = import_module(urlconf_module)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/urls.py", line 4, in <module>
    from bookmarks import views
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/views.py", line 24, in <module>
    from bookmarks.forms        import ArticleForm, TagForm, TagSelectForm, EditArticleForm, AddedDateCalendarForm, LastViewedDateCalendarForm
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 120, in <module>
    class TagSelectForm(forms.ModelForm):
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 127, in TagSelectForm
    choices=get_tag_choices()
  File "/home/john/Documents/cody_work/codyc54321-bookwormbud-f7f43c3908ca/bookmarks/forms.py", line 112, in get_tag_choices
    if tags:
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 258, in __nonzero__
    return type(self).__bool__(self)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 254, in __bool__
    self._fetch_all()
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 1118, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
  File "/home/john/anaconda3/envs/bookwormbuddy/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 886, in execute_sql
    raise original_exception
django.db.utils.OperationalError: no such table: bookmarks_mytag

The project installs immediately on a different laptop, but I don't remember how it was set up. The sqlite db has been deleted and remade empty as it was said to do on SO. Any help appreciated, thank you


问:
How to modify the reverse triangle properties in CSS
I m trying to modify a menu-bar template from http://cssmenumaker.com/menu/platinum-tabbed-dropdown-menu

the basic menu-bar structure as following `

```<code><ul>
   <li><a href='#'><span>Home</span></a></li>
   <li class='active has-sub'><a href='#'><span>Products</span></a>
      <ul>
         <li class='has-sub'><a href='#'><span>Product 1</span></a>
            <ul>
               <li><a href='#'><span>Sub Product</span></a></li>
               <li class='last'><a href='#'><span>Sub Product</span></a></li>
            </ul>
         </li>
         <li class='has-sub'><a href='#'><span>Product 2</span></a>
            <ul>
               <li><a href='#'><span>Sub Product</span></a></li>
               <li class='last'><a href='#'><span>Sub Product</span></a></li>
            </ul>
         </li>
      </ul>
   </li>
   <li><a href='#'><span>About</span></a></li>
   <li class='last'><a href='#'><span>Contact</span></a></li>
</ul>
</div>`
</code>```

For the tabs that include the second layer ,it consist of a reverse triangle ,like this ~~Food▼.

However , I want to make change of the triangle properties .What should I do ?

答:
If you look on developer console for the CSS code of one of the items with that triangle, you can see that it uses the :after CSS property and the triangle itself is an image:

So you can change it in your CSS adding another image or rotate with the CSS transform property as seen on the console.

Cheers!

Body:
I m trying to modify a menu-bar template from http://cssmenumaker.com/menu/platinum-tabbed-dropdown-menu

the basic menu-bar structure as following `

Home

Products

Product 1

Sub Product

Sub Product

Product 2

Sub Product

Sub Product

About

Contact

`

For the tabs that include the second layer ,it consist of a reverse triangle ,like this ~~Food▼.

However , I want to make change of the triangle properties .What should I do ?


问:
IIF statement in ms access query returns #error when testing for null
The IIF function in my query is returning #ERROR when I know the record i'm querying meets the criteria. My query is as follows:

```<code>SELECT tbl1.ItemCode, IIf(IsNull([tbl2].[True Available Quantity]) Or
[tbl2].[True Available Quantity]="",[tbl1].[EvalInstock],[tbl2].[True
Available Quantity]) AS InStock
FROM tbl1 LEFT JOIN tbl2 ON tbl1.ItemCode = tbl2.[Item No#]
WHERE (((tbl1.ItemCode)="3003"));
</code>```

The WHERE part is just to limit this query for testing on a record I know has data in the [tbl2].[True Available Quantity] field.

The ultimate goal is to return all items in tbl1 and use the [True Available Quantity] value from tbl2 if it is there and if not, use EvalInstock from tbl1. I appreciate any advice!

答:
Doesn't matter if [true available quantity] is number and EvalInstock is string because if EvalInstock is a string the return from either field will automatically cast as a string. I did a test to confirm. So something else is wrong.

If [true available quantity] is a number type field can't compare to empty string so remove that condition.

Is ItemCode a text type field? If not, remove the quote marks.

If you use IsNull() might as well use Nz(): Nz([True Available Quantity], [EvalInstock]) AS InStock
Review http://allenbrowne.com/QueryPerfIssue.html

Body:
The IIF function in my query is returning #ERROR when I know the record i'm querying meets the criteria. My query is as follows:

SELECT tbl1.ItemCode, IIf(IsNull([tbl2].[True Available Quantity]) Or
[tbl2].[True Available Quantity]="",[tbl1].[EvalInstock],[tbl2].[True
Available Quantity]) AS InStock
FROM tbl1 LEFT JOIN tbl2 ON tbl1.ItemCode = tbl2.[Item No#]
WHERE (((tbl1.ItemCode)="3003"));

The WHERE part is just to limit this query for testing on a record I know has data in the [tbl2].[True Available Quantity] field.

The ultimate goal is to return all items in tbl1 and use the [True Available Quantity] value from tbl2 if it is there and if not, use EvalInstock from tbl1. I appreciate any advice!


问:
How to show form when clicking buttons on nav
I'm trying to make one project based on my studies and I want to use AngularJS for this website but I have a problem with nav. The forms doesn't show when I click on nav.

This is the code of nav

```<code><nav>
<ul id="main_menu">
    <li><a class="active" ng-model="myVar"  value="Home" title="Home">Home</a></li>
    <li><a ng-model="myVar" value="Employees" title="New Employee">Register new Employee</a></li>
    <li><a ng-model="myVar" value="Customers" title="New Customer">Register new Customer</a></li>
    <li><a ng-model="myVar" value="Members" title="New Member">Register new Member</a></li>
</ul>
</nav>
</code>```

and this is this is the forms which I want to be shown when I click the buttons on nav

```<code><div ng-switch="myVar">

    <div ng-switch-when="Home">
                <h2>Welcome to Gate's Corporate Portal </h2>

                    <p class="pindex animated rotateIn">
                    With this online application:<br>
                    Your can add New Employees,
                    New Customers,
                    and New Members
                    </p>

        <div ng-switch-when="Employees">

        <div class="animated fadeInDown">
                    <form method="post" >
                    <legend>Register new Employee</legend>
                    <form method="post" action="employeesaction.php" >

                        <label for="name">Name:</label><input type="text" name="name"><br><br>
                        <label for="surname">Surname:</label><input type="text" name="surname"><br><br>
                        <label for="date_of_birth">Date of Birth:</label><input type="date" name="date_of_birth"><br><br>
                        <label for="telephone">Telephone:</label><input type="text" name="telephone"><br><br>
                        <label for="mobile">Mobile:</label><input type="text" name="mobile"><br><br>
                        <label for="email">Email:</label><input type="text" name="email"><br><br>
                        <label for="address">Address:</label><input type="text" name="address"><br><br>
                        <label for="tin">Tin:</label><input type="text" name="tin"><br><br>
                        <label for="employee_id">Employee id:</label><input type="text" name="employee_id"><br><br>

                        <p class="center">

                <button class="button1 animated flipInX" type="submit" value="Submit">Register</button>         <button class="button2 animated flipInY" type="reset" value="reset">Clear form</button>
                    </form>
                </div>
        </div>
            <div ng-switch-when="Customers">
            <legend>Register new Customer</legend>
                    <form method="post" action="customersaction.php">

                        <label for="name">Name:</label><input type="text" name="name"><br><br>
                        <label for="surname">Surname:</label><input type="text" name="surname"><br><br>
                        <label for="telephone">Telephone:</label><input type="text" name="telephone"><br><br>
                        <label for="mobile">Mobile:</label><input type="text" name="mobile"><br><br>
                        <label for="customers_company">Customers company:</label><input type="text" name="customers_company"><br><br>
                        <label for="email">Email:</label><input type="text" name="email"><br><br>
                        <label for="address">Address:</label><input type="text" name="address"><br><br>
                        <label for="tin">Tin:</label><input type="text" name="tin"><br><br>
                        <p class="center">

                <button class="button1 animated flipInX" type="submit" value="Submit">Register</button>         <button class="button2 animated flipInY" type="reset" value="reset">Clear form</button></p>
            </div>
        <div ng-switch-when="Members">
            <div class="animated fadeInDown">
                    <legend >Register new Member</legend>
                    <form  method="post" action="membersaction.php">

                        <label for="name">Name:</label><input type="text" name="name"><br><br>
                        <label for="surname">Surname:</label><input type="text" name="surname"><br><br>
                        <label for="telephone">Telephone:</label><input type="text" name="telephone"><br><br>
                        <label for="mobile">Mobile:</label><input type="text" name="mobile"><br><br>
                        <label for="email">Email:</label><input type="text" name="email"><br><br>

                    <p class="center">

                <button class="button1 animated flipInX" type="submit" value="Submit">Register</button>         <button class="button2 animated flipInY" type="reset" value="reset">Clear form</button></p>
                    </form>
                    <br><br><br><br><br><br><br><br><br><br>
                </div>
        </div>
    </div>
</code>```

答:
In your , it looks like you are trying to use a method that would work with radio buttons, but that will not work with  elements. A method for using  to accomplish this would look like the following code:

```<code><nav>
<ul id="main_menu">
    <li><a ng-click="updateMyVar('Home')" class="active" title="Home">Home</a></li>
    <li><a ng-click="updateMyVar('Employees')" title="New Employee">Register new Employee</a></li>
    <li><a ng-click="updateMyVar('Customers')" title="New Customer">Register new Customer</a></li>
    <li><a ng-click="updateMyVar('Members')" title="New Member">Register new Member</a></li>
</ul>
</nav>
</code>```

And then in your controller, you could assign a starting value to myVar like this: $scope.myVar = 'Home'; Then you would need to create a simple function:

```<code>$scope.updateMyVar = function(value) {
    $scope.myVar = value;
};
</code>```

Body:
I'm trying to make one project based on my studies and I want to use AngularJS for this website but I have a problem with nav. The forms doesn't show when I click on nav.

This is the code of nav

Home

Register new Employee

Register new Customer

Register new Member

and this is this is the forms which I want to be shown when I click the buttons on nav

Welcome to Gate's Corporate Portal

                    With this online application:

                    Your can add New Employees,
                    New Customers,
                    and New Members

                    <form method="post" >
                    <legend>Register new Employee</legend>
                    <form method="post" action="employeesaction.php" >

                        Name:<input type="text" name="name">

                        Surname:<input type="text" name="surname">

                        Date of Birth:<input type="date" name="date_of_birth">

                        Telephone:<input type="text" name="telephone">

                        Mobile:<input type="text" name="mobile">

                        Email:<input type="text" name="email">

                        Address:<input type="text" name="address">

                        Tin:<input type="text" name="tin">

                        Employee id:<input type="text" name="employee_id">

                <button class="button1 animated flipInX" type="submit" value="Submit">Register</button>         <button class="button2 animated flipInY" type="reset" value="reset">Clear form</button>
                    </form>

            <legend>Register new Customer</legend>
                    <form method="post" action="customersaction.php">

                        Name:<input type="text" name="name">

                        Surname:<input type="text" name="surname">

                        Telephone:<input type="text" name="telephone">

                        Mobile:<input type="text" name="mobile">

                        Customers company:<input type="text" name="customers_company">

                        Email:<input type="text" name="email">

                        Address:<input type="text" name="address">

                        Tin:<input type="text" name="tin">

                <button class="button1 animated flipInX" type="submit" value="Submit">Register</button>         <button class="button2 animated flipInY" type="reset" value="reset">Clear form</button>

                    <legend >Register new Member</legend>
                    <form  method="post" action="membersaction.php">

                        Name:<input type="text" name="name">

                        Surname:<input type="text" name="surname">

                        Telephone:<input type="text" name="telephone">

                        Mobile:<input type="text" name="mobile">

                        Email:<input type="text" name="email">

                <button class="button1 animated flipInX" type="submit" value="Submit">Register</button>         <button class="button2 animated flipInY" type="reset" value="reset">Clear form</button>

                    </form>

Body:
In your <nav>, it looks like you are trying to use a method that would work with radio buttons, but that will not work with <a> elements. A method for using <a> to accomplish this would look like the following code:

<nav>
<ul id="main_menu">
    <li><a ng-click="updateMyVar('Home')" class="active" title="Home">Home</a></li>
    <li><a ng-click="updateMyVar('Employees')" title="New Employee">Register new Employee</a></li>
    <li><a ng-click="updateMyVar('Customers')" title="New Customer">Register new Customer</a></li>
    <li><a ng-click="updateMyVar('Members')" title="New Member">Register new Member</a></li>
</ul>
</nav>

And then in your controller, you could assign a starting value to myVar like this: $scope.myVar = 'Home'; Then you would need to create a simple function:

$scope.updateMyVar = function(value) {
    $scope.myVar = value;
};


问:
pg-promise in AWS lambda
I am having quite a number of issues using pg-promise with AWS lambda. I wanted to understand how do I solve these issues.

The library advises you to create one instance of the Database object and then export it from a module. There should only one instance of the object created.
Something like:

```<code>const db = pgp({
  host: process.env.DATABASE_HOST,
  port: process.env.DATABASE_PORT,
  database: process.env.DATABASE_NAME,
  user: process.env.DATABASE_USERNAME,
  password: process.env.DATABASE_PASSWORD,
  poolSize: 0,
  poolIdleTimeout: 10,
});
module.exports = db;
</code>```

I understand that this just an object and no connection is created here. A connection will be created lazily when you run anything on this db object such as a db.query().

Since we have put in the pool size as 0, there would only ever be one connection created. Which is what we need as at the start of every lambda function we need to create a connection and then close the connection when the lambda finishes.

The issues we are facing are:

How do we release a connection?
AWS lambdas re-use containers. Meaning it will call on the same node code that is already initialised and re-run the same function if a call to the lambda happens soon after a prior run.
This means that the db object will be the same for the next call of the lambda. After our first lambda completes, if we call pgp.end() the documentation says the connection pool closes. It also says we cant use the pgp library in the same process after that. But the library will be used as the db object is still alive and will be used in a subsequent run.

How do we retry getting a new connection?

The other issue that AWS lambda poses, is that when you run a lambda within a VPC and your Postgres instance is also running inside a VPC, it takes time for the postgres database's DNS to resolve. So if you try to connect you might get an ENOTFOUND error. The advice from AWS is to retry acquiring the connection. Using the pg-promise how do we retry acquiring a connection?

The way I would like to implement it is:

```<code>module.exports.handler = (event, context, callback) => {
 let connection;
 try {
  connection = /*gets connection and retries if it failed the first time*/
  // run db queries and transactions.. etc.
  callback(null, result);
 } finally {
  connection.close();
 }

}
</code>```

答:
How do we release a connection?

You don't. Connections are communicated with the connection pool automatically. Once a query ends executing, the connection goes back into the pool, to be available for the next query that requests it.

When executing more than one query at a time you should use tasks. See Chaining Queries.

How do we retry getting a new connection?

Connection pool creates a new physical connection automatically, when it is necessary, according to the connection demand and the maximum pool size. When a connection goes down, it is automatically re-created.

If a single connection is all you've got within AWS lambda, then maybe the best pattern for you is to create and maintain a single global connection?

If that's the case, the Robust Listeners example might be of use to you. It shows how to maintain a single global connection outside of the connection pool, and how to keep it alive at all times.

But that's more like the last resort. I believe simply by using the automatic connection pool should be sufficient.

Title: pg-promise in AWS lambda

Body:
I am having quite a number of issues using pg-promise with AWS lambda. I wanted to understand how do I solve these issues.

The library advises you to create one instance of the Database object and then export it from a module. There should only one instance of the object created.
Something like:

const db = pgp({
  host: process.env.DATABASE_HOST,
  port: process.env.DATABASE_PORT,
  database: process.env.DATABASE_NAME,
  user: process.env.DATABASE_USERNAME,
  password: process.env.DATABASE_PASSWORD,
  poolSize: 0,
  poolIdleTimeout: 10,
});
module.exports = db;

I understand that this just an object and no connection is created here. A connection will be created lazily when you run anything on this db object such as a db.query().

Since we have put in the pool size as 0, there would only ever be one connection created. Which is what we need as at the start of every lambda function we need to create a connection and then close the connection when the lambda finishes.

The issues we are facing are:

How do we release a connection?
AWS lambdas re-use containers. Meaning it will call on the same node code that is already initialised and re-run the same function if a call to the lambda happens soon after a prior run.
This means that the db object will be the same for the next call of the lambda. After our first lambda completes, if we call pgp.end() the documentation says the connection pool closes. It also says we cant use the pgp library in the same process after that. But the library will be used as the db object is still alive and will be used in a subsequent run.

How do we retry getting a new connection?

The other issue that AWS lambda poses, is that when you run a lambda within a VPC and your Postgres instance is also running inside a VPC, it takes time for the postgres database's DNS to resolve. So if you try to connect you might get an ENOTFOUND error. The advice from AWS is to retry acquiring the connection. Using the pg-promise how do we retry acquiring a connection?

The way I would like to implement it is:

module.exports.handler = (event, context, callback) => {
 let connection;
 try {
  connection = /*gets connection and retries if it failed the first time*/
  // run db queries and transactions.. etc.
  callback(null, result);
 } finally {
  connection.close();
 }

}


问:
Time in milliseconds in C
Using the following code:

```<code>#include<stdio.h>
#include<time.h>
int main()
{
    clock_t start, stop;
    int i;
    start = clock();
    for(i=0; i<2000;i++)
    {
        printf("%d", (i*1)+(1^4));
    }
    printf("\n\n");
    stop = clock();

    //(double)(stop - start) / CLOCKS_PER_SEC

    printf("%6.3f", start);
    printf("\n\n%6.3f", stop);
    return 0;
}
</code>```

I get the following output:

```
[encoded data, 6905 characters]

  2.169

  2.169
```

Start and stop times are the same. Does it mean that the program hardly takes time to complete execution?

If 1. is false, then atleast the no.of digits beyond the (.) should differ, which does not happen here. Is my logic correct?

Note: I need to calculate the time taken for execution, and hence the above code.

答:
Here is what I write to get the timestamp in millionseconds.</p>

```<code>#include<sys/time.h>

long long timeInMilliseconds(void) {
    struct timeval tv;

    gettimeofday(&tv,NULL);
    return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Time in milliseconds in C

Body:
Using the following code:

#include<stdio.h>
#include<time.h>
int main()
{
    clock_t start, stop;
    int i;
    start = clock();
    for(i=0; i<2000;i++)
    {
        printf("%d", (i*1)+(1^4));
    }
    printf("\n\n");
    stop = clock();

    //(double)(stop - start) / CLOCKS_PER_SEC

    printf("%6.3f", start);
    printf("\n\n%6.3f", stop);
    return 0;
}

I get the following output:

[encoded data, 6905 characters]

  2.169

  2.169

Start and stop times are the same. Does it mean that the program hardly takes time to complete execution?

If 1. is false, then atleast the no.of digits beyond the (.) should differ, which does not happen here. Is my logic correct?

Note: I need to calculate the time taken for execution, and hence the above code.

Body:
Here is what I write to get the timestamp in millionseconds.

#include<sys/time.h>

long long timeInMilliseconds(void) {
    struct timeval tv;

    gettimeofday(&tv,NULL);
    return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}


问:
Kafka Zookeeper installation issue
Following the instructions from https://kafka.apache.org/quickstart.

On MingW32 console on Windows 8 64 bit, it produces this error.

```<code>$ bin/windows/zookeeper-server-start.bat config/zookeeper.properties
./zookeeper-server-start.bat: line 1: @echo: command not found
./zookeeper-server-start.bat: line 2: syntax error near unexpected token `('
./zookeeper-server-start.bat: line 2: `rem Licensed to the Apache Software Foundation (ASF) under one or more'
</code>```

How to correctly install Kafka? Looked at some other SO posts about similar issues. Could not find solution for this particular error.

答:
I think the issue is you are running the Windows scripts. In a MinGW environment you need to run the Linux commands. E.g.,

bin/zookeeper-server-start.sh config/zookeeper.properties

Windows scripts are for when you run Kafka using a Windows Command Prompt.

Title: Kafka Zookeeper installation issue

Body:
Following the instructions from https://kafka.apache.org/quickstart.

On MingW32 console on Windows 8 64 bit, it produces this error.

$ bin/windows/zookeeper-server-start.bat config/zookeeper.properties
./zookeeper-server-start.bat: line 1: @echo: command not found
./zookeeper-server-start.bat: line 2: syntax error near unexpected token `('
./zookeeper-server-start.bat: line 2: `rem Licensed to the Apache Software Foundation (ASF) under one or more'

How to correctly install Kafka? Looked at some other SO posts about similar issues. Could not find solution for this particular error.


答: This is called the ::after selector in CSS. The ::after selector inserts something after the content of each selected element(s). Use the content property to add the content what you need. S<img src="https://i.stack.imgur.com/b8OzT.jpg" alt="enter image description here">ee the image below, that you are trying to follow below from chrome developer tools. </p>

Title: How to modify the reverse triangle properties in CSS

Body: This is called the ::after selector in CSS. The ::after selector inserts something after the content of each selected element(s). Use the content property to add the content what you need. See the image below, that you are trying to follow below from chrome developer tools.


问:
Error in function frees from a linked list
I'm having trouble finding the error of my code ...

I get a memory address as a parameter and need to release from my list (HEAP)

List structure:

```<code>typedef struct free_node {
    size_t free;
    size_t size;
    struct free_node *next;
} free_node_t;

typedef struct {
  free_node_t *head;
  free_node_t *lastAlloca; // Usado para next fit
} free_list_t;
</code>```

I need to do a function that releases the ptr memory address

```<code>void libera(void *ptr) {

    free_node_t *metaData = (void*)ptr - sizeof(free_node_t);
    assert(HEAP->lastAlloca != NULL);
    free_node_t *listNavigator = HEAP->head;

    while(listNavigator != NULL) {
        if(listNavigator->next == metaData) {
            listNavigator->next = metaData->next;
            listNavigator->free += metaData->size + metaData->free + sizeof(free_node_t);
            break;
        }
        listNavigator = listNavigator->next;
    }
}
</code>```

But, it is not working. When I compile for some cases of segmentation fault.

Please, help me :)

答:
It looks like you're trying to implement a tracking memory allocator. To get at the offset of your metadata, you have to use a temporary pointer, like so:

```<code>void libera(void *ptr) {

    free_node_t *temp = (free_node_t*)ptr;
    free_node_t *metaData = temp - sizeof(free_node_t);
    assert(HEAP->lastAlloca != NULL);
    free_node_t *listNavigator = HEAP->head;

    while(listNavigator != NULL) {
        if(listNavigator->next == metaData) {
            listNavigator->next = metaData->next;
            listNavigator->free += metaData->size + metaData->free + sizeof(free_node_t);
            break;
        }
        listNavigator = listNavigator->next;
    }
}
</code>```

Your cast free_node_t *metaData = (void*)ptr - sizeof(free_node_t); doesn't do anything since ptr is passed as a void pointer, and you can't decrement a void pointer.

Body:
I'm having trouble finding the error of my code ...

I get a memory address as a parameter and need to release from my list (HEAP)

List structure:

typedef struct free_node {
    size_t free;
    size_t size;
    struct free_node *next;
} free_node_t;

typedef struct {
  free_node_t *head;
  free_node_t *lastAlloca; // Usado para next fit
} free_list_t;

I need to do a function that releases the ptr memory address

void libera(void *ptr) {

    free_node_t *metaData = (void*)ptr - sizeof(free_node_t);
    assert(HEAP->lastAlloca != NULL);
    free_node_t *listNavigator = HEAP->head;

    while(listNavigator != NULL) {
        if(listNavigator->next == metaData) {
            listNavigator->next = metaData->next;
            listNavigator->free += metaData->size + metaData->free + sizeof(free_node_t);
            break;
        }
        listNavigator = listNavigator->next;
    }
}

But, it is not working. When I compile for some cases of segmentation fault.

Please, help me :)

Body:
It looks like you're trying to implement a tracking memory allocator. To get at the offset of your metadata, you have to use a temporary pointer, like so:

void libera(void *ptr) {

    free_node_t *temp = (free_node_t*)ptr;
    free_node_t *metaData = temp - sizeof(free_node_t);
    assert(HEAP->lastAlloca != NULL);
    free_node_t *listNavigator = HEAP->head;

    while(listNavigator != NULL) {
        if(listNavigator->next == metaData) {
            listNavigator->next = metaData->next;
            listNavigator->free += metaData->size + metaData->free + sizeof(free_node_t);
            break;
        }
        listNavigator = listNavigator->next;
    }
}

Your cast free_node_t *metaData = (void*)ptr - sizeof(free_node_t); doesn't do anything since ptr is passed as a void pointer, and you can't decrement a void pointer.


问:
Allow multiple CORS domain in express js
How do I allow multiple domains for CORS in express in a simplified way.

I have

```<code> cors: {
        origin: "www.one.com";
    }

    app.all('*', function(req, res, next) {
            res.header("Access-Control-Allow-Origin", cors.origin);
            res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            next();
        });
</code>```

This works when there is only one domain mentioned in origin

But if I want to have origin as an array of domains and I want to allow CORS for all the domains in the origin array, I would have something like this -

```<code>cors: {
            origin: ["www.one.com","www.two.com","www.three.com"];
        }
</code>```

But then the problem is this below code would not work -

```<code>app.all('*', function(req, res, next) {
                res.header("Access-Control-Allow-Origin", cors.origin);
                res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                next();
            });
</code>```

How do I make res.header take an array of domains via cors.origin ?

答:
In fact, Access-Control-Allow-Origin header should be the same value as the Origin header as long as you want to allow it.

So base on your code just

```<code>cors: {
    origin: ["www.one.com","www.two.com","www.three.com"]
}

app.all('*', function(req, res, next) {
            let origin = req.headers.origin;
            if(cors.origin.indexOf(origin) >= 0){
                res.header("Access-Control-Allow-Origin", origin);
            }
            res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            next();
        });
</code>```

Body:
How do I allow multiple domains for CORS in express in a simplified way.

I have

 cors: {
        origin: "www.one.com";
    }

    app.all('*', function(req, res, next) {
            res.header("Access-Control-Allow-Origin", cors.origin);
            res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            next();
        });

This works when there is only one domain mentioned in origin

But if I want to have origin as an array of domains and I want to allow CORS for all the domains in the origin array, I would have something like this -

cors: {
            origin: ["www.one.com","www.two.com","www.three.com"];
        }

But then the problem is this below code would not work -

app.all('*', function(req, res, next) {
                res.header("Access-Control-Allow-Origin", cors.origin);
                res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                next();
            });

How do I make res.header take an array of domains via cors.origin ?

Body:
In fact, Access-Control-Allow-Origin header should be the same value as the Origin header as long as you want to allow it.

So base on your code just

cors: {
    origin: ["www.one.com","www.two.com","www.three.com"]
}

app.all('*', function(req, res, next) {
            let origin = req.headers.origin;
            if(cors.origin.indexOf(origin) >= 0){
                res.header("Access-Control-Allow-Origin", origin);
            }
            res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            next();
        });


问:
JQuery - Select input field by type and not readonly
OK, so I have a form and I would like to select a field that is of type "Date" but that does not have a read only attribute. Im sure this is super easy but Im new to js/jq. I would like to do something like this:

```<code>$('[type="Date"] && [not:readonly]').datepicker();
</code>```

Thank you very much for any help.

答:
There's no && operator, but the selectors are additive by default, similar to CSS:

```<code>$('[type="date"]:not([readonly])').datepicker();
</code>```

Body:
OK, so I have a form and I would like to select a field that is of type "Date" but that does not have a read only attribute. Im sure this is super easy but Im new to js/jq. I would like to do something like this:

$('[type="Date"] && [not:readonly]').datepicker();

Thank you very much for any help.

Body:
There's no && operator, but the selectors are additive by default, similar to CSS:

$('[type="date"]:not([readonly])').datepicker();


问:
UIButton inside of multiple UICollectionViewCells not working
I have created a UICollectionView with cells called baseCell. Inside of those cells is another UICollectionView with cells called subCell. Inside of each subCell is a UIButton. The button has

Here is the code that sets up the button and its action:

```<code>let openOptionsButton: UIButton = {
    let button = UIButton()
    button.setImage(#imageLiteral(resourceName: "CircleAdd"), for: .normal)
    button.addTarget(self, action: #selector(slideOverToOptions), for: .touchUpInside)
    button.contentMode = .scaleAspectFit
    return button
}()

func slideOverToOptions() {
    print("This is working")
}

func setupViews(){
    addSubview(openOptionsButton)

            _ = openOptionsButton.anchor(topAnchor, left: nil, bottom: nil, right: rightAnchor, topConstant: 8, leftConstant: 0, bottomConstant: 0, rightConstant: 12, widthConstant: 48, heightConstant: 48)
}
</code>```

When I press the button, it does not print. How can I fix this issue?

答: You haven't set the frame of your button or add it to a super view</p>

Body:
I have created a UICollectionView with cells called baseCell. Inside of those cells is another UICollectionView with cells called subCell. Inside of each subCell is a UIButton. The button has

Here is the code that sets up the button and its action:

let openOptionsButton: UIButton = {
    let button = UIButton()
    button.setImage(#imageLiteral(resourceName: "CircleAdd"), for: .normal)
    button.addTarget(self, action: #selector(slideOverToOptions), for: .touchUpInside)
    button.contentMode = .scaleAspectFit
    return button
}()

func slideOverToOptions() {
    print("This is working")
}

func setupViews(){
    addSubview(openOptionsButton)

            _ = openOptionsButton.anchor(topAnchor, left: nil, bottom: nil, right: rightAnchor, topConstant: 8, leftConstant: 0, bottomConstant: 0, rightConstant: 12, widthConstant: 48, heightConstant: 48)
}

When I press the button, it does not print. How can I fix this issue?


问:
java regular expression to match file path
I was trying out to create a regular expression to match file path in java like

C:\abc\def\ghi\abc.txt

I tried this ([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\? , like following code

```<code>import java.util.regex.Pattern;

  public class RETester {

public static void main(String arhs[]){

    String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";

    String path = "D:\\directoryname\\testing\\abc.txt";

    Pattern pattern = Pattern.compile(regularExpression);

    boolean isMatched = Pattern.matches(regularExpression,path);
    System.out.println(path);
    System.out.println(pattern.pattern());
    System.out.println(isMatched);

}

}
</code>```

However it's always giving me , false as result .

答: There are two reasons why it is giving you false. First one is that you need \\\\ instead of \\ because you need to escape these characters. And the second one is that you're missing a dot character, you can insert it before a-z as ([a-zA-Z]:)?(\\\\[.a-zA-Z0-9_-]+)+\\\\?

Body:
I was trying out to create a regular expression to match file path in java like

C:\abc\def\ghi\abc.txt

I tried this ([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\? , like following code

import java.util.regex.Pattern;

  public class RETester {

public static void main(String arhs[]){

    String regularExpression = "([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?";

    String path = "D:\\directoryname\\testing\\abc.txt";

    Pattern pattern = Pattern.compile(regularExpression);

    boolean isMatched = Pattern.matches(regularExpression,path);
    System.out.println(path);
    System.out.println(pattern.pattern());
    System.out.println(isMatched);

}

}

However it's always giving me , false as result .

ContentLicense: CC BY-SA 2.5


问:
Webpack built package runs fine on localhost, broken on server
So I have a react app that I am bundling using webpack, which is complete black magic for me. However, I can get it to build the site and if I use simple http server through python I can see the website and everything runs fine. So the build works! However, when I transfer all the contents of the dist folder over to my FTP server by putting it in the public_html folder on my server side there's something broken. When I navigate to my website I get this:

```<code>vendor.1ef2345b1b27ea00e944.js Failed to load resource: the server responded with a status of 404 (Not Found)
app.00a6dbb5503f500f33b7.js Failed to load resource: the server responded with a status of 404 (Not Found)
</code>```

Well....neither of those two files are anywhere in my dist folder. My only guess is that webpack is referencing those files somehow and I don't have any idea how to debug this. I've used this process to get my site up (once) before, so I thought it should work fine, but evidently not. Completely flumoxed, any help/suggestions would be appreciated.

EDIT: Ok, so now only the app file is missing, but I don't know what changed. So good, I guess?

答: So, apparently sometimes webpack will include the wrong path to the minimized js file. I had no idea that it would do this. Dang it webpack.</p>

Body:
So I have a react app that I am bundling using webpack, which is complete black magic for me. However, I can get it to build the site and if I use simple http server through python I can see the website and everything runs fine. So the build works! However, when I transfer all the contents of the dist folder over to my FTP server by putting it in the public_html folder on my server side there's something broken. When I navigate to my website I get this:

vendor.1ef2345b1b27ea00e944.js Failed to load resource: the server responded with a status of 404 (Not Found)
app.00a6dbb5503f500f33b7.js Failed to load resource: the server responded with a status of 404 (Not Found)

Well....neither of those two files are anywhere in my dist folder. My only guess is that webpack is referencing those files somehow and I don't have any idea how to debug this. I've used this process to get my site up (once) before, so I thought it should work fine, but evidently not. Completely flumoxed, any help/suggestions would be appreciated.

EDIT: Ok, so now only the app file is missing, but I don't know what changed. So good, I guess?


问:
Swift 3 - Making class iterable
Consider my two classes:

```<code>// Person.swift
class Person {
    var parents: Parents?
    // ...
}

// Parents.swift. Only a collection of parents with some helper methods.
class Parents {
    var parents = [Person]()
    // ...
}
</code>```

How could I make Parents iterate in a for loop using the iterators of parents. This is not a real world app. I'm just curious. Just would like to use for parent in myParents instead of for parent in myParents.parents.

答:
The way to do this is to have your Parents class conform to the Sequence Protocol, implement a makeIterator method, and then pass the result through from calling makeIterator on the contained Array<Person>

```<code>  // Person.swift
  class Person {
    var parents: Parents?
    // ...
  }

  // Parents.swift. Only a collection of parents with some helper methods.
  class Parents{
    var parents = [Person]()
    // ...
  }

  // conform to Sequence Protocol
  extension Parents: Sequence {
    func makeIterator() -> Array<Person>.Iterator {
      return parents.makeIterator()
    }
  }

  let myself = Person()
  if let myParents = myself.parents {
    for person in myParents {

    }
  }
</code>```

Title: Swift 3 - Making class iterable

Body:
Consider my two classes:

// Person.swift
class Person {
    var parents: Parents?
    // ...
}

// Parents.swift. Only a collection of parents with some helper methods.
class Parents {
    var parents = [Person]()
    // ...
}

How could I make Parents iterate in a for loop using the iterators of parents. This is not a real world app. I'm just curious. Just would like to use for parent in myParents instead of for parent in myParents.parents.

Body:
The way to do this is to have your Parents class conform to the Sequence Protocol, implement a makeIterator method, and then pass the result through from calling makeIterator on the contained Array<Person>

  // Person.swift
  class Person {
    var parents: Parents?
    // ...
  }

  // Parents.swift. Only a collection of parents with some helper methods.
  class Parents{
    var parents = [Person]()
    // ...
  }

  // conform to Sequence Protocol
  extension Parents: Sequence {
    func makeIterator() -> Array<Person>.Iterator {
      return parents.makeIterator()
    }
  }

  let myself = Person()
  if let myParents = myself.parents {
    for person in myParents {

    }
  }


问:
Trying to hide all bbcode-generated divs within a span, but it isn't working
Here's an example of the html:

```<code><!-- Working Example-->
<span class='prv' style='cursor: pointer; cursor: hand';>
    This text is shown...
</span>
<span class='cnt' style='cursor: pointer; cursor: hand';>
    This text will be hidden on load and shown when the 'prv' class is clicked.
</span>
<!-- Broken Example-->
<span class='prv' style='cursor: pointer; cursor: hand';>
    This text is shown...</span>
<span class='cnt' style='cursor: pointer; cursor: hand';>
    <div class="bbcode_center" style="text-align:center">
        This text isn't hidden even though I want it to be.
    </div>
</span>
</code>```

In the working example, there aren't any bbcode tags, so no bbcode class divs are generated - but I can't just get rid of the bbcode tags because I need them displayed.

Here the jquery code:

```<code>function run_on_load() {
    $('.cnt').hide();
    //$('.cnt').children().hide(); <- Tried this too
}
$('.prv').click(function() {
    $('.prv').hide();
    $('.cnt').show();
});
$('.cnt').click(function() {
    $('.cnt').hide();
    $('.prv').show();
});
</code>```

This all works for the first example, but hides nothing in the second example. How do I make it so that the jquery code hides everything within the 'cnt' class span indiscriminately?

Also, the span in the broken example isn't clickable, apparently for the same reason. Is there a way to make all divs within the span clickable, like having a jquery findall type function add the clickable style to each individual bbcode class div?

Edit: To be clear, what happens in the working example is exactly what I want: 'prv' (the preview text) is shown, and when it is clicked it hides itself and instead shows 'cnt' (the full content/text). The only issue with the broken example is that nothing within bbcode divs in 'cnt' is ever hidden when I want it all hidden indiscriminately.

答: Reddit helped me solve it. Turns out I just needed to change the spans to divs -- the html wasn't validating properly because you can't put divs inside spans, apparently.</p>

Body:
Here's an example of the html:

    This text is shown...

    This text will be hidden on load and shown when the 'prv' class is clicked.

    This text is shown...

        This text isn't hidden even though I want it to be.

In the working example, there aren't any bbcode tags, so no bbcode class divs are generated - but I can't just get rid of the bbcode tags because I need them displayed.

Here the jquery code:

function run_on_load() {
    $('.cnt').hide();
    //$('.cnt').children().hide(); <- Tried this too
}
$('.prv').click(function() {
    $('.prv').hide();
    $('.cnt').show();
});
$('.cnt').click(function() {
    $('.cnt').hide();
    $('.prv').show();
});

This all works for the first example, but hides nothing in the second example. How do I make it so that the jquery code hides everything within the 'cnt' class span indiscriminately?

Also, the span in the broken example isn't clickable, apparently for the same reason. Is there a way to make all divs within the span clickable, like having a jquery findall type function add the clickable style to each individual bbcode class div?

Edit: To be clear, what happens in the working example is exactly what I want: 'prv' (the preview text) is shown, and when it is clicked it hides itself and instead shows 'cnt' (the full content/text). The only issue with the broken example is that nothing within bbcode divs in 'cnt' is ever hidden when I want it all hidden indiscriminately.


问:
Java 7 error on multi-catch exception
I run my java application on a MacOS 10.9.5 (Mavericks) with JavaSE 1.7.0_60 installed.

I want to use the multi-catch statement for catch some exceptions...

But When I try to run my app I got an error like this:

```<code>Internal Server Error (500) for request GET /tresTest/authenticate
Compilation error (In /app/controllers/TestBoxController.java around line 57)
The file /app/controllers/TestBoxController.java could not be compiled. Error raised is : Syntax error on tokens, delete these tokens
</code>```

The reason of this error is this line of code:

```<code>try {
  class.someMethodTrowingException();
} catch (MyExceptionNo1 | MyExceptionNo2 | MyExceptionNo3 e) {
  doSomethigUseful();
}
</code>```

If type java -version on my console, i got this result:

```<code>java version "1.7.0_60"
Java(TM) SE Runtime Environment (build 1.7.0_60-b19)
Java HotSpot(TM) 64-Bit Server VM (build 24.60-b09, mixed mode)
</code>```

I can't understand why I got this behavior. Multi-catch statement is allow in Java7, right?

UPDATE 10.15.2014

I know that if I use catch in this way everything go right

```<code>try {
  class.someMethodTrowingException();
} catch (MyExceptionNo1 e1) {
  doSomethigUseful();
} catch (MyExceptionNo2 e2) {
  doSomethigUseful();
} catch (MyExceptionNo3 e3) {
  doSomethigUseful();
}
</code>```

But my goal it to use the multi-catch statement like catch (MyExceptionNo1 | MyExceptionNo2 | MyExceptionNo3 e) {...}

Check this out: http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html

UPDATE 11.20.2014

Found out the problem. It's Play that use 1.6 Java compatibility even if I told to its to not use it. Don't understand yet why, and don't understand yet how to sole, but at least I understand where problem is... :)

答:
Add the below plugin in maven to compile it using Java version 1.7</p>

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
          <source>1.7</source>
          <target>1.7</target>
    </configuration>
</plugin>
</code>```

Title: Java 7 error on multi-catch exception

Body:
I run my java application on a MacOS 10.9.5 (Mavericks) with JavaSE 1.7.0_60 installed.

I want to use the multi-catch statement for catch some exceptions...

But When I try to run my app I got an error like this:

Internal Server Error (500) for request GET /tresTest/authenticate
Compilation error (In /app/controllers/TestBoxController.java around line 57)
The file /app/controllers/TestBoxController.java could not be compiled. Error raised is : Syntax error on tokens, delete these tokens

The reason of this error is this line of code:

try {
  class.someMethodTrowingException();
} catch (MyExceptionNo1 | MyExceptionNo2 | MyExceptionNo3 e) {
  doSomethigUseful();
}

If type java -version on my console, i got this result:

java version "1.7.0_60"
Java(TM) SE Runtime Environment (build 1.7.0_60-b19)
Java HotSpot(TM) 64-Bit Server VM (build 24.60-b09, mixed mode)

I can't understand why I got this behavior. Multi-catch statement is allow in Java7, right?

UPDATE 10.15.2014

I know that if I use catch in this way everything go right

try {
  class.someMethodTrowingException();
} catch (MyExceptionNo1 e1) {
  doSomethigUseful();
} catch (MyExceptionNo2 e2) {
  doSomethigUseful();
} catch (MyExceptionNo3 e3) {
  doSomethigUseful();
}

But my goal it to use the multi-catch statement like catch (MyExceptionNo1 | MyExceptionNo2 | MyExceptionNo3 e) {...}

Check this out: http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html

UPDATE 11.20.2014

Found out the problem. It's Play that use 1.6 Java compatibility even if I told to its to not use it. Don't understand yet why, and don't understand yet how to sole, but at least I understand where problem is... :)

Body:
Add the below plugin in maven to compile it using Java version 1.7

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
          <source>1.7</source>
          <target>1.7</target>
    </configuration>
</plugin>


问:
How to insert multiple numbers from one row split into different options in a select stmt
I was wondering if there was a way to make a select box with multiple options based on one row from my MySQL table.

For instance,

```<code><?php

            if(!empty($row['size']))
            { ?>
                <label>Size</label>
                <select name="size">
                <option value=""><?php echo $row['size'];?></option>
                </select>

            <?php

            }

        ?>
</code>```

in my database I have one row labeled "size". In that row, I have multiple sizes separated by a coma. Is it possible to break those comas into separate options once I retrieve the data from my table? Or will I have to make multiple rows in my DB labeled "size_1, size_2".... and so on.

答:
I want to link to this question right here

The coding-stuff for your question:

```<code>foreach ($_GET['size'] as $selectedOption)
echo $selectedOption."\n";
</code>```

Body:
I was wondering if there was a way to make a select box with multiple options based on one row from my MySQL table.

For instance,

<?php

            if(!empty($row['size']))
            { ?>
                Size
                <select name="size">
                <option value=""><?php echo $row['size'];?></option>
                </select>

            <?php

            }

        ?>

in my database I have one row labeled "size". In that row, I have multiple sizes separated by a coma. Is it possible to break those comas into separate options once I retrieve the data from my table? Or will I have to make multiple rows in my DB labeled "size_1, size_2".... and so on.

Body:
I want to link to this question right here

The coding-stuff for your question:

foreach ($_GET['size'] as $selectedOption)
echo $selectedOption."\n";


问:
php random generate id like a32-jn3-sdf3
with the current code i'm getting are in5v6wyio0er5isu9rv4, so how do i get more number and less alphabets in the id?

below is the code which i have done

```<code>    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';

    for ($i = 0; $i < 20; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    echo $randomString;
</code>```

i would like to get the id in this format 6437270e-c2d4-4524-8a26-ad311c4ca55e.

答:
Do some edit base on your code,and that' my noob way</p>

```<code>$characters ='012345678901234567890123456789abcdefghijklmnopqrstuvwxyz0123456789';
$randomString = '';

$count = strlen($characters);

for ($i = 0; $i < 32; $i++) {
    $random = rand(0, $count - 1);
    if($i == 8 || $i == 13 || $i == 17 || $i == 21){
        $randomString .= "-";
    }
    $randomString .= $characters[$random];
}

echo $randomString;
</code>```

Body:
with the current code i'm getting are in5v6wyio0er5isu9rv4, so how do i get more number and less alphabets in the id?

below is the code which i have done

    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $randomString = '';

    for ($i = 0; $i < 20; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }

    echo $randomString;

i would like to get the id in this format 6437270e-c2d4-4524-8a26-ad311c4ca55e.

Body:
Do some edit base on your code,and that' my noob way

$characters ='012345678901234567890123456789abcdefghijklmnopqrstuvwxyz0123456789';
$randomString = '';

$count = strlen($characters);

for ($i = 0; $i < 32; $i++) {
    $random = rand(0, $count - 1);
    if($i == 8 || $i == 13 || $i == 17 || $i == 21){
        $randomString .= "-";
    }
    $randomString .= $characters[$random];
}

echo $randomString;


问:
How to restore a quote in Magento when returning to the Onepage checkout?
I am using Magento Enterprise, with a Datacash 3D Secure payment module.

In the event of an error during the payment process I want the user returned to the onepage checkout with their basket intact. Currently when the user returns to the checkout the basket is empty so they are then forwarded to the "checkout/cart" because they have no items.

I thought it might be a problem with my code so I have the initial payment action redirecting straight away with an error back to the onepage checkout.

```<code> public function redirectAction() {
  Mage::getSingleton('core/session')->addError("There was a problem with the payment gateway. Please try again");
  $session = Mage::getSingleton('checkout/session');
  return $this->_redirect('checkout/onepage/', array('_secure'=>true));
}
</code>```

However on returning to the checkout page the basket is empty. Adding in the following log into the indexAction of the onepage checkout I get "Quote ". Looking in the database the quote has had its active status set to 0.

```<code> error_log("Quote ".Mage::getSingleton('checkout/session')->getQuoteId());
</code>```

I have not came across this problem with the standard Magento only with Enterprise. Has anyone come across this issue? Ideally I do not want customers having to add products to the basket again. Its like its conflicting with some sort of Magento Enterprise module.

Thanks in advance for any help!

答:
Basically you answered your own question. load the quote (if it's not available) and perform this: </p>

```<code>$yourQuote()->setIsActive(true);
</code>```

Body:
I am using Magento Enterprise, with a Datacash 3D Secure payment module.

In the event of an error during the payment process I want the user returned to the onepage checkout with their basket intact. Currently when the user returns to the checkout the basket is empty so they are then forwarded to the "checkout/cart" because they have no items.

I thought it might be a problem with my code so I have the initial payment action redirecting straight away with an error back to the onepage checkout.

 public function redirectAction() {
  Mage::getSingleton('core/session')->addError("There was a problem with the payment gateway. Please try again");
  $session = Mage::getSingleton('checkout/session');
  return $this->_redirect('checkout/onepage/', array('_secure'=>true));
}

However on returning to the checkout page the basket is empty. Adding in the following log into the indexAction of the onepage checkout I get "Quote ". Looking in the database the quote has had its active status set to 0.

 error_log("Quote ".Mage::getSingleton('checkout/session')->getQuoteId());

I have not came across this problem with the standard Magento only with Enterprise. Has anyone come across this issue? Ideally I do not want customers having to add products to the basket again. Its like its conflicting with some sort of Magento Enterprise module.

Thanks in advance for any help!

Body:
Basically you answered your own question. load the quote (if it's not available) and perform this:

$yourQuote()->setIsActive(true);


问:
apache2: Your Ruby version is 2.1.6, but your Gemfile specified 2.3.4
I am trying to render my Rails app on Chrome.
But, I am getting an error page of Passenger:

```<code>We're sorry, but something went wrong.
The issue has been logged for investigation. Please try again later.

Technical details for the administrator of this website
This website is powered by Passenger®, a rock-solid, feature-rich web application server that integrates with Apache and Nginx built by Phusion®.
</code>```

The apache error log says that I am having the following error:

```<code>Your Ruby version is 2.1.6, but your Gemfile specified 2.3.4
</code>```

I did the following but it didn't help:

```<code>$ruby -v
ruby 2.3.4p301 (2017-03-30 revision 58214) [x86_64-darwin16]

$rbenv version
2.3.4 (set by /Users/.../.rbenv/version)

$gem update bundler
Updating installed gems
Nothing to update

$ brew upgrade ruby-build
Error: ruby-build 20170523 already installed

$ bundle install
...Bundle complete!...
</code>```

Does anyone know how to fix it?
Thanks in advance!

答:
we need to tell Passenger where it is.Passenger uses the gems installed with the system Ruby instead of the new versions.

Edit /etc/apache2/mods-available/passenger.conf`:

```<code><IfModule mod_passenger.c>
  PassengerRoot /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini
  PassengerDefaultRuby /home/$YOUR_HOME_DIRECTORY/.rbenv/shims/ruby
</IfModule>
</code>```

Body:
I am trying to render my Rails app on Chrome.
But, I am getting an error page of Passenger:

We're sorry, but something went wrong.
The issue has been logged for investigation. Please try again later.

Technical details for the administrator of this website
This website is powered by Passenger®, a rock-solid, feature-rich web application server that integrates with Apache and Nginx built by Phusion®.

The apache error log says that I am having the following error:

Your Ruby version is 2.1.6, but your Gemfile specified 2.3.4

I did the following but it didn't help:

$ruby -v
ruby 2.3.4p301 (2017-03-30 revision 58214) [x86_64-darwin16]

$rbenv version
2.3.4 (set by /Users/.../.rbenv/version)

$gem update bundler
Updating installed gems
Nothing to update

$ brew upgrade ruby-build
Error: ruby-build 20170523 already installed

$ bundle install
...Bundle complete!...

Does anyone know how to fix it?
Thanks in advance!

Body:
we need to tell Passenger where it is.Passenger uses the gems installed with the system Ruby instead of the new versions.

Edit /etc/apache2/mods-available/passenger.conf`:

<IfModule mod_passenger.c>
  PassengerRoot /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini
  PassengerDefaultRuby /home/$YOUR_HOME_DIRECTORY/.rbenv/shims/ruby
</IfModule>


问:
Clickhouse JDBC driver class name
Has anyone used Spring JDBC with Clickhouse? What is the driver class name?</p>

```<code>spring.datasource.driver-class-name=<what is it?>
</code>```

答:
I guess it could be it, even though it doesn't look like any other driver class names that I have seen.</p>

```<code>spring.datasource.driver-class-name=ru.yandex.clickhouse.ClickHouseDriver
</code>```

Title: Clickhouse JDBC driver class name

Body:
Has anyone used Spring JDBC with Clickhouse? What is the driver class name?

spring.datasource.driver-class-name=<what is it?>

Body:
I guess it could be it, even though it doesn't look like any other driver class names that I have seen.

spring.datasource.driver-class-name=ru.yandex.clickhouse.ClickHouseDriver


问:
Why is my prepareForSegue method not being called?
When I press the back button in this navigation controller, I want to send the state of the switches to variables in a different View Controller. However, the prepareForSegue method is not being called. How do I fix this?

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("here")
    let secondViewController:ViewController2 = segue.destination as! ViewController2

    if undoSwitch.isOn {
        secondViewController.undoControls[0] = true
    }
    else {
     secondViewController.undoControls[0] = false
    }
}
</code>```

答:
Rewrite your self.navigationItem.leftBarButtonItem, add an action to it, and do whatever you want.
Or use https://github.com/onegray/UIViewController-BackButtonHandler

Body:
When I press the back button in this navigation controller, I want to send the state of the switches to variables in a different View Controller. However, the prepareForSegue method is not being called. How do I fix this?

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    print("here")
    let secondViewController:ViewController2 = segue.destination as! ViewController2

    if undoSwitch.isOn {
        secondViewController.undoControls[0] = true
    }
    else {
     secondViewController.undoControls[0] = false
    }
}