问:
Wagtail Blog example results in no attribute '_default_manager'
I'm working through the wagtail tutorial. Using Python 3.6.7, Wagtail 2.5.1, Django 2.2.1.  Everything works until I get to adding the categories near the end of the page ...

```<code>class ArticlePage(Page):
    date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)
    tags = ClusterTaggableManager(through=ArticlePageTag, blank=True)
    categories = ParentalManyToManyField('article.ArticleCategory', blank=True)

# ... (Keep the main_image method and search_fields definition)

content_panels = Page.content_panels + [
    MultiFieldPanel([
        FieldPanel('date'),
        FieldPanel('tags'),
        FieldPanel('categories', widget=forms.CheckboxSelectMultiple),
    ], heading="Article information"),
    FieldPanel('intro'),
    FieldPanel('body'),
    InlinePanel('gallery_images', label="Gallery images"),
]
</code>```

The FieldPanel "categories" produces an error.  Here is the Traceback when running makemigrations :

```<code>(env) simon@ckweb$ ./manage.py makemigrations                                                                                │Watching for file changes with StatReloader
Traceback (most recent call last):                                                                                │Exception in thread django-main-thread:
  File "./manage.py", line 10, in <module>                                                                                │Traceback (most recent call last):
    execute_from_command_line(sys.argv)                                                                                │  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line                               │    self.run()
    utility.execute()                                                                                │  File "/usr/lib/python3.6/threading.py", line 864, in run
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute                                                 │    self._target(*self._args, **self._kwargs)
    self.fetch_command(subcommand).run_from_argv(self.argv)                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv                                               │    fn(*args, **kwargs)
    self.execute(*args, **cmd_options)                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute                                                     │    autoreload.raise_last_exception()
    self.check()                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check                                                       │    raise _exception[0](_exception[1]).with_traceback(_exception[2])
    include_deployment_checks=include_deployment_checks,                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks                                                 │    fn(*args, **kwargs)
    return checks.run_checks(**kwargs)                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks                                                   │    apps.populate(settings.INSTALLED_APPS)
    new_errors = check(app_configs=app_configs)                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate
  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/checks.py", line 63, in get_form_class_check                                                │    app_config.import_models()
    if not issubclass(edit_handler.get_form_class(), WagtailAdminPageForm):                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models
  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 369, in get_form_class                                              │    self.models_module = import_module(models_module_name)
    widgets=self.widget_overrides())                                                                                │  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 64, in get_form_for_model                                           │    return _bootstrap._gcd_import(name[level:], package, level)
    return metaclass(class_name, (form_class,), form_class_attrs)                                                                                │  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/forms/models.py", line 66, in __new__                                                       │  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
    new_class = super(WagtailAdminModelFormMetaclass, cls).__new__(cls, name, bases, attrs)                                                                      │  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "/home/simon/.local/lib/python3.6/site-packages/modelcluster/forms.py", line 245, in __new__                                                              │  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
    new_class = super(ClusterFormMetaclass, cls).__new__(cls, name, bases, attrs)                                                                                │  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "/home/simon/.local/lib/python3.6/site-packages/django/forms/models.py", line 256, in __new__                                                             │  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
    apply_limit_choices_to=False,                                                                                │  File "/mnt/c/Users/simon/OneDrive/dev/wagtail/ckweb/articles/models.py", line 33, in <module>
  File "/home/simon/.local/lib/python3.6/site-packages/django/forms/models.py", line 176, in fields_for_model                                                    │    class ArticlePage(Page):
    formfield = formfield_callback(f, **kwargs)                                                                                │  File "/mnt/c/Users/simon/OneDrive/dev/wagtail/ckweb/articles/models.py", line 58, in ArticlePage
  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/forms/models.py", line 47, in formfield_for_dbfield                                         │    InlinePanel('related_content_page', widget=forms.CheckboxSelectMultiple),
    return db_field.formfield(**kwargs)                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 646, in __init__
  File "/home/simon/.local/lib/python3.6/site-packages/django/db/models/fields/related.py", line 1626, in formfield                                              │    super().__init__(*args, **kwargs)
    'queryset': self.remote_field.model._default_manager.using(using),                                                                                │TypeError: __init__() got an unexpected keyword argument 'widget'
AttributeError: 'str' object has no attribute '_default_manager'
</code>```

Commenting out FieldPanel and categories lines removes the error.  I believe it is related to the "ParentalManyToManyField".  I have a couple of Categories defined through the wagtail UI

The source is on GitHub, although the App is called Articles, rather than Blog used in the example. Sure I am missing something simple but cant see it for the life of me.  Any help gratefully received.

答:
The relation is referenced by app_name.ModelName. In your case the app name is articles (plural).

Change:

```<code>ParentalManyToManyField('article.ArticleCategory', blank=True)
</code>```

To

```<code>ParentalManyToManyField('articles.ArticleCategory', blank=True)
</code>```

Body:
I'm working through the wagtail tutorial. Using Python 3.6.7, Wagtail 2.5.1, Django 2.2.1.  Everything works until I get to adding the categories near the end of the page ...

class ArticlePage(Page):
    date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)
    tags = ClusterTaggableManager(through=ArticlePageTag, blank=True)
    categories = ParentalManyToManyField('article.ArticleCategory', blank=True)

# ... (Keep the main_image method and search_fields definition)

content_panels = Page.content_panels + [
    MultiFieldPanel([
        FieldPanel('date'),
        FieldPanel('tags'),
        FieldPanel('categories', widget=forms.CheckboxSelectMultiple),
    ], heading="Article information"),
    FieldPanel('intro'),
    FieldPanel('body'),
    InlinePanel('gallery_images', label="Gallery images"),
]

The FieldPanel "categories" produces an error.  Here is the Traceback when running makemigrations :

(env) simon@ckweb$ ./manage.py makemigrations                                                                                │Watching for file changes with StatReloader
Traceback (most recent call last):                                                                                │Exception in thread django-main-thread:
  File "./manage.py", line 10, in <module>                                                                                │Traceback (most recent call last):
    execute_from_command_line(sys.argv)                                                                                │  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line                               │    self.run()
    utility.execute()                                                                                │  File "/usr/lib/python3.6/threading.py", line 864, in run
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute                                                 │    self._target(*self._args, **self._kwargs)
    self.fetch_command(subcommand).run_from_argv(self.argv)                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv                                               │    fn(*args, **kwargs)
    self.execute(*args, **cmd_options)                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute                                                     │    autoreload.raise_last_exception()
    self.check()                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check                                                       │    raise _exception[0](_exception[1]).with_traceback(_exception[2])
    include_deployment_checks=include_deployment_checks,                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks                                                 │    fn(*args, **kwargs)
    return checks.run_checks(**kwargs)                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
  File "/home/simon/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks                                                   │    apps.populate(settings.INSTALLED_APPS)
    new_errors = check(app_configs=app_configs)                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate
  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/checks.py", line 63, in get_form_class_check                                                │    app_config.import_models()
    if not issubclass(edit_handler.get_form_class(), WagtailAdminPageForm):                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models
  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 369, in get_form_class                                              │    self.models_module = import_module(models_module_name)
    widgets=self.widget_overrides())                                                                                │  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 64, in get_form_for_model                                           │    return _bootstrap._gcd_import(name[level:], package, level)
    return metaclass(class_name, (form_class,), form_class_attrs)                                                                                │  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/forms/models.py", line 66, in __new__                                                       │  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
    new_class = super(WagtailAdminModelFormMetaclass, cls).__new__(cls, name, bases, attrs)                                                                      │  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "/home/simon/.local/lib/python3.6/site-packages/modelcluster/forms.py", line 245, in __new__                                                              │  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
    new_class = super(ClusterFormMetaclass, cls).__new__(cls, name, bases, attrs)                                                                                │  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "/home/simon/.local/lib/python3.6/site-packages/django/forms/models.py", line 256, in __new__                                                             │  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
    apply_limit_choices_to=False,                                                                                │  File "/mnt/c/Users/simon/OneDrive/dev/wagtail/ckweb/articles/models.py", line 33, in <module>
  File "/home/simon/.local/lib/python3.6/site-packages/django/forms/models.py", line 176, in fields_for_model                                                    │    class ArticlePage(Page):
    formfield = formfield_callback(f, **kwargs)                                                                                │  File "/mnt/c/Users/simon/OneDrive/dev/wagtail/ckweb/articles/models.py", line 58, in ArticlePage
  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/forms/models.py", line 47, in formfield_for_dbfield                                         │    InlinePanel('related_content_page', widget=forms.CheckboxSelectMultiple),
    return db_field.formfield(**kwargs)                                                                                │  File "/home/simon/.local/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py", line 646, in __init__
  File "/home/simon/.local/lib/python3.6/site-packages/django/db/models/fields/related.py", line 1626, in formfield                                              │    super().__init__(*args, **kwargs)
    'queryset': self.remote_field.model._default_manager.using(using),                                                                                │TypeError: __init__() got an unexpected keyword argument 'widget'
AttributeError: 'str' object has no attribute '_default_manager'

Commenting out FieldPanel and categories lines removes the error.  I believe it is related to the "ParentalManyToManyField".  I have a couple of Categories defined through the wagtail UI

The source is on GitHub, although the App is called Articles, rather than Blog used in the example. Sure I am missing something simple but cant see it for the life of me.  Any help gratefully received.

Body:
The relation is referenced by app_name.ModelName. In your case the app name is articles (plural).

Change:

ParentalManyToManyField('article.ArticleCategory', blank=True)

To

ParentalManyToManyField('articles.ArticleCategory', blank=True)


来源: stackexchange

问:
Sum and joined column data in same query
I am using Oracle DB and have the following query which throws the error:

