问:
Django Post request for many to many field ValueError
I am working on a post request in which the user chooses from a list of tags and makes combinations of tags. The combination of tags should then be posted. Nothing should get changed in the Tag table.

These are the models:

models.py

```<code>class Tag(models.Model):
    name = models.CharField(max_length=256)
    language = models.CharField(max_length=256)

    objects = models.Manager()

    def __str__(self):
        """Return a human readable representation of the model instance."""
        return self.name or ''

    @property
    def tags(self):
        tags = self.tagging.values('tag')
        return tags.values('tag_id', 'tag__name', 'tag__language')

class Combination(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, null=True)
    resource = models.ForeignKey(Resource, on_delete=models.CASCADE, null=True)
    tag_id = models.ManyToManyField(Tag, null=True)
    created = models.DateTimeField(editable=False)
    score = models.PositiveIntegerField(default=0)

    objects = models.Manager()

    def __str__(self):
        return str(self.tag_id) or ''
</code>```

This is the serializer for Combination.

serializers.py

```<code>class CombinationSerializer(serializers.ModelSerializer):
  tag_id = TagWithIdSerializer(many=True, required=False, write_only=False)
  resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
                                                   required=True,
                                                   source='resource',
                                                   write_only=False)
  gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
                                                    required=False,
                                                    source='gameround',
                                                    write_only=False)
  user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
                                               required=False,
                                               source='user',
                                               write_only=False)

  class Meta:
    model = Combination
    depth = 1
    fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')

  def create(self, validated_data):
    user = None
    request = self.context.get("request")
    if request and hasattr(request, "user"):
      user = request.user

    score = 0

    tag_data = validated_data.pop('tag_id', None)

    combination = Combination(
      user=user,
      gameround=validated_data.get("gameround"),
      resource=validated_data.get("resource"),
      created=datetime.now(),
      score=score
    )
    combination.save()
    for tag_object in tag_data[0]:
      combination.tag_id.add(tag_object)
    return combination

  def to_representation(self, instance):
    rep = super().to_representation(instance)
    rep['tag_id'] = TagWithIdSerializer(instance.tag_id.all(), many=True).data
    return rep

</code>```

I have tried posting the following JSON object to the database:

```<code>{
        "gameround_id": 2015685170,
        "resource_id": 327888,
        "tag_id": [{"id": 2014077506, "name": "corwn","language": "en"}]
}
</code>```

I am getting a ValueError: Field 'id' expected a number but got 'name'.

How can I fix this issue?

答:
you need to provide tag id for each tag not all tag data,

Try like this

```<code>{
            "gameround_id": 2015685170,
            "resource_id": 327888,
            "tag_id": [2014077506,2014077507]
    }
</code>```

Body:
I am working on a post request in which the user chooses from a list of tags and makes combinations of tags. The combination of tags should then be posted. Nothing should get changed in the Tag table.

These are the models:

models.py

class Tag(models.Model):
    name = models.CharField(max_length=256)
    language = models.CharField(max_length=256)

    objects = models.Manager()

    def __str__(self):
        """Return a human readable representation of the model instance."""
        return self.name or ''

    @property
    def tags(self):
        tags = self.tagging.values('tag')
        return tags.values('tag_id', 'tag__name', 'tag__language')

class Combination(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
    gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, null=True)
    resource = models.ForeignKey(Resource, on_delete=models.CASCADE, null=True)
    tag_id = models.ManyToManyField(Tag, null=True)
    created = models.DateTimeField(editable=False)
    score = models.PositiveIntegerField(default=0)

    objects = models.Manager()

    def __str__(self):
        return str(self.tag_id) or ''

This is the serializer for Combination.

serializers.py

class CombinationSerializer(serializers.ModelSerializer):
  tag_id = TagWithIdSerializer(many=True, required=False, write_only=False)
  resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
                                                   required=True,
                                                   source='resource',
                                                   write_only=False)
  gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
                                                    required=False,
                                                    source='gameround',
                                                    write_only=False)
  user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
                                               required=False,
                                               source='user',
                                               write_only=False)

  class Meta:
    model = Combination
    depth = 1
    fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')

  def create(self, validated_data):
    user = None
    request = self.context.get("request")
    if request and hasattr(request, "user"):
      user = request.user

    score = 0

    tag_data = validated_data.pop('tag_id', None)

    combination = Combination(
      user=user,
      gameround=validated_data.get("gameround"),
      resource=validated_data.get("resource"),
      created=datetime.now(),
      score=score
    )
    combination.save()
    for tag_object in tag_data[0]:
      combination.tag_id.add(tag_object)
    return combination

  def to_representation(self, instance):
    rep = super().to_representation(instance)
    rep['tag_id'] = TagWithIdSerializer(instance.tag_id.all(), many=True).data
    return rep

I have tried posting the following JSON object to the database:

{
        "gameround_id": 2015685170,
        "resource_id": 327888,
        "tag_id": [{"id": 2014077506, "name": "corwn","language": "en"}]
}

I am getting a ValueError: Field 'id' expected a number but got 'name'.

How can I fix this issue?

Body:
you need to provide tag id for each tag not all tag data,

Try like this

{
            "gameround_id": 2015685170,
            "resource_id": 327888,
            "tag_id": [2014077506,2014077507]
    }


来源: stackexchange

问:
which is the best way to show a status message in asp.net
Which is the best way to show a status message in asp.net. For example, after saving data to DB I want to show a message like 'Data Saved Successfully". I would like to know which is the best way to show this kind of status message in asp.net.

Thanks All.

答:
On the success of your query, in code behind You can just add text to a lable like:

```<code>Label1.text = "Data Saved Successfully";
</code>```

Don't give and default text to that label in design page.

further more you can give color to that label like :

```<code>Label1.color = "green";
</code>```

SO that it will look like a Success Message.

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
On the success of your query, in code behind You can just add text to a lable like:

Label1.text = "Data Saved Successfully";

Don't give and default text to that label in design page.

further more you can give color to that label like :

Label1.color = "green";

SO that it will look like a Success Message.

Hope this helps.


问:
Jupyter doesn't load environment kernel
I'm trying to load kernel from conda environment and get following error when trying to do this:

```<code>`[I 22:10:35.989 NotebookApp] KernelRestarter: restarting kernel (5/5), new random ports
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel_launcher.py", line 15, in <module>
    from ipykernel import kernelapp as app
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel\__init__.py", line 2, in <module>
    from .connect import *
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel\connect.py", line 18, in <module>
    import jupyter_client
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\jupyter_client\__init__.py", line 4, in <module>
    from .connect import *
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\jupyter_client\connect.py", line 21, in <module>
    import zmq
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\__init__.py", line 50, in <module>
    from zmq import backend
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\__init__.py", line 40, in <module>
    reraise(*exc_info)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\utils\sixcerpt.py", line 34, in reraise
    raise value
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\__init__.py", line 27, in <module>
    _ns = select_backend(first)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\select.py", line 28, in select_backend
    mod = __import__(name, fromlist=public_api)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\cython\__init__.py", line 6, in <module>
    from . import (constants, error, message, context,
ImportError: DLL load failed: Не найден указанный модуль.
[W 22:10:39.032 NotebookApp] KernelRestarter: restart failed
[W 22:10:39.032 NotebookApp] Kernel 7695680a-c4cf-4408-a228-a36587c6acee died, removing from map.
[W 22:11:20.915 NotebookApp] Timeout waiting for kernel_info reply from 7695680a-c4cf-4408-a228-a36587c6acee
[E 22:11:20.917 NotebookApp] Error opening stream: HTTP 404: Not Found (Kernel does not exist: 7695680a-c4cf-4408-a228-a36587c6acee)
[W 22:11:21.949 NotebookApp] 404 GET /api/kernels/7695680a-c4cf-4408-a228-a36587c6acee/channels?session_id=a461c65a632c4842918b17939d5595f1 (::1): Kernel does not exist: 7695680a-c4cf-4408-a228-a36587c6acee
[W 22:11:21.963 NotebookApp] 404 GET /api/kernels/7695680a-c4cf-4408-a228-a36587c6acee/channels?session_id=a461c65a632c4842918b17939d5595f1 (::1) 16.000000ms referer=None
[W 22:11:23.987 NotebookApp] Replacing stale connection: 7695680a-c4cf-4408-a228-a36587c6acee:a461c65a632c4842918b17939d5595f1`
</code>```

The error is ImportError: DLL load failed: The specific module was not found.
I've tried to reinstall environment and jupyter and also tried to reinstall pyzmq with pip uninstall pyzmq and pip install pyzmq. I get no problem with running my default kernel.

答:
Short Answer

You might be able to get away with just:

python -m ipykernel install --user --name=my_env_name
```
<p><strong>Long Answer</strong></p>
<p>You can run <code>jupyter kernelspec list</code> to see your available kernels.</p>
<p>Depending on your operating system and how you installed Jupiter (user vs. system) you should be able to find your kernel definitions in of these directories:</p>
<ul>
<li>/usr/share/jupyter/kernels (Linux/Mac)</li>
<li>/usr/local/share/jupyter/kernels (Linux/Mac)</li>
<li>{sys.prefix}/share/jupyter/kernels (Linux/Mac)</li>
<li>~/.local/share/jupyter/kernels (Linux-user)</li>
<li>~/Library/Jupyter/kernels (Mac-user)</li>
<li>%APPDATA%\jupyter\kernels (Windows)</li>
<li>%PROGRAMDATA%\jupyter\kernels (Windows)</li>
</ul>
<p>The definitions look something like:</p>
```{
 "argv": ["python3", "-m", "IPython.kernel",
          "-f", "{connection_file}"],
 "display_name": "Python 3",
 "language": "python"
}
```

Your actual definition may look different so just copy whatever you have there and change the main arg so that it points to the particular python instance that you want to use and give it some "display_name" so you can recognise it in Jupyter.

In Jupyter whenever you create a new notebook you can select one of these kernels (you can also switch between them in an existing notebook).

So, check which kernel you are using, which kernels are defined in your spec, add the one you actually want to use if necessary and make sure you select the right one in the Jupyter UI. That should be it - good luck.

P.S. this is roughly what ipykernel install should do anyway.

ContentLicense: CC BY-SA 4.0

Title: Jupyter doesn't load environment kernel

Body:
I'm trying to load kernel from conda environment and get following error when trying to do this:

`[I 22:10:35.989 NotebookApp] KernelRestarter: restarting kernel (5/5), new random ports
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel_launcher.py", line 15, in <module>
    from ipykernel import kernelapp as app
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel\__init__.py", line 2, in <module>
    from .connect import *
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\ipykernel\connect.py", line 18, in <module>
    import jupyter_client
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\jupyter_client\__init__.py", line 4, in <module>
    from .connect import *
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\jupyter_client\connect.py", line 21, in <module>
    import zmq
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\__init__.py", line 50, in <module>
    from zmq import backend
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\__init__.py", line 40, in <module>
    reraise(*exc_info)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\utils\sixcerpt.py", line 34, in reraise
    raise value
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\__init__.py", line 27, in <module>
    _ns = select_backend(first)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\select.py", line 28, in select_backend
    mod = __import__(name, fromlist=public_api)
  File "C:\ProgramData\Anaconda3\envs\ImageAI\lib\site-packages\zmq\backend\cython\__init__.py", line 6, in <module>
    from . import (constants, error, message, context,
ImportError: DLL load failed: Не найден указанный модуль.
[W 22:10:39.032 NotebookApp] KernelRestarter: restart failed
[W 22:10:39.032 NotebookApp] Kernel 7695680a-c4cf-4408-a228-a36587c6acee died, removing from map.
[W 22:11:20.915 NotebookApp] Timeout waiting for kernel_info reply from 7695680a-c4cf-4408-a228-a36587c6acee
[E 22:11:20.917 NotebookApp] Error opening stream: HTTP 404: Not Found (Kernel does not exist: 7695680a-c4cf-4408-a228-a36587c6acee)
[W 22:11:21.949 NotebookApp] 404 GET /api/kernels/7695680a-c4cf-4408-a228-a36587c6acee/channels?session_id=a461c65a632c4842918b17939d5595f1 (::1): Kernel does not exist: 7695680a-c4cf-4408-a228-a36587c6acee
[W 22:11:21.963 NotebookApp] 404 GET /api/kernels/7695680a-c4cf-4408-a228-a36587c6acee/channels?session_id=a461c65a632c4842918b17939d5595f1 (::1) 16.000000ms referer=None
[W 22:11:23.987 NotebookApp] Replacing stale connection: 7695680a-c4cf-4408-a228-a36587c6acee:a461c65a632c4842918b17939d5595f1`

The error is ImportError: DLL load failed: The specific module was not found.
I've tried to reinstall environment and jupyter and also tried to reinstall pyzmq with pip uninstall pyzmq and pip install pyzmq. I get no problem with running my default kernel.

Body:
Short Answer

You might be able to get away with just:

python -m ipykernel install --user --name=my_env_name

Long Answer

You can run jupyter kernelspec list to see your available kernels.

Depending on your operating system and how you installed Jupiter (user vs. system) you should be able to find your kernel definitions in of these directories:

/usr/share/jupyter/kernels (Linux/Mac)

/usr/local/share/jupyter/kernels (Linux/Mac)

{sys.prefix}/share/jupyter/kernels (Linux/Mac)

~/.local/share/jupyter/kernels (Linux-user)

~/Library/Jupyter/kernels (Mac-user)

%APPDATA%\jupyter\kernels (Windows)

%PROGRAMDATA%\jupyter\kernels (Windows)

The definitions look something like:

{
 "argv": ["python3", "-m", "IPython.kernel",
          "-f", "{connection_file}"],
 "display_name": "Python 3",
 "language": "python"
}

Your actual definition may look different so just copy whatever you have there and change the main arg so that it points to the particular python instance that you want to use and give it some "display_name" so you can recognise it in Jupyter.

In Jupyter whenever you create a new notebook you can select one of these kernels (you can also switch between them in an existing notebook).

So, check which kernel you are using, which kernels are defined in your spec, add the one you actually want to use if necessary and make sure you select the right one in the Jupyter UI. That should be it - good luck.

P.S. this is roughly what ipykernel install should do anyway.


问:
VS code Remote Development problem with SSH connection (Windows to Linux)
I'm Currently trying to setup Remote developement environment with VS code.

I have installed Remote - SSH plugin and edited my .ssh/config file as below

Host ABC

```<code>User ubuntu

HostName xx.xx.xx.xx

IdentityFile ~/.ssh/filename
</code>```

It trowing an error by saying "An SSH Installation couldn't be found"

Local Machine - Windows
Host Machine - Ubuntu(Linux)

Please help on this matter

答:
Thanks for the help guys. Openssh was not present so had to install OpenSSH from Windows Powershell
https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse

Then copied the path of ssh.exe to VScode settings. Ex:
"remote.SSH.path": "C:\Program Files\OpenSSH-Win64\ssh.exe"
It worked perfectly.

Body:
I'm Currently trying to setup Remote developement environment with VS code.

I have installed Remote - SSH plugin and edited my .ssh/config file as below

Host ABC

User ubuntu

HostName xx.xx.xx.xx

IdentityFile ~/.ssh/filename

It trowing an error by saying "An SSH Installation couldn't be found"

Local Machine - Windows
Host Machine - Ubuntu(Linux)

Please help on this matter


问:
MySQL: Search for coincidences and differences in two tables
I need to find matchs between two tables, but also need to display when there is no match.

Table1: id, dni_number, name, business_id

Table2: id, dni, business_id

I need to form a table like this:

id
dni
name
business_id
is_match

1
12365478
John Doe
15451
1

1
22365478
Karen Doe
23451
0

is_match meaning 1: it found the dni in table1 and also in table2, 0 for not match

The query should have a where condition to find matchs from certain business_id

Any help will be much appreciated. Thanks in advance

答:
```<code>SELECT *, (table2.dnu = table1.dnu) AS is_match
FROM table1
   LEFT JOIN table2 ON table1.business_id = table2.business_id
WHERE table1.business_id = xxx;
</code>```


问:
Travis CI runs only on Pull Requests and in Expected for Branch
I have two builds at the same time when doing PR.

According to docs, that could be turned off via web interface

I turned that off (want to have only PR build) and also added only to .travis.yml, but still have two builds, but now branch builds just in expecting stage. In web UI Travis - no more builds for branch created.

```<code>branches:
  only:
  - master

language: python
os: linux
dist: xenial

jobs:
  include:
  - name: pytest
    python:
      - 3.7
    install:
      - pip install -U pip
      - pip install -U pytest
      - pip install -U PyYAML
      - pip install -U Cerberus
    script:
      - pytest -vvs
</code>```

答:
It seems like this was the issue

https://travis-ci.community/t/known-issue-travis-ci-reports-expected-waiting-for-status-to-be-reported-on-the-github-status-api-but-the-status-never-arrives/1154

Body:
I have two builds at the same time when doing PR.

According to docs, that could be turned off via web interface

I turned that off (want to have only PR build) and also added only to .travis.yml, but still have two builds, but now branch builds just in expecting stage. In web UI Travis - no more builds for branch created.

branches:
  only:
  - master

language: python
os: linux
dist: xenial

jobs:
  include:
  - name: pytest
    python:
      - 3.7
    install:
      - pip install -U pip
      - pip install -U pytest
      - pip install -U PyYAML
      - pip install -U Cerberus
    script:
      - pytest -vvs


问:
Check if third-party cookies are enabled
I have an application that needs to check whether the client browser has third-party-cookies enabled. Does anyone know how to do this in JavaScript?</p>

答:
Technical Background

The third party sets & reads cookies over HTTP (not in JavaScript).

So we need two requests to an external domain to test if third-party cookies are enabled:

One where the third party sets the cookie(s)

The second, with a differing response depending on whether the browser sent the cookie(s) back to the same third party in a second request.

We cannot use XMLHTTPRequest (Ajax) because of the DOM security model.

Obviously you can't load both scripts in parallel, or the second request may be made before the first request’s response makes it back, and the test cookie(s) will not have been set.

Code Example

Given:

The .html file is on one domain, and

The .js.php files are on a second domain, we have:

The HTML test page

Saved as third-party-cookies.html

```<code><!DOCTYPE html>
<html>
<head id="head">
  <meta charset=utf-8 />
  <title>Test if Third-Party Cookies are Enabled</title>
<style type="text/css">
body {
  color: black;
  background: white none;
}
.error {
  color: #c00;
}
.loading {
  color: #888;
}
.hidden {
  display: none;
}
</style>
<script type="text/javascript">
window._3rd_party_test_step1_loaded = function(){
  // At this point, a third-party domain has now attempted to set a cookie (if all went to plan!)
  var step2Url = 'http://third-party.example.com/step2.js.php',
    resultsEl = document.getElementById('3rd_party_cookie_test_results'),
    step2El = document.createElement('script');

  // Update loading / results message
  resultsEl.innerHTML = 'Stage one complete, loading stage 2…';
  // And load the second part of the test (reading the cookie)
  step2El.setAttribute('src', step2Url);
  resultsEl.appendChild(step2El);
}
window._3rd_party_test_step2_loaded = function(cookieSuccess){
  var resultsEl = document.getElementById('3rd_party_cookie_test_results'),
    errorEl = document.getElementById('3rd_party_cookie_test_error');
  // Show message
  resultsEl.innerHTML = (cookieSuccess ? 'Third party cookies are <b>functioning</b> in your browser.' : 'Third party cookies appear to be <b>disabled</b>.');

  // Done, so remove loading class
  resultsEl.className = resultsEl.className.replace(/\bloading\b/,' ');
  // And remove error message
  errorEl.className = 'hidden';
}
</script>
</head>
<body id="thebody">

  <h1>Test if Third-Party Cookies are Enabled</h1>

  <p id="3rd_party_cookie_test_results" class='loading'>Testing…</p>
  <p id="3rd_party_cookie_test_error" class="error hidden">(If this message persists, the test could not be completed; we could not reach the third-party to test, or another error occurred.)</p>

  <script type="text/javascript">
  window.setTimeout(function(){
    var errorEl = document.getElementById('3rd_party_cookie_test_error');
    if(errorEl.className.match(/\berror\b/)) {
      // Show error message
      errorEl.className = errorEl.className.replace(/\bhidden\b/,' ');
    } else {
    }
  }, 7*1000); // 7 sec timeout
  </script>
  <script type="text/javascript" src="http://third-party.example.com/step1.js.php"></script>
</body>
</html>
</code>```

The first third-party JavaScript file

Saved as step1.js.php

This is written in PHP so we can set cookies as the file loads. (It could, of course, be written in any language, or even done in server config files.)

```<code><?php
  header('Content-Type: application/javascript; charset=UTF-8');
  // Set test cookie
  setcookie('third_party_c_t', 'hey there!', time() + 3600*24*2);
?>
window._3rd_party_test_step1_loaded();
</code>```

The second third-party JavaScript file

Saved as step2.js.php

This is written in PHP so we can read cookies, server-side, before we respond. We also clear the cookie so the test can be repeated (if you want to mess around with browser settings and re-try).

```<code><?php
  header('Content-Type: application/javascript; charset=UTF-8');
  // Read test cookie, if there
  $cookie_received = (isset($_COOKIE['third_party_c_t']) && $_COOKIE['third_party_c_t'] == 'hey there!');
  // And clear it so the user can test it again
  setcookie('third_party_c_t', '', time() - 3600*24);
?>
window._3rd_party_test_step2_loaded(<?php echo ($cookie_received ? 'true' : 'false'); ?>);
</code>```

The last line uses the ternary operator to output a literal Javascript true or false depending on whether the test cookie was present.

Test it here.

Available for your testing pleasure at https://alanhogan.github.io/web-experiments/3rd/third-party-cookies.html.

(As a final note — don’t use someone else’s server to test third-party cookies without their permission. It could break spontaneously or inject malware. And it’s rude.)

Body:
Technical Background

The third party sets & reads cookies over HTTP (not in JavaScript).

So we need two requests to an external domain to test if third-party cookies are enabled:

One where the third party sets the cookie(s)

The second, with a differing response depending on whether the browser sent the cookie(s) back to the same third party in a second request.

We cannot use XMLHTTPRequest (Ajax) because of the DOM security model.

Obviously you can't load both scripts in parallel, or the second request may be made before the first request’s response makes it back, and the test cookie(s) will not have been set.

Code Example

Given:

The .html file is on one domain, and

The .js.php files are on a second domain, we have:

The HTML test page

Saved as third-party-cookies.html

<!DOCTYPE html>
<html>
<head id="head">
  <meta charset=utf-8 />
  <title>Test if Third-Party Cookies are Enabled</title>
<style type="text/css">
body {
  color: black;
  background: white none;
}
.error {
  color: #c00;
}
.loading {
  color: #888;
}
.hidden {
  display: none;
}
</style>
<script type="text/javascript">
window._3rd_party_test_step1_loaded = function(){
  // At this point, a third-party domain has now attempted to set a cookie (if all went to plan!)
  var step2Url = 'http://third-party.example.com/step2.js.php',
    resultsEl = document.getElementById('3rd_party_cookie_test_results'),
    step2El = document.createElement('script');

  // Update loading / results message
  resultsEl.innerHTML = 'Stage one complete, loading stage 2&hellip;';
  // And load the second part of the test (reading the cookie)
  step2El.setAttribute('src', step2Url);
  resultsEl.appendChild(step2El);
}
window._3rd_party_test_step2_loaded = function(cookieSuccess){
  var resultsEl = document.getElementById('3rd_party_cookie_test_results'),
    errorEl = document.getElementById('3rd_party_cookie_test_error');
  // Show message
  resultsEl.innerHTML = (cookieSuccess ? 'Third party cookies are <b>functioning</b> in your browser.' : 'Third party cookies appear to be <b>disabled</b>.');

  // Done, so remove loading class
  resultsEl.className = resultsEl.className.replace(/\bloading\b/,' ');
  // And remove error message
  errorEl.className = 'hidden';
}
</script>
</head>
<body id="thebody">

  <h1>Test if Third-Party Cookies are Enabled</h1>

  <p id="3rd_party_cookie_test_results" class='loading'>Testing&hellip;</p>
  <p id="3rd_party_cookie_test_error" class="error hidden">(If this message persists, the test could not be completed; we could not reach the third-party to test, or another error occurred.)</p>

  <script type="text/javascript">
  window.setTimeout(function(){
    var errorEl = document.getElementById('3rd_party_cookie_test_error');
    if(errorEl.className.match(/\berror\b/)) {
      // Show error message
      errorEl.className = errorEl.className.replace(/\bhidden\b/,' ');
    } else {
    }
  }, 7*1000); // 7 sec timeout
  </script>
  <script type="text/javascript" src="http://third-party.example.com/step1.js.php"></script>
</body>
</html>

The first third-party JavaScript file

Saved as step1.js.php

This is written in PHP so we can set cookies as the file loads. (It could, of course, be written in any language, or even done in server config files.)

<?php
  header('Content-Type: application/javascript; charset=UTF-8');
  // Set test cookie
  setcookie('third_party_c_t', 'hey there!', time() + 3600*24*2);
?>
window._3rd_party_test_step1_loaded();

The second third-party JavaScript file

Saved as step2.js.php

This is written in PHP so we can read cookies, server-side, before we respond. We also clear the cookie so the test can be repeated (if you want to mess around with browser settings and re-try).

<?php
  header('Content-Type: application/javascript; charset=UTF-8');
  // Read test cookie, if there
  $cookie_received = (isset($_COOKIE['third_party_c_t']) && $_COOKIE['third_party_c_t'] == 'hey there!');
  // And clear it so the user can test it again
  setcookie('third_party_c_t', '', time() - 3600*24);
?>
window._3rd_party_test_step2_loaded(<?php echo ($cookie_received ? 'true' : 'false'); ?>);

The last line uses the ternary operator to output a literal Javascript true or false depending on whether the test cookie was present.

Test it here.

Available for your testing pleasure at https://alanhogan.github.io/web-experiments/3rd/third-party-cookies.html.

(As a final note — don’t use someone else’s server to test third-party cookies without their permission. It could break spontaneously or inject malware. And it’s rude.)


问:
Spanning a range of colors to a text in HTML
I am comparatively new to HTML & I recently came across a website (YT video) which made a beautiful range of colors on the button. Link to the website: https://www.youtube.com/watch?v=OPaLnMw2i_0

I was wondering if these ranges of colors used can be implemented to some text in HTML. Could anyone help me out with this?
Range of colors used on the tab Button (This is done using React & Next.js)

Thanks in Advance!

答:
You can use inline CSS and its linear-gradient function.

Read:
https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient()

Example:

Learn More

```

Body:
You can use inline CSS and its linear-gradient function.

Read:
https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient()

Example:

<p style="
    background:linear-gradient(to left, blue, pink);
    font-family: sans-serif;
    color: white;
    font-weight: bold;
    width: 10em;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
    border-radius: 5%;
    margin: 10rem auto;
">Learn More</p>


问:
One-Many Relationship in Jpa
I want to get data from my entity with 1-M relationships.
Users have an entity for cv information.With JpaRepo,
Cv class :

```<code>@Entity
@Table(name = "cvs")
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "educations", "works", "langueges", "technologies"})
public class CV {

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

    //ToDo : Employee bilgilerinin görünmesi problemi giderilecek.
    @OneToOne
    @JoinColumn(name = "employee_id")
    private Employee employee;

    @OneToMany(mappedBy = "cv", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Education> educations;

    @OneToMany(mappedBy = "cv", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Work> works;

    @OneToMany(mappedBy = "cv", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Languege> langueges;

    @OneToMany(mappedBy = "cv", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Technology> technologies;

    @Column(name = "github")
    private String github;

    @Column(name = "linkedin")
    private String linkedin;

    @NotNull
    @NotBlank
    @Column(name = "cover_letter")
    private String coverLetter;

    @Column(name = "photo")
    private String photo;

}
</code>```

This is Education class (work, languege, technology classes same):

```<code>@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "cv_educations")
public class Education {

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

    @NotNull
    @NotBlank
    @Column(name = "school_name")
    private String schoolName;

    @NotNull
    @NotBlank
    @Column(name = "department")
    private String department;

    @NotNull
    @NotBlank
    @PastOrPresent
    @Column(name = "starting_date")
    @DateTimeFormat(pattern = "yyyy-mm-dd")
    private LocalDate startingDate;

    @NotBlank
    @Column(name = "graduation_date")
    @DateTimeFormat(pattern = "yyyy-mm-dd")
    private LocalDate graduationDate;

    @ManyToOne
    @JoinColumn(name = "cv_id")
    private CV cv;
}
</code>```

I tried to build the following structure with jpa, but the constructer takes list parameter. I got an error because I couldn't write it with jpql

```<code>public interface CvRepository extends JpaRepository<CV, Integer> {

        @Query("select new com.demo.humanresourcesmanagementsystem.Entities.concretes.CV" +
                "(employee.firstName, employee.lastName, cv.github, cv.linkedin, cv.coverLetter," +
                "educations, works, langueges, technologies)" +
                "from CV cv inner join cv.employee employee inner join cv.educations educations " +
                "inner join cv.works works inner join cv.langueges langueges " +
                "inner join cv.technologies technologies where cv.employee.id =:employeeId")
        CV findByCv(int employeeId);
    }
</code>```

I'd like to read about the educations, works, langueges and technologies in this entity. This means that there will be one cv as output, but there may be more than one education object within the cv (such as primary school, high school), and the incoming data will be in the following format, for example:

```<code>"firstName": "X",
"lastName" : "X",
"educations" : [
           "education1" {
                  "school" : "x",
                  "department" : "x" ...},
           "education2" {
                  "school" : "x",
                  "department" : "x"...}
"works" : [
    "work1" {
           "workplace" : "x",
           "job" : "x" ...
          }
       ]
"github" : "x",
"linkedin" : "x"
</code>```

How do i set up this structure with the jpa repository? What kind of dto should I write if I'm gonna use it? Thanks.

UPDATE

When i use spring jpa derivered query (findByEmployeeId) i receive data with this format :

```<code>{
  "success": true,
  "message": "string",
  "data": {
    "id": 0,
    "employee": {
      "id": 0,
      "email": "string",
      "password": "string",
      "firstName": "string",
      "lastName": "string",
      "nationalIdentity": "string",
      "yearOfBirth": 0
    },
    "github": "string",
    "linkedin": "string",
    "coverLetter": "string",
    "photo": "string"
  }
}
</code>```

So i cant receive data for education, work, languege and technology.

答:
It seems you're trying to retrieve a CV by its employer.id. In that case, you can really just use the JPA query method containing keywords. In this case it would look like:

CV findByEmployeeId(int employeeId);

This should return the complete CV object as you would expect.

See here for more details on JPA query method keywords.

Title: One-Many Relationship in Jpa

Body:
I want to get data from my entity with 1-M relationships.
Users have an entity for cv information.With JpaRepo,
Cv class :

@Entity
@Table(name = "cvs")
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "educations", "works", "langueges", "technologies"})
public class CV {

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