ORA-00937: not a single-group group function

Query:

```<code>select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText';
</code>```

If I try to access the following individually, it works. As in calling sum separately, ct.CREAT_TS separately and so on.

The issue seems to be calling sum in this query. I plan to capture the output in an Object (Java if relevant). I expected the query to output  following. Is it possible to achieve this?

```<code>CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   8
2019-04-02 02:56:14.530000    SOME_EVENT 2
</code>```

After Given answers, getting following results where the sum value is split per column:

```<code>CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   2
2019-04-02 02:56:14.530000    SOME_EVENT 2   6
</code>```

答:
If at least one aggregated column exists in the select list, you need to group by non-aggregated columns </p>

```<code>select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText'
    group by ct.CREAT_TS, ev.EVENT
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Oracle DB and have the following query which throws the error:

ORA-00937: not a single-group group function

Query:

select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText';

If I try to access the following individually, it works. As in calling sum separately, ct.CREAT_TS separately and so on.

The issue seems to be calling sum in this query. I plan to capture the output in an Object (Java if relevant). I expected the query to output  following. Is it possible to achieve this?

CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   8
2019-04-02 02:56:14.530000    SOME_EVENT 2

After Given answers, getting following results where the sum value is split per column:

CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   2
2019-04-02 02:56:14.530000    SOME_EVENT 2   6

Body:
If at least one aggregated column exists in the select list, you need to group by non-aggregated columns

select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText'
    group by ct.CREAT_TS, ev.EVENT


问:
How to replace elements in list/array with dictionary values?
I have following code:

```<code># dict for replacements
replacements = {'*': 0, ' ': 1, 'A': 2, 'B': 3}
# open and read file
file = open(file, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
# create array
maze_array = np.zeros((rows, cols), dtype=str)
# add lines to array
for index, line in enumerate(lines):
    for i in range(0, len(line) - 1):
        maze_array[index][i] = line[i]
return maze_array
</code>```

This opens a file where the content is just '*', ' ', 'A' or 'B'. From that file I read the lines and get the number of rows as well as columns. Then I create a pseudo array where I add the lines to get following output:

```<code>[['*' ' ' '*' ... '*' ' ' '*']
['*' ' ' '*' ... ' ' 'B' '*']
['*' '*' '*' ... '*' '*' '*']]
</code>```

When I print out the variable lines above, I get following output:

```<code>['*****************************************************************\n', '...']
</code>```

Now my goal is to replace the '*', ' ', 'A' or 'B' with the values from the dictionary (0, 1, 2 or 3). How can I reach my goal?

答:
When assigning the characters to the array, attempt to get the corresponding replacement value:

```<code>for index, line in enumerate(lines):
    for i in range(0, len(line) - 1):
        maze_array[index][i] = replacements.get(line[i], line[i])
</code>```

The dict.get is used with the default value as the character itself so that if a character that has no replacement is encountered, the program will continue normally.

Body:
I have following code:

# dict for replacements
replacements = {'*': 0, ' ': 1, 'A': 2, 'B': 3}
# open and read file
file = open(file, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
# create array
maze_array = np.zeros((rows, cols), dtype=str)
# add lines to array
for index, line in enumerate(lines):
    for i in range(0, len(line) - 1):
        maze_array[index][i] = line[i]
return maze_array

This opens a file where the content is just '*', ' ', 'A' or 'B'. From that file I read the lines and get the number of rows as well as columns. Then I create a pseudo array where I add the lines to get following output:

[['*' ' ' '*' ... '*' ' ' '*']
['*' ' ' '*' ... ' ' 'B' '*']
['*' '*' '*' ... '*' '*' '*']]

When I print out the variable lines above, I get following output:

['*****************************************************************\n', '...']

Now my goal is to replace the '*', ' ', 'A' or 'B' with the values from the dictionary (0, 1, 2 or 3). How can I reach my goal?

Body:
When assigning the characters to the array, attempt to get the corresponding replacement value:

for index, line in enumerate(lines):
    for i in range(0, len(line) - 1):
        maze_array[index][i] = replacements.get(line[i], line[i])

The dict.get is used with the default value as the character itself so that if a character that has no replacement is encountered, the program will continue normally.


问:
Error at accessing database table data in javascript
I have a database table and I am listing it into a jsp table. I have author names, titles, dates and quantities in it. I want to make an edit function and to display the current id with its corresponding data. I have managed to access all the data, but the author and the title. I am using the same method, accesing them through javascript, but it gives me this error for title and author:
Uncaught ReferenceError: MP is not defined at HTMLButtonElement.onclick
where "MP" is an author name. I don't understand how the code manages to see the current author's name, but not display it in the edit field and thus triggering the error... I have simplified the function down there, to see what is triggering my error...

```<code>  <c:forEach var="book" items="${bookAttribute}">
    <tr id="book_${book.id}">
        <td><c:out value="${book.author}"/></td>

 <button class="button" id="editButton_${book.id}" type="submit" name="editButton" onclick="editBooks(${book.author})">
</button>

function editBooks(author) {
        document.getElementById("authorText").value = author;
}

</code>```

答:
You have at least one problem and potentially two (but you haven't provided enough information to determine the second).

First, you are attempting to pass a string into your editBooks() function like this:

```<code>onclick="editBooks(${book.author})"
</code>```

In the case of the author named MP, the result looks like this:

```<code>onclick="editBooks(MP)"
</code>```

As you can see, there is no variable defined as MP so you see that error.

To fix put quotes around the interprelation like this:

```<code>onclick="editBooks('${book.author}')"
</code>```

The second problem may be related to this code:

```<code>document.getElementById("authorText").value = author;
</code>```

If the element with the id of authorText is NOT an HTMLInputElement, this code won't do what you expect. Only HTMLInputElements have a value property. Elements like
s have textContent properties. So depending on the type of element you are putting the author's name into, you may need to change this:

```<code>document.getElementById("authorText").value = author;
</code>```

To this:

```<code>document.getElementById("authorText").textContent = author;
</code>```

Body:
I have a database table and I am listing it into a jsp table. I have author names, titles, dates and quantities in it. I want to make an edit function and to display the current id with its corresponding data. I have managed to access all the data, but the author and the title. I am using the same method, accesing them through javascript, but it gives me this error for title and author:
Uncaught ReferenceError: MP is not defined at HTMLButtonElement.onclick
where "MP" is an author name. I don't understand how the code manages to see the current author's name, but not display it in the edit field and thus triggering the error... I have simplified the function down there, to see what is triggering my error...

  <c:forEach var="book" items="${bookAttribute}">

        <c:out value="${book.author}"/>

 <button class="button" id="editButton_${book.id}" type="submit" name="editButton" onclick="editBooks(${book.author})">
</button>

function editBooks(author) {
        document.getElementById("authorText").value = author;
}

Body:
You have at least one problem and potentially two (but you haven't provided enough information to determine the second).

First, you are attempting to pass a string into your editBooks() function like this:

onclick="editBooks(${book.author})"

In the case of the author named MP, the result looks like this:

onclick="editBooks(MP)"

As you can see, there is no variable defined as MP so you see that error.

To fix put quotes around the interprelation like this:

onclick="editBooks('${book.author}')"

The second problem may be related to this code:

document.getElementById("authorText").value = author;

If the element with the id of authorText is NOT an HTMLInputElement, this code won't do what you expect. Only HTMLInputElements have a value property. Elements like <div>s have textContent properties. So depending on the type of element you are putting the author's name into, you may need to change this:

document.getElementById("authorText").value = author;

To this:

document.getElementById("authorText").textContent = author;


问:
Firebase functions authentication with hosting stripping Authentication header
I have Firebase functions backend rest api and custom domain Firebase hosting pointed to it so I don't lock myself to Firebase provided domain.

At this moment I can reach my backend at 3 urls.

https://us-central1-my-project.cloudfunctions.net/app - Default url provided by firebase to directly call function.

https://my-project.firebaseapp.com/api - Default hosting provided by Firebase, rewriting the /api source to app function.

https://my-custom-domain.com/api - My custom domain set up in Firebase, rewriting the /api source to app function.

Now, I can reach my backend on any of these just fine, with one exception.
I've added an authentication requirement to my functions based on https://github.com/firebase/functions-samples/tree/master/authorized-https-endpoint

E.g., my client sends Authorization: Bearer IdToken, then Express middleware reads it and verifies it with Firebase Auth.

My problem is that the Authorization header is not present in request when the client accesses the backend via 3rd url. The 1st and the 2nd work just fine.

Would anybody know what do I have to configure so the header is forwarded properly?

Thanks

P.S.: This is my hosting configuration:

```<code>{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "/api/**",
        "function": "app"
      }
    ]
  }
}

</code>```

答:
Solved, the problem was the following:

I own mydomain.com and www.mydomain.com. My Firebase hosting is set to serve from www and mydomain.com only redirects to www.mydomain.com. I've setup clients to call mydomain.com instead of www.mydomain.com. Hence the redirect stripped headers. All I had to do is to point my clients to www.

Body:
I have Firebase functions backend rest api and custom domain Firebase hosting pointed to it so I don't lock myself to Firebase provided domain.

At this moment I can reach my backend at 3 urls.

https://us-central1-my-project.cloudfunctions.net/app - Default url provided by firebase to directly call function.

https://my-project.firebaseapp.com/api - Default hosting provided by Firebase, rewriting the /api source to app function.

https://my-custom-domain.com/api - My custom domain set up in Firebase, rewriting the /api source to app function.

Now, I can reach my backend on any of these just fine, with one exception.
I've added an authentication requirement to my functions based on https://github.com/firebase/functions-samples/tree/master/authorized-https-endpoint

E.g., my client sends Authorization: Bearer IdToken, then Express middleware reads it and verifies it with Firebase Auth.

My problem is that the Authorization header is not present in request when the client accesses the backend via 3rd url. The 1st and the 2nd work just fine.

Would anybody know what do I have to configure so the header is forwarded properly?

Thanks

P.S.: This is my hosting configuration:

{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "/api/**",
        "function": "app"
      }
    ]
  }
}


问:
Request validation using serverless framework
I am using serverless framework for the backend. How can I implement request validation? (do not want to write validation inside lambda functions). </p>

答:
This is now supported by Serverless framework, so there is no need to use external plugins.

To enable requests validation one need is to add the following to the serverless.yml:

```<code>  HttpHandler:
    handler: src/lambda/http/create.handler
    events:
      - http:
          method: post
          path: items
          request:
            schemas:
              application/json: ${file(models/create-todo-model.json)}
</code>```

Instead of keeping the file location directly under application/json you can also keep the name of the model after defining it under serverless.yml file's apiGateway section. link to documentation

Kindly note that, as of Feb-2022, serverless-offline plugin is not validating the http.request.schemas in your local. Though they are supporting deprecated version http.request.schema.

ContentLicense: CC BY-SA 3.0

Body:
This is now supported by Serverless framework, so there is no need to use external plugins.

To enable requests validation one need is to add the following to the serverless.yml:

  HttpHandler:
    handler: src/lambda/http/create.handler
    events:
      - http:
          method: post
          path: items
          request:
            schemas:
              application/json: ${file(models/create-todo-model.json)}

Instead of keeping the file location directly under application/json you can also keep the name of the model after defining it under serverless.yml file's apiGateway section. link to documentation

Kindly note that, as of Feb-2022, serverless-offline plugin is not validating the http.request.schemas in your local. Though they are supporting deprecated version http.request.schema.


问:
So I'm trying to understand Exists condition in sql. I know it returns True if there exists one or more tuples
How does with work. My nested query returns only 3 tuples. But when combined with outer query, it(outer query) returns 736 tuples. And this is the same amount of tuples if I write a query say select p.height from ... where True.

I read the books which says it only returns true which makes sense in my case. Also read few online article where exists returns True but the outer query only selects from the results of nested query.

mysql-workbench

```<code>select p.height
from world_cup.player as p
where Exists(select q.height from world_cup.player as q where q.height = 165)
order by p.height;
</code>```

Actual result should have been those three tuples 165, 165, 165(according to the book and online resources)

答:
EXISTS is true if and only if the subquery returns at least one tuple.

So as long there's at least one player with a height of 165, your EXISTS returns true, for all tuples of the outer query that is. If there were no such player you had an empty set as result. So you see your use is pretty static and maybe doesn't make too much sense used in that way, unless that is what you intended.

Usually the subquery to an EXISTS is correlated, i.e. a value of the outer query appears in the WHERE clause of the inner query, so that the results of EXISTS can differ from tuple to tuple of the outer query.

If you just want player with a height of 165 simply use the equality expression in the WHERE clause.

```<code>SELECT p.height
       FROM world_cup.player as p
       WHERE p.height = 165;
</code>```

The ORDER BY p.height is useless then too as they're all the same.

Body:
How does with work. My nested query returns only 3 tuples. But when combined with outer query, it(outer query) returns 736 tuples. And this is the same amount of tuples if I write a query say select p.height from ... where True.

I read the books which says it only returns true which makes sense in my case. Also read few online article where exists returns True but the outer query only selects from the results of nested query.

mysql-workbench

select p.height
from world_cup.player as p
where Exists(select q.height from world_cup.player as q where q.height = 165)
order by p.height;

Actual result should have been those three tuples 165, 165, 165(according to the book and online resources)

Body:
EXISTS is true if and only if the subquery returns at least one tuple.

So as long there's at least one player with a height of 165, your EXISTS returns true, for all tuples of the outer query that is. If there were no such player you had an empty set as result. So you see your use is pretty static and maybe doesn't make too much sense used in that way, unless that is what you intended.

Usually the subquery to an EXISTS is correlated, i.e. a value of the outer query appears in the WHERE clause of the inner query, so that the results of EXISTS can differ from tuple to tuple of the outer query.

If you just want player with a height of 165 simply use the equality expression in the WHERE clause.

SELECT p.height
       FROM world_cup.player as p
       WHERE p.height = 165;

The ORDER BY p.height is useless then too as they're all the same.


问:
'Could not load file or assembly 'FSharp.Core, Version=4.6.2.0
I upgraded Visual Studio from VS2017 to VS2019.  I opened a solution with both C# and F# in it.  A C# unit test project references a F# .dll project.

The solution compiles fine but at run time, I get the following message

System.IO.FileLoadException: 'Could not load file or assembly
  'FSharp.Core, Version=4.6.2.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
  located assembly's manifest definition does not match the assembly
  reference. (Exception from HRESULT: 0x80131040)'

and the inner exception is

Could not load file or assembly 'FSharp.Core, Version=4.6.0.0,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
  dependencies. The located assembly's manifest definition does not
  match the assembly reference. (Exception from HRESULT: 0x80131040)

I have this in the unit tests app.config:

```<code>  <dependentAssembly>
    <assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.6.2.0" newVersion="4.6.2.0" />
  </dependentAssembly>
</code>```

and the unit test project has this in the packages.config

```<code><package id="FSharp.Core" version="4.6.2" targetFramework="net461" />
</code>```

Is there a missing reference I am not seeing?

Thanks

答:
Bent Tranberg was right

In the test project, I changed the binding redirect to

```<code>       <dependentAssembly>
         <assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
         <bindingRedirect oldVersion="0.0.0.0-4.6.2.0" newVersion="4.6.0.0" />
       </dependentAssembly>
</code>```

and it worked

Body:
I upgraded Visual Studio from VS2017 to VS2019.  I opened a solution with both C# and F# in it.  A C# unit test project references a F# .dll project.

The solution compiles fine but at run time, I get the following message

System.IO.FileLoadException: 'Could not load file or assembly
  'FSharp.Core, Version=4.6.2.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
  located assembly's manifest definition does not match the assembly
  reference. (Exception from HRESULT: 0x80131040)'

and the inner exception is

Could not load file or assembly 'FSharp.Core, Version=4.6.0.0,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
  dependencies. The located assembly's manifest definition does not
  match the assembly reference. (Exception from HRESULT: 0x80131040)

I have this in the unit tests app.config:

  <dependentAssembly>
    <assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.6.2.0" newVersion="4.6.2.0" />
  </dependentAssembly>

and the unit test project has this in the packages.config

<package id="FSharp.Core" version="4.6.2" targetFramework="net461" />

Is there a missing reference I am not seeing?

Thanks

Body:
Bent Tranberg was right

In the test project, I changed the binding redirect to

       <dependentAssembly>
         <assemblyIdentity name="FSharp.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
         <bindingRedirect oldVersion="0.0.0.0-4.6.2.0" newVersion="4.6.0.0" />
       </dependentAssembly>

and it worked


问:
Can the vanilla JS date object be used normally in React.js?
I'm trying to get the last date of the current month so I can accurately display calendar days so I'm using the vanilla JS date object. However, from what I've seen by console logging the date object, it seems as though it's a completely different object, presumably a react object. So how can I access the date object?

I've tried using the toString method to unwrap the date object into a string which didn't work because it turns into an array with the object in it.

```<code>componentDidMount() {
    let date;
    date = new Date(2019, 11, 5);
    console.log(date)
}
</code>```

I expect the date object to be outputted instead of the unknown object

EDIT:

The unknown object looks like this in the console:

```<code>{$$typeof: Symbol(react.element), type: "div", key: null, ref: null,
props: {…}, …}
</code>```

DOUBLE EDIT:

Here's the  minimum reproducible code.

So while doing this I figured out that the date changes from the default
date structure
Ex. Mon May 27 2019 16:00:56 etc. to the other object when I import in the Date component for some reason.

File App.js

```<code>import React from "react";
import Calendar from "./Calendar"

function App() {
    return (
        <div>
            <Calendar />
        </div>

    )
}

export default App;
</code>```

File Calendar.js

```<code>import React from "react";
import Date from "./Date";

class Calendar extends React.Component {
    constructor() {
        super();
    }

    componentDidMount() {
        let date = new Date();
        console.log(date)
    }

    render() {
        return (
            <Date />
        )
    }
}

export default Calendar;
</code>```

File Date.js

```<code>import React from "react";

function Date() {
    return (
        <div className="grid date">
            <p>1</p>
        </div>
    )
}

export default Date;
</code>```

答:
```<code>import React, { Component } from "react";