    //ToDo : Employee bilgilerinin görünmesi problemi giderilecek.
    @OneToOne
    @JoinColumn(name = "employee_id")
    private Employee employee;

    @OneToMany(mappedBy = "cv", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Education> educations;

    @OneToMany(mappedBy = "cv", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Work> works;

    @OneToMany(mappedBy = "cv", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Languege> langueges;

    @OneToMany(mappedBy = "cv", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Technology> technologies;

    @Column(name = "github")
    private String github;

    @Column(name = "linkedin")
    private String linkedin;

    @NotNull
    @NotBlank
    @Column(name = "cover_letter")
    private String coverLetter;

    @Column(name = "photo")
    private String photo;

}

This is Education class (work, languege, technology classes same):

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "cv_educations")
public class Education {

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

    @NotNull
    @NotBlank
    @Column(name = "school_name")
    private String schoolName;

    @NotNull
    @NotBlank
    @Column(name = "department")
    private String department;

    @NotNull
    @NotBlank
    @PastOrPresent
    @Column(name = "starting_date")
    @DateTimeFormat(pattern = "yyyy-mm-dd")
    private LocalDate startingDate;

    @NotBlank
    @Column(name = "graduation_date")
    @DateTimeFormat(pattern = "yyyy-mm-dd")
    private LocalDate graduationDate;

    @ManyToOne
    @JoinColumn(name = "cv_id")
    private CV cv;
}

I tried to build the following structure with jpa, but the constructer takes list parameter. I got an error because I couldn't write it with jpql

public interface CvRepository extends JpaRepository<CV, Integer> {

        @Query("select new com.demo.humanresourcesmanagementsystem.Entities.concretes.CV" +
                "(employee.firstName, employee.lastName, cv.github, cv.linkedin, cv.coverLetter," +
                "educations, works, langueges, technologies)" +
                "from CV cv inner join cv.employee employee inner join cv.educations educations " +
                "inner join cv.works works inner join cv.langueges langueges " +
                "inner join cv.technologies technologies where cv.employee.id =:employeeId")
        CV findByCv(int employeeId);
    }

I'd like to read about the educations, works, langueges and technologies in this entity. This means that there will be one cv as output, but there may be more than one education object within the cv (such as primary school, high school), and the incoming data will be in the following format, for example:

"firstName": "X",
"lastName" : "X",
"educations" : [
           "education1" {
                  "school" : "x",
                  "department" : "x" ...},
           "education2" {
                  "school" : "x",
                  "department" : "x"...}
"works" : [
    "work1" {
           "workplace" : "x",
           "job" : "x" ...
          }
       ]
"github" : "x",
"linkedin" : "x"

How do i set up this structure with the jpa repository? What kind of dto should I write if I'm gonna use it? Thanks.

UPDATE

When i use spring jpa derivered query (findByEmployeeId) i receive data with this format :

{
  "success": true,
  "message": "string",
  "data": {
    "id": 0,
    "employee": {
      "id": 0,
      "email": "string",
      "password": "string",
      "firstName": "string",
      "lastName": "string",
      "nationalIdentity": "string",
      "yearOfBirth": 0
    },
    "github": "string",
    "linkedin": "string",
    "coverLetter": "string",
    "photo": "string"
  }
}

So i cant receive data for education, work, languege and technology.


问:
Custom resolver to select a field from a DictConfig
```<code>nodes:
  node1: 1
  node2: 2
  node3: 3

selected_node: ${subfield:${nodes},node1}
</code>```

Can I make a subfield resolver that returns nodes["node1"] and stores it in selected_node?

My attempts so far result in this error:

```<code>omegaconf.errors.GrammarParseError: token recognition error at: '{'
    full_key: selected_node
    object_type=dict
</code>```

答:
I managed to solve this using the implementation below.

It would be better to avoid importing the private interface omegaconf._impl, but I haven't yet found a way to do that.

import yaml
from omegaconf import OmegaConf

def _subfield(key, field, _parent_):
    from omegaconf._impl import select_value
    obj = select_value(cfg=_parent_,
                       key=key,
                       absolute_key=True,
                       throw_on_missing=True,
                       throw_on_resolution_failure=True)
    return obj[field]

OmegaConf.register_new_resolver("subfield", _subfield)

d = yaml.safe_load("""
nodes:
  node1: this_one
  node2: not_this
  node3: and_not_this

selected_node: ${subfield:nodes,node1}
""")

cfg = OmegaConf.create(d)
print(cfg.selected_node)
# this_one
```

Body:
nodes:
  node1: 1
  node2: 2
  node3: 3

selected_node: ${subfield:${nodes},node1}

Can I make a subfield resolver that returns nodes["node1"] and stores it in selected_node?

My attempts so far result in this error:

omegaconf.errors.GrammarParseError: token recognition error at: '{'
    full_key: selected_node
    object_type=dict


问:
Coinbase API - Keep getting Invalid API Key despite following the documentation
I'm trying to set me up an application to interact with Coinbase API but I'm struggling with the API Key/Secret.

Based on my code:

import { readFile } from 'fs';
import crypto from 'crypto';
import request from 'request';
import { request as rqu } from 'undici';
import fetch, { Headers } from 'node-fetch';
// Import { getJSON } from './sys-handler.mjs';

/**
 * Read Local JSON file
 * No real error management but that should be fine
 *
 * @param {string} file - JSON file to read
 * @returns {object}
 */
function getJSON( file ) {
    return new Promise( ( resolve, reject ) => {
        readFile( file, 'utf8', ( err, data ) => {
            if ( err ) {
                reject( err );
            }
            else {
                resolve( JSON.parse( data ) );
            }
        } );
    } );
}

/**
 * Base64 Decode
 * @param {string} str
 * @returns {string}
 */
function atob( str ) {
    return `${ Buffer.from( str, 'base64' ) }`;
}

/**
 * Base64 Encode
 * @param {string} str
 * @returns {string}
 */
function btoa( str ) {
    return `${ Buffer.from( str ).toString( 'base64' ) }`;
}

/**
 * Get API Credentials from base64 Hash
 *
 * Credentials are stored in a string that is composed of the following:
 * - Key
 * - Secret
 * - Passphrase
 *
 * Each is base64 encoded, then they are joined with a colon (:), then the whole string is base64 encoded again.
 *
 * @param {string} file JSON File containing API Credentials
 * @returns {Promise<string[]>}
 */
async function getApiCredentialsFromBase64( file ) {
    try {
        const keys = await getJSON( file );
        return keys.map(
            str => atob( str )
                .split( ':' )
                .map( atob )
        );
    }
    catch ( error ) {
        throw error;
    }
}

/**
 * Get API Credentials from plain text
 *
 * Credentials are stored in clear plain text as they were generated initially in a JSON object as follows:
 * ```javascript
 * {
 *     "key":        "................",
 *     "secret":     "...........................",
 *     "passphrase": "............."
 * }
 * ```
 *
 * @param {string} file JSON File containing API Credentials
 * @returns {Promise<string[]>}
 */
async function getApiCredentialsFromPlainText( file ) {
    try {
        const { key, secret, passphrase } = await getJSON( file );
        return {
            key,
            secret,
            passphrase
        };
    }
    catch ( error ) {
        throw error;
    }
}

/**
 * Ensure path does not start with /
 *
 * @param {string} path
 * @returns {string}
 */
function sanitizePath( path ) {
    return `${ path.replace( /^\/*/gu, '' ) }`;
}

/**
 * Ensure url does not end with /
 *
 * @param {string} url
 * @returns {string}
 */
function sanitizeURL( url ) {
    return `${ url.replace( /\/*$/gu, '' ) }`;
}

/**
 * @typedef {Object} SignatureOptions
 * @property {string} method - HTTP Method
 * @property {string} endpoint - API Endpoint
 * @property {string} body - Request Body
 * @property {number} timestamp - Timestamp
 * @property {string} version - API Version
 * @property {string} credentials - API Credentials File
 */

/**
 * Build Coinbase-formatted Signature
 *
 * A timestamp, the method, the path and the body are all concatenated together to create the `message` string.
 * The `message` string is then signed using the base64 decoded API Secret through an HMAC-sha256.
 *
 * Then, `timestamp`, sanitized `path`, `passphrase`, API Key, the base64 encoded HMAC-sha256 signature and the trailing-slash-free endpoint are returned within an object.
 *
 *
 * @param {SignatureOptions} options - Options
 */
async function buildSignature( {
    timestamp = Math.floor( Date.now() / 1000 ),
    method = 'GET',
    endpoint,
    body,
    credentials,
    version
} ) {
    // Sanitize the path
    const _endpoint = sanitizePath( endpoint );

    let key; let passphrase; let
        secret;

    // Get API Credentials
    if ( credentials.endsWith( '.base64.json' ) ) {
        [ [ key, secret, passphrase ] ] = await getApiCredentialsFromBase64( credentials );
        secret = atob( secret );
    }
    else {
        ( { key, secret, passphrase } = await getApiCredentialsFromPlainText( credentials ) );
    }

    // Build Message
    let message;
    // If a version is provided, it is prepended to the endpoint
    if ( version ) {
        message = `${ timestamp }${ method.toUpperCase() }/${ version }/${ _endpoint }${ body || '' }`;
    }
    else {
        message = `${ timestamp }${ method.toUpperCase() }/${ _endpoint }${ body || '' }`;
    }

    return {
        signature: crypto.createHmac( 'sha256', secret )
            .update( message )
            .digest( 'base64' ),
        timestamp,
        passphrase,
        key,
        endpoint: _endpoint
    };
}

/**
 * @typedef {Object} APIRequestOptions
 * @property {string} api - API URL
 * @property {string} version - API Version
 * @property {string} endpoint - API Endpoint
 * @property {string} credentials - API Key File
 * @property {string|Object} body - Request Body
 * @property {string} method - HTTP Method
 * @property {string} lib - Library used to send request
 * @returns
 */

/**
 * Send API Request
 *
 * @param {APIRequestOptions} options
 * @returns {Promise<*>}
 */
const getAccountInfo = async ( {
    endpoint,
    body,
    method = 'GET',
    version = 'v2',
    sandbox = false,
    credentials = './api.json',
    api,
    lib = 'undici'
} ) => {

    let _api;

    if ( !api ) {
        // Choose the right URL depending on the sandbox mode
        if ( sandbox ) {
            _api = `https://api-public.sandbox.exchange.coinbase.com`;
        }
        else {
            _api = `https://api.exchange.coinbase.com`;
        }
    }
    else {
        _api = `${ sanitizeURL( api ) }`;
    }

    if ( version ) {
        _api = `${ _api }/${ version }`;
    }

    // Build Request Signature
    const {
        key,
        signature,
        passphrase,
        timestamp,
        endpoint: _endpoint
    } = await buildSignature( { method, endpoint, body, credentials, version } );

    // Full Endpoint
    const fullEndpoint = `${ _api }/${ _endpoint }`;

    // Send Request
    return await new Promise( async ( resolve, reject ) => {

        // Craft Request Headers
        const headers = {
            'User-Agent': 'aemi-node-client',
            'CB-ACCESS-KEY': key,
            'CB-ACCESS-SIGN': signature,
            'CB-ACCESS-TIMESTAMP': timestamp,
            'CB-ACCESS-PASSPHRASE': passphrase,
            Accept: 'application/json',
            'Content-Type': 'application/json'
        };

        const options = {};

        // Try different libraries to send the request
        switch ( lib ) {
            case 'node-fetch': {
                /*
                 * Craft Request Options
                 * Use object assign as official Coinbase Pro Node Client does
                 * Using the Headers object from node-fetch library
                 */
                Object.assign( options, {
                    headers: new Headers( headers ),
                    method,
                    uri: fullEndpoint,
                    ...body ? { body } : {}
                } );
                // Parse the JSON request or display an error
                try {
                    const response = await fetch( fullEndpoint, options );
                    resolve( await response.json() );
                }
                catch ( error ) {
                    console.error( error );
                    reject( error );
                }

                break;
            }
            case 'request': {
                /*
                 * Craft Request Options
                 * Use object assign as official Coinbase Pro Node Client does
                 */
                Object.assign( options, {
                    headers,
                    method,
                    uri: fullEndpoint,
                    ...body ? { body } : {}
                } );
                // Send Request
                request( options, async ( error, response, data ) => {
                    // Parse the JSON request or display an error
                    try {
                        if ( error ) {
                            reject( error );
                        }
                        else {
                            if ( data ) {
                                resolve( JSON.parse( data ) );
                            }
                            else {
                                resolve( await response.toJSON() );
                            }
                        }
                    }
                    catch ( error ) {
                        reject( error );
                    }
                } );
                break;
            }
            case 'undici':
            default: {
                /*
                 * Craft Request Options
                 * Use object assign as official Coinbase Pro Node Client does
                 */
                Object.assign( options, {
                    headers,
                    method,
                    uri: fullEndpoint,
                    ...body ? { body } : {}
                } );
                // Parse the JSON request or display an error
                try {
                    const response = await rqu( fullEndpoint, options );
                    resolve( await response.body.json() );
                }
                catch ( error ) {
                    console.error( error );
                    reject( error );
                }

                break;
            }
        }
    } );
};

// API URLs tested
const apis = [
    'https://api.pro.coinbase.com',
    'https://api.exchange.coinbase.com',
    'https://api-public.sandbox.exchange.coinbase.com',
    'https://api-public.sandbox.pro.coinbase.com'
];

// API Key files
const apiKeys = [
    './api.base64.json', // View Rights on Coinbase Pro (1st key generated)
    './api.test.base64.json', // View Rights on Coinbase Pro (2nd Key generated)
    './api.sandbox.base64.json', // View Rights on Coinbase Pro Sandbox Mode
    './api.plain.json' // View Rights on Coinbase Pro (same as api.test.base64)
];

// Libraries tested to send request
const libs = [
    'undici',
    'request',
    'node-fetch'
];

// Test Endpoint that requires authentication
const endpoint = '/accounts';

// Avoid ESLint parsing problem about await outside an async function
( async () => {
    for ( const lib of libs ) {
        for ( const version of [ '', 'v2' ] ) {
            for ( const key of apiKeys ) {
                for ( const api of apis ) {
                    const options = { api, version, endpoint, credentials: key, lib };
                    console.log( `// ---- ----- ---- //` );
                    try {
                        const response = await getAccountInfo( options );
                        options.return = JSON.stringify( response, 0, 0 );
                    }
                    catch ( error ) {
                        console.error( `//      Error      //` );
                        let errorString;
                        try {
                            errorString = JSON.stringify( error, 0, 0 );
                        }
                        catch ( _ ) {
                            errorString = error;
                        }
                        options.return = errorString;
                    }
                    console.log( options );
                    console.log( `// ---- ----- ---- //` );
                }
            }
        }
    }
} )();
```
<p>...I keep getting (logs have been truncated because of Stack Overflow characters limit and I removed the combinations <code>(exchange|pro)-key/(exchange|pro)-sandbox-mode</code>):</p>
<pre class="lang-js prettyprint-override"><code>// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.test.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.test.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api-public.sandbox.exchange.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.sandbox.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api-public.sandbox.pro.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.sandbox.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.plain.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.plain.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.test.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.test.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api-public.sandbox.exchange.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.sandbox.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api-public.sandbox.pro.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.sandbox.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.plain.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.plain.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ... It goes the same way with other used libraries.
</code>```

If I'm dumb as f*ck, tell me but please tell me what's wrong with this code too. I'm not sure the API URLs are correct but every URLs Coinbase provides resulted in unsuccessful trials.

Edit: Code has been commented and detailed precisely, and logs provided have not been manipulated unless specified.

Thank you all,

Best Regards

答:
As the comments suggest you probably have an invalid key. I've seen CB invalidate my Key out of nowhere and I have to get a new one.

If you were having problems with your signature you'd get more appropriate errors.

Something like:

invalid signature

timestamp has expired

etc.

Body:
I'm trying to set me up an application to interact with Coinbase API but I'm struggling with the API Key/Secret.

Based on my code:

import { readFile } from 'fs';
import crypto from 'crypto';
import request from 'request';
import { request as rqu } from 'undici';
import fetch, { Headers } from 'node-fetch';
// Import { getJSON } from './sys-handler.mjs';

/**
 * Read Local JSON file
 * No real error management but that should be fine
 *
 * @param {string} file - JSON file to read
 * @returns {object}
 */
function getJSON( file ) {
    return new Promise( ( resolve, reject ) => {
        readFile( file, 'utf8', ( err, data ) => {
            if ( err ) {
                reject( err );
            }
            else {
                resolve( JSON.parse( data ) );
            }
        } );
    } );
}

/**
 * Base64 Decode
 * @param {string} str
 * @returns {string}
 */
function atob( str ) {
    return `${ Buffer.from( str, 'base64' ) }`;
}

/**
 * Base64 Encode
 * @param {string} str
 * @returns {string}
 */
function btoa( str ) {
    return `${ Buffer.from( str ).toString( 'base64' ) }`;
}

/**
 * Get API Credentials from base64 Hash
 *
 * Credentials are stored in a string that is composed of the following:
 * - Key
 * - Secret
 * - Passphrase
 *
 * Each is base64 encoded, then they are joined with a colon (:), then the whole string is base64 encoded again.
 *
 * @param {string} file JSON File containing API Credentials
 * @returns {Promise<string[]>}
 */
async function getApiCredentialsFromBase64( file ) {
    try {
        const keys = await getJSON( file );
        return keys.map(
            str => atob( str )
                .split( ':' )
                .map( atob )
        );
    }
    catch ( error ) {
        throw error;
    }
}

/**
 * Get API Credentials from plain text
 *
 * Credentials are stored in clear plain text as they were generated initially in a JSON object as follows:
 * ```javascript
 * {
 *     "key":        "................",
 *     "secret":     "...........................",
 *     "passphrase": "............."
 * }
 * ```
 *
 * @param {string} file JSON File containing API Credentials
 * @returns {Promise<string[]>}
 */
async function getApiCredentialsFromPlainText( file ) {
    try {
        const { key, secret, passphrase } = await getJSON( file );
        return {
            key,
            secret,
            passphrase
        };
    }
    catch ( error ) {
        throw error;
    }
}

/**
 * Ensure path does not start with /
 *
 * @param {string} path
 * @returns {string}
 */
function sanitizePath( path ) {
    return `${ path.replace( /^\/*/gu, '' ) }`;
}

/**
 * Ensure url does not end with /
 *
 * @param {string} url
 * @returns {string}
 */
function sanitizeURL( url ) {
    return `${ url.replace( /\/*$/gu, '' ) }`;
}

/**
 * @typedef {Object} SignatureOptions
 * @property {string} method - HTTP Method
 * @property {string} endpoint - API Endpoint
 * @property {string} body - Request Body
 * @property {number} timestamp - Timestamp
 * @property {string} version - API Version
 * @property {string} credentials - API Credentials File
 */

/**
 * Build Coinbase-formatted Signature
 *
 * A timestamp, the method, the path and the body are all concatenated together to create the `message` string.
 * The `message` string is then signed using the base64 decoded API Secret through an HMAC-sha256.
 *
 * Then, `timestamp`, sanitized `path`, `passphrase`, API Key, the base64 encoded HMAC-sha256 signature and the trailing-slash-free endpoint are returned within an object.
 *
 *
 * @param {SignatureOptions} options - Options
 */
async function buildSignature( {
    timestamp = Math.floor( Date.now() / 1000 ),
    method = 'GET',
    endpoint,
    body,
    credentials,
    version
} ) {
    // Sanitize the path
    const _endpoint = sanitizePath( endpoint );

    let key; let passphrase; let
        secret;

    // Get API Credentials
    if ( credentials.endsWith( '.base64.json' ) ) {
        [ [ key, secret, passphrase ] ] = await getApiCredentialsFromBase64( credentials );
        secret = atob( secret );
    }
    else {
        ( { key, secret, passphrase } = await getApiCredentialsFromPlainText( credentials ) );
    }

    // Build Message
    let message;
    // If a version is provided, it is prepended to the endpoint
    if ( version ) {
        message = `${ timestamp }${ method.toUpperCase() }/${ version }/${ _endpoint }${ body || '' }`;
    }
    else {
        message = `${ timestamp }${ method.toUpperCase() }/${ _endpoint }${ body || '' }`;
    }

    return {
        signature: crypto.createHmac( 'sha256', secret )
            .update( message )
            .digest( 'base64' ),
        timestamp,
        passphrase,
        key,
        endpoint: _endpoint
    };
}

/**
 * @typedef {Object} APIRequestOptions
 * @property {string} api - API URL
 * @property {string} version - API Version
 * @property {string} endpoint - API Endpoint
 * @property {string} credentials - API Key File
 * @property {string|Object} body - Request Body
 * @property {string} method - HTTP Method
 * @property {string} lib - Library used to send request
 * @returns
 */

/**
 * Send API Request
 *
 * @param {APIRequestOptions} options
 * @returns {Promise<*>}
 */
const getAccountInfo = async ( {
    endpoint,
    body,
    method = 'GET',
    version = 'v2',
    sandbox = false,
    credentials = './api.json',
    api,
    lib = 'undici'
} ) => {

    let _api;

    if ( !api ) {
        // Choose the right URL depending on the sandbox mode
        if ( sandbox ) {
            _api = `https://api-public.sandbox.exchange.coinbase.com`;
        }
        else {
            _api = `https://api.exchange.coinbase.com`;
        }
    }
    else {
        _api = `${ sanitizeURL( api ) }`;
    }

    if ( version ) {
        _api = `${ _api }/${ version }`;
    }

    // Build Request Signature
    const {
        key,
        signature,
        passphrase,
        timestamp,
        endpoint: _endpoint
    } = await buildSignature( { method, endpoint, body, credentials, version } );

    // Full Endpoint
    const fullEndpoint = `${ _api }/${ _endpoint }`;

    // Send Request
    return await new Promise( async ( resolve, reject ) => {

        // Craft Request Headers
        const headers = {
            'User-Agent': 'aemi-node-client',
            'CB-ACCESS-KEY': key,
            'CB-ACCESS-SIGN': signature,
            'CB-ACCESS-TIMESTAMP': timestamp,
            'CB-ACCESS-PASSPHRASE': passphrase,
            Accept: 'application/json',
            'Content-Type': 'application/json'
        };

        const options = {};

        // Try different libraries to send the request
        switch ( lib ) {
            case 'node-fetch': {
                /*
                 * Craft Request Options
                 * Use object assign as official Coinbase Pro Node Client does
                 * Using the Headers object from node-fetch library
                 */
                Object.assign( options, {
                    headers: new Headers( headers ),
                    method,
                    uri: fullEndpoint,
                    ...body ? { body } : {}
                } );
                // Parse the JSON request or display an error
                try {
                    const response = await fetch( fullEndpoint, options );
                    resolve( await response.json() );
                }
                catch ( error ) {
                    console.error( error );
                    reject( error );
                }

                break;
            }
            case 'request': {
                /*
                 * Craft Request Options
                 * Use object assign as official Coinbase Pro Node Client does
                 */
                Object.assign( options, {
                    headers,
                    method,
                    uri: fullEndpoint,
                    ...body ? { body } : {}
                } );
                // Send Request
                request( options, async ( error, response, data ) => {
                    // Parse the JSON request or display an error
                    try {
                        if ( error ) {
                            reject( error );
                        }
                        else {
                            if ( data ) {
                                resolve( JSON.parse( data ) );
                            }
                            else {
                                resolve( await response.toJSON() );
                            }
                        }
                    }
                    catch ( error ) {
                        reject( error );
                    }
                } );
                break;
            }
            case 'undici':
            default: {
                /*
                 * Craft Request Options
                 * Use object assign as official Coinbase Pro Node Client does
                 */
                Object.assign( options, {
                    headers,
                    method,
                    uri: fullEndpoint,
                    ...body ? { body } : {}
                } );
                // Parse the JSON request or display an error
                try {
                    const response = await rqu( fullEndpoint, options );
                    resolve( await response.body.json() );
                }
                catch ( error ) {
                    console.error( error );
                    reject( error );
                }

                break;
            }
        }
    } );
};

// API URLs tested
const apis = [
    'https://api.pro.coinbase.com',
    'https://api.exchange.coinbase.com',
    'https://api-public.sandbox.exchange.coinbase.com',
    'https://api-public.sandbox.pro.coinbase.com'
];

// API Key files
const apiKeys = [
    './api.base64.json', // View Rights on Coinbase Pro (1st key generated)
    './api.test.base64.json', // View Rights on Coinbase Pro (2nd Key generated)
    './api.sandbox.base64.json', // View Rights on Coinbase Pro Sandbox Mode
    './api.plain.json' // View Rights on Coinbase Pro (same as api.test.base64)
];

// Libraries tested to send request
const libs = [
    'undici',
    'request',
    'node-fetch'
];

// Test Endpoint that requires authentication
const endpoint = '/accounts';

// Avoid ESLint parsing problem about await outside an async function
( async () => {
    for ( const lib of libs ) {
        for ( const version of [ '', 'v2' ] ) {
            for ( const key of apiKeys ) {
                for ( const api of apis ) {
                    const options = { api, version, endpoint, credentials: key, lib };
                    console.log( `// ---- ----- ---- //` );
                    try {
                        const response = await getAccountInfo( options );
                        options.return = JSON.stringify( response, 0, 0 );
                    }
                    catch ( error ) {
                        console.error( `//      Error      //` );
                        let errorString;
                        try {
                            errorString = JSON.stringify( error, 0, 0 );
                        }
                        catch ( _ ) {
                            errorString = error;
                        }
                        options.return = errorString;
                    }
                    console.log( options );
                    console.log( `// ---- ----- ---- //` );
                }
            }
        }
    }
} )();

...I keep getting (logs have been truncated because of Stack Overflow characters limit and I removed the combinations (exchange|pro)-key/(exchange|pro)-sandbox-mode):

// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.test.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.test.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api-public.sandbox.exchange.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.sandbox.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api-public.sandbox.pro.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.sandbox.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.plain.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: '',
  endpoint: '/accounts',
  credentials: './api.plain.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.test.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.test.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api-public.sandbox.exchange.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.sandbox.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api-public.sandbox.pro.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.sandbox.base64.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.pro.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.plain.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ---- ----- ---- //
{
  api: 'https://api.exchange.coinbase.com',
  version: 'v2',
  endpoint: '/accounts',
  credentials: './api.plain.json',
  lib: 'undici',
  return: '{"message":"invalid signature"}'
}
// ---- ----- ---- //
// ... It goes the same way with other used libraries.

If I'm dumb as f*ck, tell me but please tell me what's wrong with this code too. I'm not sure the API URLs are correct but every URLs Coinbase provides resulted in unsuccessful trials.

Edit: Code has been commented and detailed precisely, and logs provided have not been manipulated unless specified.

Thank you all,

Best Regards


问:
Spring @Conditional based on a value in database table
Condition evaluation depends on a value provided in data base table

```<code>@Component
public class XYZCondition implements Condition{

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
              //based on value defined in DB should return true/false
    }

}
</code>```

As Condition is executing very early, unable to fetch db value
is there any alternate way to achieve this ?

答:
You can try defining your condition in your configuration file and use it like below :</p>
```<code>@ConditionalOnProperty(name="filter.enabled", havingValue="true")
</code>```

Body:
Condition evaluation depends on a value provided in data base table

@Component
public class XYZCondition implements Condition{

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
              //based on value defined in DB should return true/false
    }

}

As Condition is executing very early, unable to fetch db value
is there any alternate way to achieve this ?

Body:
You can try defining your condition in your configuration file and use it like below :

@ConditionalOnProperty(name="filter.enabled", havingValue="true")


问:
How Spring SAML Works if assertion expires
I have integrated wso2 IS 5.11 with Spring SAML. After login the SAML response contains 5 minutes of assertion expiry. But if the same user uses the application for more than 5 minutes. There is no assertion refresh or logout happened. So, I am not getting how the assertion refresh should happen? How the session expiry should happen?. I wanted to implement a stateless SAML implementation using SAML token how to implement for session validation for each request?

答:
The SAML assertion is validated upon login only. Thereafter, the app will be using its own session to keep users logged in. If the app side session is expired, the user will be redirected to WSO2 IS and the user will be automatically logged in (a new assertion will be issued) if the IDP session is still valid.

The default session idle timeout of WSO2 IS is 15mins. If the user did not interact with WSO2 IS for more than 15mins, the IDP session will be expired.

If your requirement is to use stateless authentication, you may read the answers for Stateless Sessions with Spring Security Saml and SP Application


问:
What event should be used for checking when a user's custom status updates?
I'm trying to make a vanity bot for Discord, but I'm not sure if I'm using the correct event. Here is my code:

```<code>client.on("presenceUpdate", newPresence => {
    let vanityRole = newPresence.guild.roles.cache.find(role => role.id === "940679835456536596");
  const activity = newPresence.member.user.presence.activities[0].state
  if (activity === null) return;
  if (activity.includes("gg/pm")) {
    let memberTarget = newPresence.guild.members.cache.get(newPresence.member.id);
    memberTarget.roles.add(vanityRole);
    const vanity = new Discord.MessageEmbed()
      .setColor(color)
      .setDescription(`<@${memberTarget.id}>, thanks for putting us in your status <3`);
      message.channel.send(vanity)
  }
  else return;
});
</code>```

Here is the error I'm receiving:
On this line: const activity = newPresence.member.user.presence.activities[0].state
Error: [TypeError: Cannot read property 'state' of undefined]
repl process died unexpectedly: exit status 1

Thanks

答:
One of your items at newPresence.member.user.presence.activities is equal to an empty array or undefined, therefore newPresence.member.user.presence.activities[0] === undefined.

You can try: const activity = newPresence.member.user.presence.activities[0]?.state

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

Body:
I'm trying to make a vanity bot for Discord, but I'm not sure if I'm using the correct event. Here is my code:

client.on("presenceUpdate", newPresence => {
    let vanityRole = newPresence.guild.roles.cache.find(role => role.id === "940679835456536596");
  const activity = newPresence.member.user.presence.activities[0].state
  if (activity === null) return;
  if (activity.includes("gg/pm")) {
    let memberTarget = newPresence.guild.members.cache.get(newPresence.member.id);
    memberTarget.roles.add(vanityRole);
    const vanity = new Discord.MessageEmbed()
      .setColor(color)
      .setDescription(`<@${memberTarget.id}>, thanks for putting us in your status <3`);
      message.channel.send(vanity)
  }
  else return;
});

Here is the error I'm receiving:
On this line: const activity = newPresence.member.user.presence.activities[0].state
Error: [TypeError: Cannot read property 'state' of undefined]
repl process died unexpectedly: exit status 1

Thanks


问:
Is there a generally accepted way to handle my exceptions in a WPF/PRISM app?
I'm trying to redo an existing app of mine using PRISM to get at a more manageable app construction.

My app throws, of course, exceptions here and there, now handled in a custom handler.
I want to do it the Prism way.

I see two options:

'.Publish()' the error data from the catch-block with the IEventAggregator and subscribe to the event in an error-handling Prism Module (which I could then also use in other apps). In the module I would subscribe to the event and do the handling with a DialogService registered as a singleton.

Run that DialogService (show a Dialog) directly from the catch-block.

Which is the best (or only) way?

答:
There is no "Prism Way" to handle exceptions.  The framework says nothing about them.   Exceptions can occur in situations where you would never want the user to know about them.  It depends on the nature of the exception.  Certainly, you do not want a dialog for every exception that occurs in your app.

In some cases, it is enough merely to log the exception.  If you are injecting some sort of event logging interface with Prism, then you should be able to do that no problem.  If you are NOT injecting an event log interface, start, doing it.

If the exception is important enough to notify the user, it is probably simpler to put the dialog right where the error occurs. That's assuming you are talking about a simple user alert and nothing more.

Only use IEventAggregator when other distinct components of your application need to know about what happened and your code (the part catching the exception) might not even know about them or how to notify them).  That is where IEventAggregator works best.

One thing about Prism's dialog service:  It is useful but it there is definitely some work to set up a dialog. If you are using any sort of UI toolkit that provides utility dialog functions for simple Alert/Prompt dialogs (as I fortunately am), I suggest using those instead.  Prism's dialogs shine better when you need complicated information returned.


问:
Javascript bookmarklet go to URL and execute
I have a javascript like this, used i a bookmarklet:

```<code>window.location="URL"
document.getElementById('username-id').value = 'User'
document.getElementById('pwd-id').value = 'pass'
doLogin();
</code>```

The problem is that javascript stops as soon as it hits the URL.
How to make it go to a page and execute a script?

Any help would be greatly appreciated.

答:
Try wrapping your code with window.onload event.

```<code>window.location = "URL"; window.onload = function() {
document.getElementById('username-id').value = 'User'
document.getElementById('pwd-id').value = 'pass'
doLogin();
}
</code>```

As the solution above doesn't work, you still should be able to write a simple browser extension to solve your problem. It's easy: choose the browser you use and follow the documentation. This is only way to do that.

Body:
I have a javascript like this, used i a bookmarklet:

window.location="URL"
document.getElementById('username-id').value = 'User'
document.getElementById('pwd-id').value = 'pass'
doLogin();

The problem is that javascript stops as soon as it hits the URL.
How to make it go to a page and execute a script?

Any help would be greatly appreciated.

Body:
Try wrapping your code with window.onload event.

window.location = "URL"; window.onload = function() {
document.getElementById('username-id').value = 'User'
document.getElementById('pwd-id').value = 'pass'
doLogin();
}

As the solution above doesn't work, you still should be able to write a simple browser extension to solve your problem. It's easy: choose the browser you use and follow the documentation. This is only way to do that.


问:
How to assign new Class object through factory method but in a "generic" way?
I'm trying to create a class where I can pass optional parameters and through a factory method it assigns the values to the corresponding class attributes.

But I cannot access in a "generic" way any attributes on the class.

```<code>this[key] = object[key];
</code>```

Is there a way to do it?

This is my object assignement:

```<code>p1: Person = new Person({ name: 'John Doe' });
p2: Person = new Person({ age: 2, height: 180 });
</code>```

This is my Person class:

```<code>export class Person {
  name: string = '';
  age: number = 0;
  height: number = 0;

  constructor(data: Object) {
    this.factory(data);
  }

  factory(object: Object) {
    for (const key in object) {
      if (object.hasOwnProperty(key)) {
        this[key] = object[key]; // <-- HERE IS MY PROBLEM
      }
    }
  }
}
</code>```

I put my code on Stackblitz

答:
There is an elegant solution for this. Add an indexer and use a more concrete parameter type. Look at this:

```<code>export class Person {
  name: string = '';
  age: number = 0;
  height: number = 0;

  [key: string]: any;

  constructor(data: Partial<Person>) {
    this.factory(data);
  }

  factory(object: Partial<Person>) {
    for (const key in object) {
      this[key] = object[key];
    }
  }
}
</code>```

Update: That should work even without indexer:

```<code>factory(object: Partial<Person>) {
  Object.assign(this, object);
}
</code>```

Body:
I'm trying to create a class where I can pass optional parameters and through a factory method it assigns the values to the corresponding class attributes.

But I cannot access in a "generic" way any attributes on the class.

this[key] = object[key];

Is there a way to do it?

This is my object assignement:

p1: Person = new Person({ name: 'John Doe' });
p2: Person = new Person({ age: 2, height: 180 });

This is my Person class:

export class Person {
  name: string = '';
  age: number = 0;
  height: number = 0;

  constructor(data: Object) {
    this.factory(data);
  }

  factory(object: Object) {
    for (const key in object) {
      if (object.hasOwnProperty(key)) {
        this[key] = object[key]; // <-- HERE IS MY PROBLEM
      }
    }
  }
}

I put my code on Stackblitz

Body:
There is an elegant solution for this. Add an indexer and use a more concrete parameter type. Look at this:

export class Person {
  name: string = '';
  age: number = 0;
  height: number = 0;

  [key: string]: any;

  constructor(data: Partial<Person>) {
    this.factory(data);
  }

  factory(object: Partial<Person>) {
    for (const key in object) {
      this[key] = object[key];
    }
  }
}

Update: That should work even without indexer:

factory(object: Partial<Person>) {
  Object.assign(this, object);
}