export default class App extends Component {
  state = {
    date: ""
  };
  componentDidMount() {
    this.setState({
      date: new Date().toISOString().slice(0, 10)
    });
  }
  render() {
    return <div>{this.state.date}</div>;
  }
}
</code>```

Remember there are tons of ways to achieve this.  But keeping it Vanilla flavoured as per OP's request.

Body:
I'm trying to get the last date of the current month so I can accurately display calendar days so I'm using the vanilla JS date object. However, from what I've seen by console logging the date object, it seems as though it's a completely different object, presumably a react object. So how can I access the date object?

I've tried using the toString method to unwrap the date object into a string which didn't work because it turns into an array with the object in it.

componentDidMount() {
    let date;
    date = new Date(2019, 11, 5);
    console.log(date)
}

I expect the date object to be outputted instead of the unknown object

EDIT:

The unknown object looks like this in the console:

{$$typeof: Symbol(react.element), type: "div", key: null, ref: null,
props: {…}, …}

DOUBLE EDIT:

Here's the  minimum reproducible code.

So while doing this I figured out that the date changes from the default
date structure
Ex. Mon May 27 2019 16:00:56 etc. to the other object when I import in the Date component for some reason.

File App.js

import React from "react";
import Calendar from "./Calendar"

function App() {
    return (

            <Calendar />

    )
}

export default App;

File Calendar.js

import React from "react";
import Date from "./Date";

class Calendar extends React.Component {
    constructor() {
        super();
    }

    componentDidMount() {
        let date = new Date();
        console.log(date)
    }

    render() {
        return (
            <Date />
        )
    }
}

export default Calendar;

File Date.js

import React from "react";

function Date() {
    return (

1

    )
}

export default Date;

Body:
import React, { Component } from "react";

export default class App extends Component {
  state = {
    date: ""
  };
  componentDidMount() {
    this.setState({
      date: new Date().toISOString().slice(0, 10)
    });
  }
  render() {
    return <div>{this.state.date}</div>;
  }
}

Remember there are tons of ways to achieve this.  But keeping it Vanilla flavoured as per OP's request.


Title: I want to hide all other div's when i click on one div

Body:
I am making a software were i need to hide all other div's when i click on another div. what happens now is that the div's just stack on top of each other. and the div only dissapears when i click the same div again.

i already tried some of the JavaScript and jQuery code on this platform but can't quite figure it out myself.

--- THIS IS THE SCRIPT IM USING TO SHOW AND HIDE THE DIV'S ---

--- THESE ARE MY CLICKABLE AREA'S WHERE THE USER CAN CLICK ON TO SHOW AND HIDE A DIV ---

        <map name="Map" id="Map">

     <area onclick="toggle_visibility('vooglid');" alt="" title="" href="#" shape="poly" coords=170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
        <area onclick="toggle_visibility('vwimpers');" alt="" title="" href="#" shape="poly" coords="170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
        <area onclick="toggle_visibility('vwenkbrauw');" alt="" title="" href="#" shape="poly" coords="43,157,62,120,84,103,114,85,132,75,151,65,191,47,204,38,232,31,268,31,298,31,317,31,339,33,365,42,390,47,408,51,429,59,445,61,467,69,484,74,501,85,504,127,498,141,494,146,471,136,446,123,432,119,412,113,396,108,376,100,362,96,354,93,334,90,321,90,308,89,295,87,271,83,260,81,232,75,218,74,207,73,192,73,181,76,150,95,122,109,102,118,78,138,62,149,54,158,49,163,47,167" />
        <area onclick="toggle_visibility('vooghoek');" alt="" title="" href="#" shape="poly" coords="388,275,396,270,401,270,407,266,408,263,411,258,420,263,425,269,428,273,432,278,435,280,434,282,434,285,422,284,414,279" />

    </map>

--- AND THESE ARE MY DIV'S CONTAINING THE INFORMATION IT HAS TO SHOW AND HIDE ---

 Symptoom ooglid

 Symptoom wimper

 Symptoom wenkbrauw

 Symptoom ooghoek

I want the result to be that when I click one of the areas above, the corresponding div shows and all other divs hide.

Body:
Something like that ?

const AlldivTest = document.querySelectorAll('.test');

document.querySelector('#Map').onclick =e=>{
  if (!e.target.matches('area')) return;
  e.stopPropagation();

  AlldivTest.forEach(d=>{
    if (d.id===e.target.dataset.elm)
      { d.style.display = (d.style.display==='none') ? 'block' : 'none' }
    else
      { d.style.display = 'none' }
  })
}

.test { display: none; border:1px solid grey; padding: 5px 10px }
img { width:550px; height:550px }

<div class="div-voog">
  <img class="map" src="images/tekening-oog-vrouw-550px.jpg" alt="" usemap="#Map" />
  <map name="Map" id="Map">
    <area data-elm="vooglid" alt="" title="" href="#" shape="poly"
      coords=170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
    <area data-elm="vwimpers" alt="" title="" href="#" shape="poly"
      coords="170,251,159,253,140,251,134,249,126,244,121,241,118,237,114,226,113,221,118,214,128,204,141,195,160,187,176,178,194,171,208,165,230,157,249,155,268,153,284,151,300,151,326,154,341,158,358,168,371,178,380,190,394,209,402,221,408,235,412,244,403,247,392,242,378,231,366,219,347,207,334,203,316,199,286,199,263,203,246,208,221,218" />
    <area data-elm="vwenkbrauw" alt="" title="" href="#" shape="poly"
      coords="43,157,62,120,84,103,114,85,132,75,151,65,191,47,204,38,232,31,268,31,298,31,317,31,339,33,365,42,390,47,408,51,429,59,445,61,467,69,484,74,501,85,504,127,498,141,494,146,471,136,446,123,432,119,412,113,396,108,376,100,362,96,354,93,334,90,321,90,308,89,295,87,271,83,260,81,232,75,218,74,207,73,192,73,181,76,150,95,122,109,102,118,78,138,62,149,54,158,49,163,47,167" />
    <area data-elm="vooghoek" alt="" title="" href="#" shape="poly"
      coords="388,275,396,270,401,270,407,266,408,263,411,258,420,263,425,269,428,273,432,278,435,280,434,282,434,285,422,284,414,279" />
  </map>
</div>

<div class="test" id="vooglid"> Symptoom ooglid</div>
<div class="test" id="vwimpers"> Symptoom wimper</div>
<div class="test" id="vwenkbrauw"> Symptoom wenkbrauw</div>
<div class="test" id="vooghoek"> Symptoom ooghoek</div>

[edit]
For a quick see of "my" part of code you have to use only one script and it should b: like this

<script>
  $(function () {

    $('.map').maphilight({
      fade: false
    });

    $('.map').maphilight({
      fillColor: '008800'
    });

    $('#hilightlink')
    .mouseover(function (e) { $('#square2').mouseover(); })
    .mouseout(function (e)  { $('#square2').mouseout();  })
    .click(function (e)     { e.preventDefault();        });

    $('#linkerbeenlink')
    .click(function (e) {
      e.preventDefault();
      var data = $('#linkerbeen').data('maphilight') || {};
      data.neverOn = !data.neverOn;
      $('#linkerbeen').data('maphilight', data);
    });

    $('#linkerbeen,#linkerbeenlink2')
    .click(function (e) {
      e.preventDefault();
      var data = $('#linkerbeen').mouseout().data('maphilight') || {};
      data.alwaysOn = !data.alwaysOn;
      $('#linkerbeen').data('maphilight', data).trigger('alwaysOn.maphilight');
    });

    $('#vinger2link')
    .click(function (e) {
      e.preventDefault();
      var data = $('#vinger2').data('maphilight') || {};
      data.neverOn = !data.neverOn;
      $('#vinger2').data('maphilight', data);
    });

    $('#vinger2,#vinger2link2')
    .click(function (e) {
      e.preventDefault();
      var data = $('#vinger2').mouseout().data('maphilight') || {};
      data.alwaysOn = !data.alwaysOn;
      $('#vinger2').data('maphilight', data).trigger('alwaysOn.maphilight');
    });

    const AlldivTest = document.querySelectorAll('.test');

    document.querySelector('#Map').onclick =e=>{
      if (!e.target.matches('area')) return;

      e.stopPropagation();

      AlldivTest.forEach(d=>{
        if (d.id===e.target.dataset.elm)
          { d.style.display = (d.style.display==='none') ? 'block' : 'none' }
        else
          { d.style.display = 'none' }
      })
    }
  });
</script>


问:
Importing Saved Object to Kibana via setup.yml
I have a file in JSON format that Kibana exported as a saved object and it saves an index pattern as well as some visualizations and dashboard I want to install on a fresh image of Kibana and Elasticsearch.

Reading some Elastic for Docker documentation I see that there is the possibility to install Dashboards and Index Patterns via the setup.yml file. The thing is that I don't know how. I have heard about elasticdump but it does not fit me as I need both Elasticsearch instances running at the same time.

答:
Basically it's running shell scripts through a short lived container. The Beats dashboards can be imported through that binary directly, see https://github.com/elastic/stack-docker/blob/master/scripts/setup-beat.sh#L25-L28.

If you have custom dashboards, export them and import them with curl; probably  in https://github.com/elastic/stack-docker/blob/master/scripts/setup-kibana.sh if you are using that Docker repository. You can find the API at https://www.elastic.co/guide/en/kibana/7.1/dashboard-import-api-import.html.


问:
Why won't Flutter mobX store code generate?
I have a mobx store and it's really hit and miss getting my storename.g.dart generated.

The first time, I copied an example from medium and just kept running the generator until eventually it gave code.

The second time, I wrote my own store forgot the abstract keyword. Added it in and it worked.

I thought that was the problem.

Now, third project, I think I have all my code down but it's still not generating. Many actions but no output.

What makes it work or fail? This is my current mobx

```<code>import 'package:mobx/mobx.dart';
import 'package:firebase_auth/firebase_auth.dart';

// have this line
// then generate with
// flutter packages pub run build_runner build
// or
// flutter packages pub run build_runner clean; flutter packages pub run build_runner build --delete-conflicting-outputs

// todo edit this file name
part 'usermodel.g.dart';

class UserModel = UserModelBase with _$UserModel;

abstract class UserModelBase implements Store {
  @observable
  FirebaseUser user;

  @action
  setUser(FirebaseUser u){
    user = u;
  }

  dispose() {}
}
</code>```

答:
Store is should be used as a mixin.

Do:

```<code>abstract class Foo with Store {}
</code>```

Don't:

```<code>abstract class Foo implements Store {
  void dispose() {}
}
</code>```

Body:
I have a mobx store and it's really hit and miss getting my storename.g.dart generated.

The first time, I copied an example from medium and just kept running the generator until eventually it gave code.

The second time, I wrote my own store forgot the abstract keyword. Added it in and it worked.

I thought that was the problem.

Now, third project, I think I have all my code down but it's still not generating. Many actions but no output.

What makes it work or fail? This is my current mobx

import 'package:mobx/mobx.dart';
import 'package:firebase_auth/firebase_auth.dart';

// have this line
// then generate with
// flutter packages pub run build_runner build
// or
// flutter packages pub run build_runner clean; flutter packages pub run build_runner build --delete-conflicting-outputs

// todo edit this file name
part 'usermodel.g.dart';

class UserModel = UserModelBase with _$UserModel;

abstract class UserModelBase implements Store {
  @observable
  FirebaseUser user;

  @action
  setUser(FirebaseUser u){
    user = u;
  }

  dispose() {}
}

Body:
Store is should be used as a mixin.

Do:

abstract class Foo with Store {}

Don't:

abstract class Foo implements Store {
  void dispose() {}
}


问:
Design decisions concerning migrating medium sized content site to drupal 7
We are in the process of moving a legacy asp.net 2.0 content site to drupal 7.  We are a pretty traditional entertainment content site with about 8 years worth of content (5gb database) which consists of mostly custom articles like news, movie reviews etc..

Another big chunk of our data that we import every day includes image galleries of celebrities, syndicated news and most importantly movie, tv and celebrity data from All music guide (AMG).  We have seen first hand what happens to drupal applications that insist on circumventing the drupal API for importing and working with data and understand the huge performance nightmare that can become but our main concern is what to do with importing so much domain specific movie, tv and celebrity data and then having to access it afterwards?

My question is would it be better to create our content types to match our movie, tv and celebrity data schema (and all the relationships within those entities) and just use the drupal API for initial import and daily deltas or would it make more sense to keep the domain data in a traditional domain specific schema and write drupal modules to access that data?

答: If you have a big schema with lots of fields it's probably a better idea to use the Entity API Drupal 7 provides instead of using content types. That way you'd be able to use your domain specific schema which should speed things up. I have been using it for a while on a lot of data and it sounds exactly like what you need.</p>


问:
How to reference Data in an Array/Hash from JSON Response in Perl
I'm writing some Perl Code and I am a totally noob (specialized in PHP and JS). I'm retrieving some data from a JSON API Request and I want to reference the data and build some HTML-Options for a select field. But I just can't figure out how to reference the values from the JSON Response.

#!/bin/false

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;
use JSON;
use Encode;

use vars qw(@parameters $new $mode $metainfo);

use Data::Dumper qw(Dumper);

sub main
{
    if ($mode ne 'EDIT') {
        return;
    }

    my @pagetypes = _getPagetypes();
    if (scalar @pagetypes == 0 || ! defined \@pagetypes) {
        return "";
    }

    my $html = "";

    foreach (@pagetypes) {
        my $pagetype = $_;

        return Dumper @pagetypes;

        $html .= sprintf(
            '<option value="%s">%s</option>',
            $pagetype->{"identifier"},
            encode_utf8($pagetype->{"label"}),
        );
    }

    return $html;
}

##
# Get Pagetypes from API
##
sub _getPagetypes
{
    my $url = sprintf(
        "%s/page-types/",
        $ENV{'URL'}
    );

    my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 1 });
    my $header = HTTP::Request->new(GET => $url);
    my $request = HTTP::Request->new('GET', $url, $header);
    my $response = $ua->request($request);

    my @data = decode_json($response->content);
    my @pagetypes = @data[0]->{'pageTypes'};

    return @pagetypes;
}
```

<p>Where it says <code>return Dumper $pagetypes;</code> the following output is written:</p>

```$VAR1 = [
    {
        'label' => 'Projektsteckbrief',
        'identifier' => 'pagetype-profile'
    }
];
```

<p>I tried <code>$pagetype->{"label"}</code> and <code>$pagetypes[0]->{"label"}</code> and so much more...but I just don't know how to get the label and the identifier there.</p>

<p><strong>update:</strong></p>

<p>I tried to implement the pagetypes manually and this is working fine with the <code>main()</code> method (without the Dumper Call):</p>

<pre class="lang-perl prettyprint-override"><code>sub _getPagetypes
{
    my @pagetypes = (
        {
            identifier => "pagetype-profile",
            label => "Projektsteckbrief",
        },
    );

    return @pagetypes;
}
</code>```

UPDATE 2:

So I got a new problem...it's not working completely yet, but Bl00D4NGEL's response was a great help anyway!

So my code looks like this right now:

#!/bin/false

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;
use JSON;
use Encode;
use Project::Util::Api;

use vars qw(@parameters $new $mode $metainfo);

sub main
{
    if ($mode ne 'EDIT') {
        return;
    }

    my @pagetypes = _getPagetypes();
    if (scalar @pagetypes == 0 || ! defined \@pagetypes) {
        return "";
    }

    my $html = "";

    foreach my $pagetype (@pagetypes) {
        # selection will be automatically set by Imperia
        $html .= sprintf(
            '<option value="%s">%s</option>',
            $pagetype->[0]->{"identifier"},
            encode_utf8($pagetype->[0]->{"label"}),
        );
    }

    return $html;
}

##
# Get Pagetypes from API
##
sub _getPagetypes
{
    my $response = Project::Util::Api->sendRequest("/ajax/imperia/page-types/de/");
    my @pagetypes = $response->{"pageTypes"};

    return @pagetypes;
}

$new = main();
```

<p>The problem is now that only one item is displayed.
So <code>$pagetype</code> in my foreach loop looks like it's still the array with all of the items inside and <code>$pagetype->[0]</code> then gives me only the first item out of the array.</p>

<p>When I use <code>for</code> instead of <code>foreach</code> like this:</p>

<pre class="lang-perl prettyprint-override"><code>for ( $a = 0 ; $a <= 10 ; $a++ ) {
    $html .= sprintf(
        '<option value="%s">%s</option>',
        @pagetypes[0]->[$a]->{"id"},
        encode_utf8(@pagetypes[0]->[$a]->{"label"}),
    );
}
</code>```

I get 10 items of 200, but I just cant figure out how to get the length of the array @pagetypes.
I tried the following:

# 500 Server error (because of long loading?)
for ( $a = 0 ; $a <= @pagetypes[0] ; $a++ ) {

my $pagetypesLength = @pagetypes;
# Only 2 items are displayed
for ( $a = 0 ; $a <= @pagetypes ; $a++ ) {
for ( $a = 0 ; $a <= $pagetypesLength ; $a++ ) {
for ( $a = 0 ; $a <= scalar @pagetypes ; $a++ ) {
for ( $a = 0 ; $a <= length @pagetypes ; $a++ ) {
```

<p><strong>UPDATE 3 (FINALLY WORKING)</strong>:</p>

<p>So finally I managed to get it working. Final code following:</p>

<pre class="lang-perl prettyprint-override"><code>#!/bin/false

use strict;
use warnings;

use Encode;
use Project::Util::Api;

use vars qw(@parameters $new $mode $metainfo);

sub main
{
    if ($mode ne 'EDIT') {
        return;
    }

    my $items = _getData();
    if (0 == scalar @$items) {
        return "";
    }

    my $html = "";

    # $#{$items} is last index of array reference $items
    for (my $i = 0 ; $i <= $#{$items} ; $i++) {
        if (defined $items->[$i]->{"id"}) {
            # option selection will be automatically set by Imperia
            $html .= sprintf(
                '<option value="%s">%s</option>',
                $items->[$i]->{"identifier"},
                encode_utf8($items->[$i]->{"label"}),
            );
        }
    }

    return $html;
}

##
# Get Pagetypes from API
##
sub _getData
{
    my $response = Project::Util::Api->sendRequest("/ajax/imperia/page-types/de/");

    return $response->{"pageTypes"};
}

$new = main();

</code>```

答:
It looks like the $pagetype variable is actually an array ref (looking at the Dumper at least it looks like it)
So what should probably solve this issue is this:</p>

```<code>    my $pagetype = $_;

    $html .= sprintf(

    '<option value="%s">%s</option>',
    $pagetype->[0]->{"identifier"},
    encode_utf8($pagetype->{"label"}),

    );

</code>```

Body:
I'm writing some Perl Code and I am a totally noob (specialized in PHP and JS). I'm retrieving some data from a JSON API Request and I want to reference the data and build some HTML-Options for a select field. But I just can't figure out how to reference the values from the JSON Response.

#!/bin/false

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;
use JSON;
use Encode;

use vars qw(@parameters $new $mode $metainfo);

use Data::Dumper qw(Dumper);

sub main
{
    if ($mode ne 'EDIT') {
        return;
    }

    my @pagetypes = _getPagetypes();
    if (scalar @pagetypes == 0 || ! defined \@pagetypes) {
        return "";
    }

    my $html = "";

    foreach (@pagetypes) {
        my $pagetype = $_;

        return Dumper @pagetypes;

        $html .= sprintf(
            '<option value="%s">%s</option>',
            $pagetype->{"identifier"},
            encode_utf8($pagetype->{"label"}),
        );
    }

    return $html;
}

##
# Get Pagetypes from API
##
sub _getPagetypes
{
    my $url = sprintf(
        "%s/page-types/",
        $ENV{'URL'}
    );

    my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 1 });
    my $header = HTTP::Request->new(GET => $url);
    my $request = HTTP::Request->new('GET', $url, $header);
    my $response = $ua->request($request);

    my @data = decode_json($response->content);
    my @pagetypes = @data[0]->{'pageTypes'};

    return @pagetypes;
}

Where it says return Dumper $pagetypes; the following output is written:

$VAR1 = [
    {
        'label' => 'Projektsteckbrief',
        'identifier' => 'pagetype-profile'
    }
];

I tried $pagetype->{"label"} and $pagetypes[0]->{"label"} and so much more...but I just don't know how to get the label and the identifier there.

update:

I tried to implement the pagetypes manually and this is working fine with the main() method (without the Dumper Call):

sub _getPagetypes
{
    my @pagetypes = (
        {
            identifier => "pagetype-profile",
            label => "Projektsteckbrief",
        },
    );

    return @pagetypes;
}

UPDATE 2:

So I got a new problem...it's not working completely yet, but Bl00D4NGEL's response was a great help anyway!

So my code looks like this right now:

#!/bin/false

use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request;
use JSON;
use Encode;
use Project::Util::Api;

use vars qw(@parameters $new $mode $metainfo);

sub main
{
    if ($mode ne 'EDIT') {
        return;
    }

    my @pagetypes = _getPagetypes();
    if (scalar @pagetypes == 0 || ! defined \@pagetypes) {
        return "";
    }

    my $html = "";

    foreach my $pagetype (@pagetypes) {
        # selection will be automatically set by Imperia
        $html .= sprintf(
            '<option value="%s">%s</option>',
            $pagetype->[0]->{"identifier"},
            encode_utf8($pagetype->[0]->{"label"}),
        );
    }

    return $html;
}

##
# Get Pagetypes from API
##
sub _getPagetypes
{
    my $response = Project::Util::Api->sendRequest("/ajax/imperia/page-types/de/");
    my @pagetypes = $response->{"pageTypes"};

    return @pagetypes;
}

$new = main();

The problem is now that only one item is displayed.
So $pagetype in my foreach loop looks like it's still the array with all of the items inside and $pagetype->[0] then gives me only the first item out of the array.

When I use for instead of foreach like this:

for ( $a = 0 ; $a <= 10 ; $a++ ) {
    $html .= sprintf(
        '<option value="%s">%s</option>',
        @pagetypes[0]->[$a]->{"id"},
        encode_utf8(@pagetypes[0]->[$a]->{"label"}),
    );
}

I get 10 items of 200, but I just cant figure out how to get the length of the array @pagetypes.
I tried the following:

# 500 Server error (because of long loading?)
for ( $a = 0 ; $a <= @pagetypes[0] ; $a++ ) {

my $pagetypesLength = @pagetypes;
# Only 2 items are displayed
for ( $a = 0 ; $a <= @pagetypes ; $a++ ) {
for ( $a = 0 ; $a <= $pagetypesLength ; $a++ ) {
for ( $a = 0 ; $a <= scalar @pagetypes ; $a++ ) {
for ( $a = 0 ; $a <= length @pagetypes ; $a++ ) {

UPDATE 3 (FINALLY WORKING):

So finally I managed to get it working. Final code following:

#!/bin/false

use strict;
use warnings;

use Encode;
use Project::Util::Api;

use vars qw(@parameters $new $mode $metainfo);

sub main
{
    if ($mode ne 'EDIT') {
        return;
    }

    my $items = _getData();
    if (0 == scalar @$items) {
        return "";
    }

    my $html = "";

    # $#{$items} is last index of array reference $items
    for (my $i = 0 ; $i <= $#{$items} ; $i++) {
        if (defined $items->[$i]->{"id"}) {
            # option selection will be automatically set by Imperia
            $html .= sprintf(
                '<option value="%s">%s</option>',
                $items->[$i]->{"identifier"},
                encode_utf8($items->[$i]->{"label"}),
            );
        }
    }

    return $html;
}

##
# Get Pagetypes from API
##
sub _getData
{
    my $response = Project::Util::Api->sendRequest("/ajax/imperia/page-types/de/");

    return $response->{"pageTypes"};
}

$new = main();

Body:
It looks like the $pagetype variable is actually an array ref (looking at the Dumper at least it looks like it)
So what should probably solve this issue is this:

    my $pagetype = $_;

    $html .= sprintf(

    '<option value="%s">%s</option>',
    $pagetype->[0]->{"identifier"},
    encode_utf8($pagetype->{"label"}),

    );


问:
How to debug a problem with GET Express Router
I develop a game with a MEAN stack, so I need to create the API with Node & MongoDB to store scores and using this API in a Angular client.

The database is OK and I can add a score with POST but now I try to query the database with the API and the GET method not working.

I try to create a simple response (route /) but the response is the Angular client (index.html) in Postman, the POST work but the GET not !

```<code>classRouter.post('/add', (req, res) => {
  // Check request body
  if (typeof req.body === 'undefined' || req.body === null) {
    sendBodyError(res, Vocabulary.errors.noBody)
  };
  // Check fields in the body
  const {
    miss,
    extra,
    ok
  } = checkFields(Mandatory.game, req.body);

  //=> Error: bad fields provided
  if (!ok) {
    sendFieldsError(res, Vocabulary.errors.badFields, miss, extra)
  }
  else {
    //=> Request is valid: use controller
    createScore(req.body)
      .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
      .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse))
  };
});

// Route for all score
classRouter.get('/all', (req, res) => {
  getAllScores()
    .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
    .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse))
});

classRouter.get('/', function(req, res) {
  res.send('GET request to the homepage');
});
</code>```

```<code>const createScore = body => {
  return new Promise((resolve, reject) => {
    // Register new user
    ScoreModel.create(body)
      .then(mongoResponse => resolve(mongoResponse))
      .catch(mongoResponse => reject(mongoResponse))
  });
};

// Get all scores from the database
const getAllScores = () => {
  return new Promise((resolve, reject) => {
    ScoreModel.find((error, item) => {
      // Request error
      if (error) {
        return reject(error)
      } else {
        return resolve(item)
      };
    });
  });
};
</code>```

If someone can help me ?

Thanks

答:
You need to use debug package for debugging purposes.

First of all you need to log apiResponse within then() to make sure that the function getAllScores returns what you really expected.

But it appears, however, your problem doesn't related to these things.
You need to put a return before function getAllScores.

```<code>classRouter.get( '/all', (req, res) => {
    return getAllScores()
        .then( apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse) )
        .catch( apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse))
});
</code>```

Body:
I develop a game with a MEAN stack, so I need to create the API with Node & MongoDB to store scores and using this API in a Angular client.

The database is OK and I can add a score with POST but now I try to query the database with the API and the GET method not working.

I try to create a simple response (route /) but the response is the Angular client (index.html) in Postman, the POST work but the GET not !

classRouter.post('/add', (req, res) => {
  // Check request body
  if (typeof req.body === 'undefined' || req.body === null) {
    sendBodyError(res, Vocabulary.errors.noBody)
  };
  // Check fields in the body
  const {
    miss,
    extra,
    ok
  } = checkFields(Mandatory.game, req.body);

  //=> Error: bad fields provided
  if (!ok) {
    sendFieldsError(res, Vocabulary.errors.badFields, miss, extra)
  }
  else {
    //=> Request is valid: use controller
    createScore(req.body)
      .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
      .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse))
  };
});

// Route for all score
classRouter.get('/all', (req, res) => {
  getAllScores()
    .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
    .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse))
});

classRouter.get('/', function(req, res) {
  res.send('GET request to the homepage');
});

const createScore = body => {
  return new Promise((resolve, reject) => {
    // Register new user
    ScoreModel.create(body)
      .then(mongoResponse => resolve(mongoResponse))
      .catch(mongoResponse => reject(mongoResponse))
  });
};

// Get all scores from the database
const getAllScores = () => {
  return new Promise((resolve, reject) => {
    ScoreModel.find((error, item) => {
      // Request error
      if (error) {
        return reject(error)
      } else {
        return resolve(item)
      };
    });
  });
};

If someone can help me ?

Thanks

Body:
You need to use debug package for debugging purposes.

First of all you need to log apiResponse within then() to make sure that the function getAllScores returns what you really expected.

But it appears, however, your problem doesn't related to these things.
You need to put a return before function getAllScores.

classRouter.get( '/all', (req, res) => {
    return getAllScores()
        .then( apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse) )
        .catch( apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse))
});


问:
Why print_r() still exists?
```<code>print_r(array('name'=> 'bob', 'age' => 20, 'sex' => 'man'));
</code>```

Then :

```<code>Array {
    [name] => bob,
    [age] => 20,
    [sex] => man }

var_dump(array('name' => 'bob', 'age' => 20));
</code>```

will display:

```<code>array(2) {
    ['name'] => string(3) 'bob'
    ['age'] => int(20) }
</code>```

var_dump is perfect to debug  and  much better than print_r. But why print_r still exists? or print_r has some advantage i don't know

答:
A big difference between print_r and var_dump is that print_r takes an optional second argument, which allows you to the store the contents in a variable. For example:

```<code>$debug = print_r($someArray, true);
echo $debug;
</code>```

(Note that this could also be achieved for var_dump using output control functions, though)

Additionally, the readability of print_r is far better than that of var_dump:

var_dump:

```<code>array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}
</code>```

print_r:

```<code>Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</code>```

Title: Why print_r() still exists?

Body:
print_r(array('name'=> 'bob', 'age' => 20, 'sex' => 'man'));

Then :

Array {
    [name] => bob,
    [age] => 20,
    [sex] => man }

var_dump(array('name' => 'bob', 'age' => 20));

will display:

array(2) {
    ['name'] => string(3) 'bob'
    ['age'] => int(20) }

var_dump is perfect to debug  and  much better than print_r. But why print_r still exists? or print_r has some advantage i don't know

Body:
A big difference between print_r and var_dump is that print_r takes an optional second argument, which allows you to the store the contents in a variable. For example:

$debug = print_r($someArray, true);
echo $debug;

(Note that this could also be achieved for var_dump using output control functions, though)

Additionally, the readability of print_r is far better than that of var_dump:

var_dump:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

print_r:

Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)


问:
Return Value From DispatchQueue.MainQueue.DispatchAsync
We have a function that returns NSAttributedString
We want to instantiate the attributedString on the main thread
like this:

DispatchQueue.MainQueue.DispatchAsync(() =>
                {
                    NSAttributedString attributedString = new NSAttributedString(myHtmlData, options, out dict, ref error);
                });
```

How can we return the attributedString after the dispatch async finishes

答:
You can use the following code snippet</p>

```<code>var attributedString= await GetAttributedStringAsync();

        public Task<NSAttributedString> GetAttributedStringAsync()
        {
            var tcs = new TaskCompletionSource<NSAttributedString>();
            DispatchQueue.MainQueue.DispatchAsync(() =>
            {
                tcs.SetResult(new NSAttributedString(myHtmlData, options, out dict, ref error););
            });

            return tcs.Task;
        }
</code>```

Body:
We have a function that returns NSAttributedString
We want to instantiate the attributedString on the main thread
like this:

DispatchQueue.MainQueue.DispatchAsync(() =>
                {
                    NSAttributedString attributedString = new NSAttributedString(myHtmlData, options, out dict, ref error);
                });

How can we return the attributedString after the dispatch async finishes

Body:
You can use the following code snippet

var attributedString= await GetAttributedStringAsync();

        public Task<NSAttributedString> GetAttributedStringAsync()
        {
            var tcs = new TaskCompletionSource<NSAttributedString>();
            DispatchQueue.MainQueue.DispatchAsync(() =>
            {
                tcs.SetResult(new NSAttributedString(myHtmlData, options, out dict, ref error););
            });

            return tcs.Task;
        }


问:
SQLNative query returning empty results
I'm trying to execute a query which needs 4 tables :

```<code>    @Query(value="SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode "
            + "and sd.id_synop_decode = sy.id_synop" + " and DATE(sy.date)= :date and "
                    + "sy.id_station = st.id_station and st.id_station= :stationId", nativeQuery=true)
    public List<Erreur> recherche(@Param("date") Date date, @Param("stationId") Long stationId);
</code>```

This query works fine et native sql, i pass an existing stationId and  a date like the following :

```<code>SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode and sd.id_synop_decode = sy.id_synop
            and DATE(sy.date)= '2019-05-27' and sy.id_station = st.id_station and st.id_station= 60355;
</code>```

This query works fine in Mysql Workbench.

Here's the actual controller i'm using for testing purpose :

```<code>@GetMapping("/station/{stationId}/erreurs/today")
    public List<Erreur> getTodayErreurByStationId(@PathVariable Long stationId)
    {
        List<Erreur> erreurs = new ArrayList<Erreur>();
        Optional<Station> stationOptional = stationRepository.findById(stationId);
        if(stationOptional.isPresent())
        {
            return erreurRepository.recherche(new Date(), stationId);
        }
        return null;
    }
</code>```

The expected results are the actual "Ererur" objects in my array list, but RestClient just returns an empty array [], while the query works just fine in mysql like i described it above.

So my question is : How can i write this query into Hql language so that i can return the right entities. Or how can i map my sql results to my target custom calss "Erreur"?

```<code>@Entity
@Getter @Setter @NoArgsConstructor
@Table(name="erreur")
public class Erreur {

    public Erreur(int section, int groupe, String info) {
        this.section = section;
        this.groupe = groupe;
        this.info = info;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_erreur")
    private Long id;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
    fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_synop")
    private SynopDecode synopDecode;

    @OneToOne
    @JoinColumn(name="id_controle")
    private Controle controle;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
            fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_station")
    private Station station;

    @Column(name="section")
    private int section;

    @Column(name="groupe")
    private int groupe;

    @Column(name="info")
    private String info;
}
</code>```

答:
You can use jpa methods by conventions.

Assuming SynopDecode has property like:

//SynopDecode class

@ManyToOne
private Synop synop;
```

<pre class="lang-java prettyprint-override"><code>//repository interface

List<Erreur> findByStationIdAndSynopDecodeSynopDate(Long stationId, Date date);
//or
//List<Erreur> findByStationIdAndSynopDecode_Synop_Date(Long stationId, Date date);
</code>```

UPDATE

As Punit Tiwan (@punit-tiwan) note that, the above methods used for a specific datettime.

You can use methods below for just DATE.

//repository interface

List<Erreur> findByStationIdAndSynopDecodeSynopDateBetween(Long stationId, Date startOfDate, Date endOfDate);
//or
//List<Erreur> findByStationIdAndSynopDecode_Synop_DateBetween(Long stationId, Date startOfDate, Date endOfDate);
```

Title: SQLNative query returning empty results

Body:
I'm trying to execute a query which needs 4 tables :

    @Query(value="SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode "
            + "and sd.id_synop_decode = sy.id_synop" + " and DATE(sy.date)= :date and "
                    + "sy.id_station = st.id_station and st.id_station= :stationId", nativeQuery=true)
    public List<Erreur> recherche(@Param("date") Date date, @Param("stationId") Long stationId);

This query works fine et native sql, i pass an existing stationId and  a date like the following :

SELECT e.* FROM erreur e, synop sy, synop_decode sd, station st WHERE e.id_synop = sd.id_synop_decode and sd.id_synop_decode = sy.id_synop
            and DATE(sy.date)= '2019-05-27' and sy.id_station = st.id_station and st.id_station= 60355;

This query works fine in Mysql Workbench.

Here's the actual controller i'm using for testing purpose :

@GetMapping("/station/{stationId}/erreurs/today")
    public List<Erreur> getTodayErreurByStationId(@PathVariable Long stationId)
    {
        List<Erreur> erreurs = new ArrayList<Erreur>();
        Optional<Station> stationOptional = stationRepository.findById(stationId);
        if(stationOptional.isPresent())
        {
            return erreurRepository.recherche(new Date(), stationId);
        }
        return null;
    }

The expected results are the actual "Ererur" objects in my array list, but RestClient just returns an empty array [], while the query works just fine in mysql like i described it above.

So my question is : How can i write this query into Hql language so that i can return the right entities. Or how can i map my sql results to my target custom calss "Erreur"?

@Entity
@Getter @Setter @NoArgsConstructor
@Table(name="erreur")
public class Erreur {

    public Erreur(int section, int groupe, String info) {
        this.section = section;
        this.groupe = groupe;
        this.info = info;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_erreur")
    private Long id;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
    fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_synop")
    private SynopDecode synopDecode;

    @OneToOne
    @JoinColumn(name="id_controle")
    private Controle controle;

    @ManyToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH},
            fetch=FetchType.LAZY)
    @JsonIgnore
    @JoinColumn(name="id_station")
    private Station station;

    @Column(name="section")
    private int section;

    @Column(name="groupe")
    private int groupe;

    @Column(name="info")
    private String info;
}

Body:
You can use jpa methods by conventions.

Assuming SynopDecode has property like:

//SynopDecode class

@ManyToOne
private Synop synop;

//repository interface

List<Erreur> findByStationIdAndSynopDecodeSynopDate(Long stationId, Date date);
//or
//List<Erreur> findByStationIdAndSynopDecode_Synop_Date(Long stationId, Date date);

UPDATE

As Punit Tiwan (@punit-tiwan) note that, the above methods used for a specific datettime.

You can use methods below for just DATE.

//repository interface

List<Erreur> findByStationIdAndSynopDecodeSynopDateBetween(Long stationId, Date startOfDate, Date endOfDate);
//or
//List<Erreur> findByStationIdAndSynopDecode_Synop_DateBetween(Long stationId, Date startOfDate, Date endOfDate);


问:
Hide one of the checkbox group choices but stiil keep its functionallity activated
I have a basic shiny app below with a checkbox group and the printed results of it. I was wondering if it is possible to somehow hide one of the 3 choices (for example "1") but the printed result should still include "1".</p>

```<code>#ui.r
fluidPage(

  # Copy the chunk below to make a group of checkboxes
  checkboxGroupInput("checkGroup", label = h3("Checkbox group"),
    choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3),
    selected = 1),

  hr(),
  fluidRow(column(3, verbatimTextOutput("value")))

)
#server.r
function(input, output) {

  # You can access the values of the widget (as a vector)
  # with input$checkGroup, e.g.
  output$value <- renderPrint({ input$checkGroup })

}
</code>```

答:
It isn't a checkboxGroupInput, but it mimics the idea...

```<code>library(shiny)

ui <- fluidPage(

  # Copy the chunk below to make a group of checkboxes
  checkboxGroupInput("checkGroup", label = h3("Checkbox group"),
                     choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3),
                     selected = 1),
  hr(),
  conditionalPanel(
    "input.check1 == 'T'",
    checkboxInput("check1", "Choice 1", value = T)
  ),
  checkboxInput("check2", "Choice 2", value = F),
  checkboxInput("check3", "Choice 3", value = F),
  hr(),
  fluidRow(column(3, verbatimTextOutput("value"))),
  fluidRow(column(3, verbatimTextOutput("value2")))

)

server <- function(input, output) {

  # You can access the values of the widget (as a vector)
  # with input$checkGroup, e.g.
  output$value <- renderPrint({ input$checkGroup })
  output$value2 <- renderPrint({ c(input$check1, input$check2, input$check3)})

}

shinyApp(ui, server)
</code>```

Body:
I have a basic shiny app below with a checkbox group and the printed results of it. I was wondering if it is possible to somehow hide one of the 3 choices (for example "1") but the printed result should still include "1".

#ui.r
fluidPage(

  # Copy the chunk below to make a group of checkboxes
  checkboxGroupInput("checkGroup", label = h3("Checkbox group"),
    choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3),
    selected = 1),

  hr(),
  fluidRow(column(3, verbatimTextOutput("value")))

)
#server.r
function(input, output) {

  # You can access the values of the widget (as a vector)
  # with input$checkGroup, e.g.
  output$value <- renderPrint({ input$checkGroup })

}

Body:
It isn't a checkboxGroupInput, but it mimics the idea...

library(shiny)

ui <- fluidPage(

  # Copy the chunk below to make a group of checkboxes
  checkboxGroupInput("checkGroup", label = h3("Checkbox group"),
                     choices = list("Choice 1" = 1, "Choice 2" = 2, "Choice 3" = 3),
                     selected = 1),
  hr(),
  conditionalPanel(
    "input.check1 == 'T'",
    checkboxInput("check1", "Choice 1", value = T)
  ),
  checkboxInput("check2", "Choice 2", value = F),
  checkboxInput("check3", "Choice 3", value = F),
  hr(),
  fluidRow(column(3, verbatimTextOutput("value"))),
  fluidRow(column(3, verbatimTextOutput("value2")))

)

server <- function(input, output) {

  # You can access the values of the widget (as a vector)
  # with input$checkGroup, e.g.
  output$value <- renderPrint({ input$checkGroup })
  output$value2 <- renderPrint({ c(input$check1, input$check2, input$check3)})

}

shinyApp(ui, server)


问:
Private method returned as string
I'm developing a simple jquery plugin and im having a difficulties setting up the method structure. Could someone please enlighten me. I am using the plugin structure as described in the official Jquery Authoring documentation.

The problem I am having is when calling the private function _generateID, the function actually returns the function text ( function() { return this.. ) instead of 'hi'.

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

    var methods = {
        init : function( options ) {
            return this.each(function() {

            });
        },

        _generateID : function() {
            return this.each(function() {
                return 'hi';
            });
        },

        create : function( options ) {
            return this.each(function() {
                var settings = {
                    'id' : methods._generateID,
                };
                if ( options ) { $.extend( settings, options ); }
                $('<div>', {
                    id : settings.id,
                }).appendTo(this);
            });
        },

        destroy : function( id ) {
            return this.each(function(){
                $(window).unbind('#'+id);
                $('#'+id).remove();
            });
        }
    };

    $.fn.workzone = function( method ) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.workzone' );
        }
    };

})( jQuery );
</code>```

答:
Where did you call the function? I only see:

```<code>var settings = {
   'id' : methods._generateID,
};
</code>```

Perhaps you meant:

```<code>var settings = {
   'id' : methods._generateID(),
};
</code>```

Function calls take the form return_value = function_name(arg_list);

Title: Private method returned as string

Body:
I'm developing a simple jquery plugin and im having a difficulties setting up the method structure. Could someone please enlighten me. I am using the plugin structure as described in the official Jquery Authoring documentation.

The problem I am having is when calling the private function _generateID, the function actually returns the function text ( function() { return this.. ) instead of 'hi'.

(function( $ ){

    var methods = {
        init : function( options ) {
            return this.each(function() {

            });
        },

        _generateID : function() {
            return this.each(function() {
                return 'hi';
            });
        },

        create : function( options ) {
            return this.each(function() {
                var settings = {
                    'id' : methods._generateID,
                };
                if ( options ) { $.extend( settings, options ); }
                $('
', {
                    id : settings.id,
                }).appendTo(this);
            });
        },

        destroy : function( id ) {
            return this.each(function(){
                $(window).unbind('#'+id);
                $('#'+id).remove();
            });
        }
    };

    $.fn.workzone = function( method ) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.workzone' );
        }
    };

})( jQuery );

Body:
Where did you call the function? I only see:

var settings = {
   'id' : methods._generateID,
};

Perhaps you meant:

var settings = {
   'id' : methods._generateID(),
};

Function calls take the form return_value = function_name(arg_list);


问:
Clicking on button shifts entire page a few pixels to the left
I'm trying to fix an issue where when a user clicks a button it causes the entire page to shift to the left. The issue only seems to appear when the browser is maximized.

You can try it yourself here: https://professionallyspeaking.oct.ca/exemplary.aspx

Click on the "Great Teachers- Alphabetical +" button to see the shift in action.

答:
Page was shifting due to appearance of the vertical scrollbar. Thanks to @j08691 for pointing this out. I resolved the issue by applying overflow-y: scroll to the html:</p>

```<code>html {
overflow-y: scroll;
}
</code>```

Body:
Page was shifting due to appearance of the vertical scrollbar. Thanks to @j08691 for pointing this out. I resolved the issue by applying overflow-y: scroll to the html:

html {
overflow-y: scroll;
}


问:
Trouble loading array safely in my angular html template
I have an array that is populated after a .subscribe to my API. Console shows it populated as expected. Accessing an element of the array results to an error thrown because of it being undefined

```<code><div *ngIf="!invoices || invoices.length === 0">
       No invoices
</div>
<div *ngIf="invoices || async ">
      {{ invoices[0]?.invoice_id || async}}
</div>
</code>```

If I remove the elvis operator my content will load fine however the console will throw errors InvoicesComponent.html:10 ERROR TypeError: Cannot read property 'invoice_id' of undefined until the array gets populated from the subscribe function.

The invoices array is initialised in my service

```<code> invoices: Array<Invoice> = [];
</code>```

And I populate the array

```<code>getInvoices(){
   var _invoices = this.invoices;
   if(this.afAuth.user){
      // users/uid/invoices/invoice_id/
      var userRef = this.afs.doc(`users/${this.afAuth.auth.currentUser.uid}`)

 userRef.collection('invoices').get().subscribe(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
        _invoices.push({
          'invoice_id': doc.id,
          'customer_company': doc.data().customer_company,
          'year_id':doc.data().year_id,
          'date_created': doc.data().date_created,
          'date_modified': doc.data().date_modified})
    });
    console.log(_invoices)
});
return _invoices
}
</code>```

Based on the suggestion of trichetriche, an `Invoice class was created

```<code>import { QueryDocumentSnapshot } from  "@angular/fire/firestore";
import { of } from 'rxjs'

export class Invoice {
    invoice_id: string;
    customer_company: string;
    date_created: string;
    date_modified: string;
    year_id: string;

constructor(invoiceDoc: QueryDocumentSnapshot<any>){
    this.invoice_id = invoiceDoc.id
    this.customer_company = invoiceDoc.data().customer_company
    this.date_created = invoiceDoc.data().date_created
    this.date_modified = invoiceDoc.data().date_modified
    this.year_id = invoiceDoc.data().year_id
}

    toObservable(){
        return of(this)
    }
}
</code>```

答:
Right so after some research it seems that I was better off subscribing to an observable and dealing with the data as it arrives from my API with the async pipe.

So my final functions look kind of like this:

ngOnInit() {
    this.observableInvoices = this.auth.getObservableInvoices().pipe(map(
      (data) => data));
    console.log(this.observableInvoices)
    }
```

<pre class="lang-html prettyprint-override"><code><li *ngFor="let invoice of observableInvoices | async; index as i">
</code>```

  getObservableInvoices(): Observable<any> {
    this.observable_invoices = this.afs
      .collection(`users/${this.afAuth.auth.currentUser.uid}/invoices`)
      .valueChanges() as Observable<any[]>;
    return this.observable_invoices;
  }
```

Body:
I have an array that is populated after a .subscribe to my API. Console shows it populated as expected. Accessing an element of the array results to an error thrown because of it being undefined

       No invoices

      {{ invoices[0]?.invoice_id || async}}

If I remove the elvis operator my content will load fine however the console will throw errors InvoicesComponent.html:10 ERROR TypeError: Cannot read property 'invoice_id' of undefined until the array gets populated from the subscribe function.

The invoices array is initialised in my service

 invoices: Array<Invoice> = [];

And I populate the array

getInvoices(){
   var _invoices = this.invoices;
   if(this.afAuth.user){
      // users/uid/invoices/invoice_id/
      var userRef = this.afs.doc(`users/${this.afAuth.auth.currentUser.uid}`)

 userRef.collection('invoices').get().subscribe(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
        _invoices.push({
          'invoice_id': doc.id,
          'customer_company': doc.data().customer_company,
          'year_id':doc.data().year_id,
          'date_created': doc.data().date_created,
          'date_modified': doc.data().date_modified})
    });
    console.log(_invoices)
});
return _invoices
}

Based on the suggestion of trichetriche, an `Invoice class was created

import { QueryDocumentSnapshot } from  "@angular/fire/firestore";
import { of } from 'rxjs'

export class Invoice {
    invoice_id: string;
    customer_company: string;
    date_created: string;
    date_modified: string;
    year_id: string;

constructor(invoiceDoc: QueryDocumentSnapshot<any>){
    this.invoice_id = invoiceDoc.id
    this.customer_company = invoiceDoc.data().customer_company
    this.date_created = invoiceDoc.data().date_created
    this.date_modified = invoiceDoc.data().date_modified
    this.year_id = invoiceDoc.data().year_id
}

    toObservable(){
        return of(this)
    }
}

Body:
Right so after some research it seems that I was better off subscribing to an observable and dealing with the data as it arrives from my API with the async pipe.

So my final functions look kind of like this:

ngOnInit() {
    this.observableInvoices = this.auth.getObservableInvoices().pipe(map(
      (data) => data));
    console.log(this.observableInvoices)
    }

<li *ngFor="let invoice of observableInvoices | async; index as i">

  getObservableInvoices(): Observable<any> {
    this.observable_invoices = this.afs
      .collection(`users/${this.afAuth.auth.currentUser.uid}/invoices`)
      .valueChanges() as Observable<any[]>;
    return this.observable_invoices;
  }