问:
POST request from Salesforce Marketing Cloud cloudpage to Twilio using SSJS
I am trying to send a POST request to Twilio's SMS API from Marketing Cloud's cloudpage using SSJS. I am getting a 401 unauthorized access even though I have added ACCOUNT_SID AND AUTH_TOKEN in the URL.

```
</div>
</div>
</p>
<p>I get this error:
{"message":"An error occurred when attempting to evaluate a HTTPPost function call. See inner exception for details.","description":"ExactTarget.OMM.FunctionExecutionException: An error occurred when attempting to evaluate a HTTPPost function call. See inner exception for details.\r\n Error Code: OMM_FUNC_EXEC_ERROR\r\n - from Jint --> \r\n\r\n --- inner exception 1---\r\n\r\nSystem.Net.WebException: The remote server returned an error: (401) Unauthorized. - from System\r\n\r\n\r\n\r\n"}</p>
<p>I have tried using client side JavaScript, but I get the same error.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><script>

const url = 'https://XXXX:XXXX@api.twilio.com/2010-04-01/Accounts/XXXX/Messages.json';

  var xhr = new XMLHttpRequest();
xhr.open("POST", url);

xhr.setRequestHeader("Accept", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

 var data = 'From=+0000&To=+0000&Body=Test1';

xhr.send(data);

</script></code>```

答:
Twilio developer evangelist here.

I'm not familiar with SSJS and I'm finding it hard to connect the documentation(?) with what you've written. If this documentation refers to the same HTTP.Post method you are using then try something like this:

```

In this case I have concatenated the accountSid and authToken separated by a ":" then base 64 encoded the result. I then added an Authorization header to the HTTP request and set the value to Basic  plus the base64 encoded credentials.

Body:
I am trying to send a POST request to Twilio's SMS API from Marketing Cloud's cloudpage using SSJS. I am getting a 401 unauthorized access even though I have added ACCOUNT_SID AND AUTH_TOKEN in the URL.

I get this error:
{"message":"An error occurred when attempting to evaluate a HTTPPost function call. See inner exception for details.","description":"ExactTarget.OMM.FunctionExecutionException: An error occurred when attempting to evaluate a HTTPPost function call. See inner exception for details.\r\n Error Code: OMM_FUNC_EXEC_ERROR\r\n - from Jint --> \r\n\r\n --- inner exception 1---\r\n\r\nSystem.Net.WebException: The remote server returned an error: (401) Unauthorized. - from System\r\n\r\n\r\n\r\n"}

I have tried using client side JavaScript, but I get the same error.

Body:
Twilio developer evangelist here.

I'm not familiar with SSJS and I'm finding it hard to connect the documentation(?) with what you've written. If this documentation refers to the same HTTP.Post method you are using then try something like this:

<script type="text/javascript" runat="server">
  Platform.Load("core", "1");

  var accountSid = YOUR_ACCOUNT_SID;
  var authToken  = YOUR_AUTH_TOKEN;
  var auth = btoa(accountSid + ":" + authToken);

  var config = {
    endpoint: "https://api.twilio.com/2010-04-01/Accounts/XXXX/Messages.json",
    contentType: "application/x-www-form-urlencoded",
    payload : "From=+0000&To=+0000&Body=Test1"
  };

  try {
    var httpResult = HTTP.Post(
      config.endpoint,
      config.contentType,
      config.payload,
      ["Authorization"],
      ["Basic " + auth]
    );

    var result = JSON.parse(httpResult.response);
    Write(httpResult.StatusCode);
    Write('result' + result);
  } catch(error) {
    Write(Stringify(error));
  }
</script>

In this case I have concatenated the accountSid and authToken separated by a ":" then base 64 encoded the result. I then added an Authorization header to the HTTP request and set the value to Basic  plus the base64 encoded credentials.


来源: stackexchange

问:
Finding a keyword in a column and editing a new column in Excel VBA
I want to read Column C and find different keywords at the beginning of the text.

For simplicity let's call them KW1 and KW2. Based on the keyword found I have to edit Column D with a text.

If "KW1" in cell C2, add a column D and cell D2 will have the text "Keyword1".

I do not know how to deal with the ranges.

I am doing a "for each" loop on Column C but I do not know how to refer to this column nor how to edit a different column using a for each.

Dummy document

I would have to add a column between Column 3 and Column 4 to implement this concept.

The myRange variable doesn't make sense. I modified it  many times trying to make it work.

Sub Keyword()
    Columns("D:D").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    ActiveCell.FormulaR1C1 = "Column 3.5"
    Range("I3").Select

    myRange = Worksheets("Sheet1").Selection.CurrentRegion.Select

    LR = Cells(Rows.Count, 1).End(xlUp).Row

    For Each cell In myRange
        If InStr(LCase(cell.Value), LCase("KW1:")) <> 0 Then
            cell.Value = "Keyword1"
        End If
    Next
End Sub
```

答:
Following methods should work (not tested)

Method 1: Loop rows

Sub Keyword()
    myRange =Range("A1").CurrentRegion
    For Each row In myRange.rows
            If InStr(LCase(cells(row,3).Value), LCase("KW1:")) <> 0 Then
                cells(row,4).Value = "Keyword1"
        end with
    Next
End Sub
```
<p>Method 2: Loop cells in column C</p>
<pre class="lang-vb prettyprint-override"><code>Sub Keyword()
    myRange = Range("C2:C" & Cells(Rows.Count, 1).End(xlUp).Row)

    For Each cell In myRange.cells
        If InStr(LCase(cell.Value), LCase("KW1:")) <> 0 Then
            cell.offset(0,1).Value = "Keyword1"
        End If
    Next
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Following methods should work (not tested)

Method 1: Loop rows

Sub Keyword()
    myRange =Range("A1").CurrentRegion
    For Each row In myRange.rows
            If InStr(LCase(cells(row,3).Value), LCase("KW1:")) <> 0 Then
                cells(row,4).Value = "Keyword1"
        end with
    Next
End Sub

Method 2: Loop cells in column C

Sub Keyword()
    myRange = Range("C2:C" & Cells(Rows.Count, 1).End(xlUp).Row)

    For Each cell In myRange.cells
        If InStr(LCase(cell.Value), LCase("KW1:")) <> 0 Then
            cell.offset(0,1).Value = "Keyword1"
        End If
    Next
End Sub


问:
What could be causing install errors with pip, conda and setup.py install
Whenever I try to install a package with pip or pip3 I get an error that starts with:

```<code>DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621
</code>```

and ends with:

```<code>
  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [1 lines of output]
      error in decorator setup command: use_2to3 is invalid.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code>```

using Conda I get the error:

```<code>ImportError: dlopen(/Users/user1/miniconda3/lib/python3.8/lib-dynload/_ctypes.cpython-38-darwin.so, 0x0002): Library not loaded: @rpath/libffi.7.dylib
  Referenced from: /Users/user1/miniconda3/lib/python3.8/lib-dynload/_ctypes.cpython-38-darwin.so
  Reason: tried: '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/python3.8/lib-dynload/../../libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/python3.8/lib-dynload/../../libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/bin/../lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/bin/../lib/libffi.7.dylib' (no such file), '/usr/local/lib/libffi.7.dylib' (no such file), '/usr/lib/libffi.7.dylib' (no such file)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/exceptions.py", line 1212, in print_unexpected_error_report
    message_builder.append(get_main_info_str(error_report['conda_info']))
  File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/cli/main_info.py", line 237, in get_main_info_str
    info_dict['_' + key] = ('\n' + 26 * ' ').join(info_dict[key])
KeyError: 'pkgs_dirs'

# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<

    Traceback (most recent call last):
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/exceptions.py", line 1080, in __call__
        return func(*args, **kwargs)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/cli/main.py", line 84, in _main
        exit_code = do_call(args, p)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/cli/conda_argparse.py", line 83, in do_call
        return getattr(module, func_name)(args, parser)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/cli/main_install.py", line 20, in execute
        install(args, parser, 'install')
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/cli/install.py", line 259, in install
        unlink_link_transaction = solver.solve_for_transaction(
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/core/solve.py", line 114, in solve_for_transaction
        unlink_precs, link_precs = self.solve_for_diff(update_modifier, deps_modifier,
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/core/solve.py", line 157, in solve_for_diff
        final_precs = self.solve_final_state(update_modifier, deps_modifier, prune, ignore_pinned,
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/core/solve.py", line 262, in solve_final_state
        ssc = self._collect_all_metadata(ssc)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/common/io.py", line 88, in decorated
        return f(*args, **kwds)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/core/solve.py", line 397, in _collect_all_metadata
        _supplement_index_with_system(virtual_pkg_index)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/core/index.py", line 159, in _supplement_index_with_system
        cuda_version = context.cuda_version
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/auxlib/decorators.py", line 268, in new_fget
        cache[inner_attname] = func(self)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/common/decorators.py", line 20, in wrapper
        return func(*args, **kwargs)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/base/context.py", line 850, in cuda_version
        return cuda_detect()
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/common/cuda.py", line 37, in cuda_detect
        import ctypes
      File "/Users/user1/miniconda3/lib/python3.8/ctypes/__init__.py", line 7, in <module>
        from _ctypes import Union, Structure, Array
    ImportError: dlopen(/Users/user1/miniconda3/lib/python3.8/lib-dynload/_ctypes.cpython-38-darwin.so, 0x0002): Library not loaded: @rpath/libffi.7.dylib
      Referenced from: /Users/user1/miniconda3/lib/python3.8/lib-dynload/_ctypes.cpython-38-darwin.so
      Reason: tried: '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/python3.8/lib-dynload/../../libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/python3.8/lib-dynload/../../libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/bin/../lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/bin/../lib/libffi.7.dylib' (no such file), '/usr/local/lib/libffi.7.dylib' (no such file), '/usr/lib/libffi.7.dylib' (no such file)

</code>```

Are these errors related? What could be causing this type of error.  If I install from source (setup.py) the module will install but I'll get an error about a circular import. I've tried installing with sudo, for example using:

```<code>sudo -H pip install bat-country

</code>```

but that doesn't work. If I activate a conda environment I can install with pip within it but I also get the circular import error. conda install does not work from within an environment. Is there anyway to debug this?

答:
I think this may have been an apple silicon issue. I was able to fix the particular error by doing a search for libffi.7.dylib and adding the enclosing folder to package directories using "conda config --file < path to .condarc > --add pkgs_dirs < path to libffi.7.dylib enclosing folder >" or also by coping the contents of the enclosing folder to one of the directories conda said it searched in the error message. This, however, did not fix the numerous other install and import errors I was having. The solution was to download MiniForge from here: (https://github.com/conda-forge/miniforge)and running

chmod +x ~/Downloads/Miniforge3-MacOSX-arm64.sh

sh ~/Downloads/Miniforge3-MacOSX-arm64.sh

source ~/miniforge3/bin/activate

Body:
Whenever I try to install a package with pip or pip3 I get an error that starts with:

DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621

and ends with:

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [1 lines of output]
      error in decorator setup command: use_2to3 is invalid.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

using Conda I get the error:

ImportError: dlopen(/Users/user1/miniconda3/lib/python3.8/lib-dynload/_ctypes.cpython-38-darwin.so, 0x0002): Library not loaded: @rpath/libffi.7.dylib
  Referenced from: /Users/user1/miniconda3/lib/python3.8/lib-dynload/_ctypes.cpython-38-darwin.so
  Reason: tried: '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/python3.8/lib-dynload/../../libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/python3.8/lib-dynload/../../libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/bin/../lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/bin/../lib/libffi.7.dylib' (no such file), '/usr/local/lib/libffi.7.dylib' (no such file), '/usr/lib/libffi.7.dylib' (no such file)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/exceptions.py", line 1212, in print_unexpected_error_report
    message_builder.append(get_main_info_str(error_report['conda_info']))
  File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/cli/main_info.py", line 237, in get_main_info_str
    info_dict['_' + key] = ('\n' + 26 * ' ').join(info_dict[key])
KeyError: 'pkgs_dirs'

# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<

    Traceback (most recent call last):
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/exceptions.py", line 1080, in __call__
        return func(*args, **kwargs)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/cli/main.py", line 84, in _main
        exit_code = do_call(args, p)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/cli/conda_argparse.py", line 83, in do_call
        return getattr(module, func_name)(args, parser)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/cli/main_install.py", line 20, in execute
        install(args, parser, 'install')
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/cli/install.py", line 259, in install
        unlink_link_transaction = solver.solve_for_transaction(
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/core/solve.py", line 114, in solve_for_transaction
        unlink_precs, link_precs = self.solve_for_diff(update_modifier, deps_modifier,
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/core/solve.py", line 157, in solve_for_diff
        final_precs = self.solve_final_state(update_modifier, deps_modifier, prune, ignore_pinned,
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/core/solve.py", line 262, in solve_final_state
        ssc = self._collect_all_metadata(ssc)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/common/io.py", line 88, in decorated
        return f(*args, **kwds)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/core/solve.py", line 397, in _collect_all_metadata
        _supplement_index_with_system(virtual_pkg_index)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/core/index.py", line 159, in _supplement_index_with_system
        cuda_version = context.cuda_version
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/auxlib/decorators.py", line 268, in new_fget
        cache[inner_attname] = func(self)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/common/decorators.py", line 20, in wrapper
        return func(*args, **kwargs)
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/base/context.py", line 850, in cuda_version
        return cuda_detect()
      File "/Users/user1/miniconda3/lib/python3.8/site-packages/conda/common/cuda.py", line 37, in cuda_detect
        import ctypes
      File "/Users/user1/miniconda3/lib/python3.8/ctypes/__init__.py", line 7, in <module>
        from _ctypes import Union, Structure, Array
    ImportError: dlopen(/Users/user1/miniconda3/lib/python3.8/lib-dynload/_ctypes.cpython-38-darwin.so, 0x0002): Library not loaded: @rpath/libffi.7.dylib
      Referenced from: /Users/user1/miniconda3/lib/python3.8/lib-dynload/_ctypes.cpython-38-darwin.so
      Reason: tried: '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/python3.8/lib-dynload/../../libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/python3.8/lib-dynload/../../libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/bin/../lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/lib/libffi.7.dylib' (no such file), '/Users/user1/miniconda3/bin/../lib/libffi.7.dylib' (no such file), '/usr/local/lib/libffi.7.dylib' (no such file), '/usr/lib/libffi.7.dylib' (no such file)

Are these errors related? What could be causing this type of error.  If I install from source (setup.py) the module will install but I'll get an error about a circular import. I've tried installing with sudo, for example using:

sudo -H pip install bat-country

but that doesn't work. If I activate a conda environment I can install with pip within it but I also get the circular import error. conda install does not work from within an environment. Is there anyway to debug this?


问:
I am new, trying to roll 3d6, rerolling 1's, and put them into a list. I cant seem to get 3 "new" values in the list. The numbers just keep adding up
```<code>import random

my_stats = []

stat = 0

while len(my_stats) < 3:
    for i in range(1,4):                # generates a num (d6) but no 1's
        number = (random.randint(1, 6))
        while number == 1:
            number = (random.randint(1, 6))
        else:
            stat += number          # sums the 3 rolls into stat

    my_stats.append(stat)

print(my_stats)
</code>```

I am not sure how to get 3 distinct entries in my list, just keeps adding up.

答:
You never reset stat.

Try moving its initialization into the loop, e.g.

while len(my_stats) < 3:
    stat = 0
    for i in range(1,4):
        # ...
```

Body:
import random

my_stats = []

stat = 0

while len(my_stats) < 3:
    for i in range(1,4):                # generates a num (d6) but no 1's
        number = (random.randint(1, 6))
        while number == 1:
            number = (random.randint(1, 6))
        else:
            stat += number          # sums the 3 rolls into stat

    my_stats.append(stat)

print(my_stats)

I am not sure how to get 3 distinct entries in my list, just keeps adding up.


问:
Way to get image URL from the image hash ID of a Facebook Ad
Is there any way to use the Facebook API (or other method) to get the image URL for my ad images? I have a list of image hashes, but how can I get their URLs?

Alternatively, is there another way to get the URL of my ad images without relying on the hash? I am trying to download them all systematically.

答:
Yes! Get the permalink_url of an image using the /adimages edge off the adaccount node. You can also return the hash value and filter the query by a list of specific hashes:

```<code>https://graph.facebook.com/v13/act_<AD_ACCOUNT_ID>/adimages?
    fields=id,permalink_url,
    hash&hashes=["<IMAGE_HASH_1>","<IMAGE_HASH_2>"]
</code>```

This returns:

```<code>{
  "data": [
    {
      "id": "<AD_IMAGE_ID>",
      "permalink_url": "https://www.facebook.com/ads/image/?d=<UNIQUE_NUMBER>",
      "hash": "<IMAGE_HASH_1>"
    },
    {
      "id": "<AD_IMAGE_ID>",
      "permalink_url": "https://www.facebook.com/ads/image/?d=<UNIQUE_NUMBER>",
      "hash": "<IMAGE_HASH_2>"
    },
  ],
  "paging": {
    "cursors": {
      "before": "<VALUE>",
      "after": "<VALUE>"
    }
  }
}
</code>```

Body:
Yes! Get the permalink_url of an image using the /adimages edge off the adaccount node. You can also return the hash value and filter the query by a list of specific hashes:

https://graph.facebook.com/v13/act_<AD_ACCOUNT_ID>/adimages?
    fields=id,permalink_url,
    hash&hashes=["<IMAGE_HASH_1>","<IMAGE_HASH_2>"]

This returns:

{
  "data": [
    {
      "id": "<AD_IMAGE_ID>",
      "permalink_url": "https://www.facebook.com/ads/image/?d=<UNIQUE_NUMBER>",
      "hash": "<IMAGE_HASH_1>"
    },
    {
      "id": "<AD_IMAGE_ID>",
      "permalink_url": "https://www.facebook.com/ads/image/?d=<UNIQUE_NUMBER>",
      "hash": "<IMAGE_HASH_2>"
    },
  ],
  "paging": {
    "cursors": {
      "before": "<VALUE>",
      "after": "<VALUE>"
    }
  }
}


问:
IntrinsicAttributes props in React Typescript component
Hello I have this message alert:

The type '{ children: string; notify: string; }' cannot be assigned to
type 'IntrinsicAttributes & { notify: any; }'.   Property 'children'
does not exist on type 'IntrinsicAttributes & { notify: any;
}'.ts(2322)

using Card component. This is the first time I get it.

this is the component:

```<code>const Card = (props:{notify:any}) => {

  if (props.notify.length> 0> 0){
    return <IonIcon icon={notifications}  id="iconoHomeCampana">  </IonIcon>

  }else{
    return <IonIcon icon={notificationsOff}  id="iconoHomeCampana">  </IonIcon>
  }
}

export interface newMessage{
  de:string
  ticket:string
}

const App= () => {

  const [notifications, setNotifications] =  useState < newMessage []> ( [])

  useEffect(() => {

  axios.get(url+"chatsinleer/"+props.email).then((resp: { data: any; }) => {
      if (resp.data!="bad"){
        setNotifications(resp.data.map((d: { de: any; ticket: any; }) => ({
          de:d.de,
          ticket:d.ticket,
          })));
      }
    })

  }, []);

return (
      <IonPage >
        <IonHeader>
          <IonToolbar>
            <IonGrid>
              <IonRow id="header">
                <IonCol id="columna" size="1.5"><IonButtons ><IonMenuButton /> </IonButtons></IonCol>
                <IonCol id="columna2" ><Busqueda categorias={categorias} setCategorias={setCategorias} setProveedorBuscadoHook={setProveedorBuscadoHook} setBuscar={setBuscar} /></IonCol>
                <IonCol id="columna3" size="1.5">
                  <Card notify={notifications}>  </Card>
                </IonCol>
              </IonRow>
            </IonGrid>
          </IonToolbar>
        </IonHeader>
    )
}
</code>```

答:
The answer:

<Card> </Card> is the same as <Card>{" "}</Card> which means you are sending a space as a child of that component. Replace it for <Card {...props} /> and that will solve your problem as there is no children nodes.

The explanation:

JSX Docs:

JSX removes whitespace at the beginning and ending of a line. It also removes blank lines. New lines adjacent to tags are removed; new lines that occur in the middle of string literals are condensed into a single space.

And this issue.

Basically, spaces are considered meaningful in JSX, so avoiding them when not needed it's a good practice.

More nerdy stuff:

JSX.IntrinsicAttributes it's an interface that allows you to globally extend the attributes of JSX nodes, for example, key in React.

React does not include the children prop in IntrinsicAttributes so, when a component needs to render children it is necessary to explicitly add it to the props type definition.

More info here

Body:
Hello I have this message alert:

The type '{ children: string; notify: string; }' cannot be assigned to
type 'IntrinsicAttributes & { notify: any; }'.   Property 'children'
does not exist on type 'IntrinsicAttributes & { notify: any;
}'.ts(2322)

using Card component. This is the first time I get it.

this is the component:

const Card = (props:{notify:any}) => {

  if (props.notify.length> 0> 0){
    return <IonIcon icon={notifications}  id="iconoHomeCampana">  </IonIcon>

  }else{
    return <IonIcon icon={notificationsOff}  id="iconoHomeCampana">  </IonIcon>
  }
}

export interface newMessage{
  de:string
  ticket:string
}

const App= () => {

  const [notifications, setNotifications] =  useState < newMessage []> ( [])

  useEffect(() => {

  axios.get(url+"chatsinleer/"+props.email).then((resp: { data: any; }) => {
      if (resp.data!="bad"){
        setNotifications(resp.data.map((d: { de: any; ticket: any; }) => ({
          de:d.de,
          ticket:d.ticket,
          })));
      }
    })

  }, []);

return (
      <IonPage >
        <IonHeader>
          <IonToolbar>
            <IonGrid>
              <IonRow id="header">
                <IonCol id="columna" size="1.5"><IonButtons ><IonMenuButton /> </IonButtons></IonCol>
                <IonCol id="columna2" ><Busqueda categorias={categorias} setCategorias={setCategorias} setProveedorBuscadoHook={setProveedorBuscadoHook} setBuscar={setBuscar} /></IonCol>
                <IonCol id="columna3" size="1.5">
                  <Card notify={notifications}>  </Card>
                </IonCol>
              </IonRow>
            </IonGrid>
          </IonToolbar>
        </IonHeader>
    )
}


问:
Showing Result returned in a Carousel RecyclerView (Kotlin)
I have a rotating carousel (using carouselrecyclerview) to rotate a list of images around.

The user can call a second activity and then search the images, and then return the selected image’s ID back to the MainActivity.kt.

The MainActivity.kt receives the result  (using intent) in the onActivityResult.
I then need to call scrollToPosition (from the carouselLayoutManager) to move the carousel to the position that was selected in the second activity.

As the call to the carouselLayoutManager is within the onCreate, I can’t call it from the onActivityResult? I have tried moving the onActivityResult to within the onCreate, but then the onActivityResult is not called when returning from the second activity.

So, how can I call the code which is within the onCreate from the onActivityResult please?

Any help really appreciated as I’m struggling on this.

MainActivity.kt
...

```<code> override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val carouselRecyclerview = findViewById<CarouselRecyclerview>(R.id.recycler)
    val list = ArrayList<DataModel>()
    // Load the images of the Veg
    for (mycount in 0..41) {
        list.add(DataModel(VegName[mycount].image, VegName[mycount].name))
    }
    val adapter = DataAdapter(list)
    carouselRecyclerview.adapter = adapter
    val carouselLayoutManager = carouselRecyclerview.getCarouselLayoutManager()
    carouselLayoutManager.scrollToPosition(1)
    carouselRecyclerview.setItemSelectListener(object : CarouselLayoutManager.OnSelected {
        override fun onItemSelected(position: Int) {
            var ShowIt = findViewById(R.id.textVegName) as TextView
            //Cente item
            ShowIt.text = list[position].text

        }
    })
    Searchbutton.setOnClickListener {
        val intent = Intent(this, SearchActivity::class.java)
        startActivityForResult(intent, SEARCH_ACTIVITY_REQUEST_CODE)
   }

   // Move the carousel to the  position received - THIS ISN'T CALLED?
   fun setthelocation(SetThisPlace: Int ) {
        carouselLayoutManager.scrollToPosition(SetThisPlace)
   }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == SEARCH_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            val returnedfrom = VegName.find{ it.name == data?.getStringExtra("result") }

            if (returnedfrom==null)
                Toast.makeText(applicationContext, "Did not find the result returned!", Toast.LENGTH_LONG).show()
            else {
                Toast.makeText(applicationContext, "Got = " + returnedfrom.id, Toast.LENGTH_LONG).show()
                //Need to call eiter setthelocation() or carouselLayoutManager.scrollToPosition???
                return
            }
        }
    }
}
</code>```

答:
As the call to the carouselLayoutManager is within the onCreate, I can’t call it from the onActivityResult?

I think you're confusing terms. There is no "call to the carouselLayoutManager" - that's a variable to assign to an object, not a function you call.

I have tried moving the onActivityResult to within the onCreate, but then the onActivityResult is not called when returning from the second activity.

onActivityResult is a base-class method that is invoked for you when you use startActivityForResult and close the opened activity. If you "move it to within the onCreate" all you're doing is calling the base class implementation (which does nothing).

So, how can I call the code which is within the onCreate from the onActivityResult please?

The easiest solution would be to hold on to the layout manager as a variable you can use in either onCreate or onActivityResult:

```<code>// Class-level property you can use in either function
private lateinit var carouselLayoutManager: LayoutManager

override fun onCreate(...) {
    // Replace local val with class-level property

    // Instead of this:
    // val carouselLayoutManager = carouselRecyclerview.getCarouselLayoutManager()

    // Do this: initialize member property to use here and in onActivityResult
    carouselLayoutManager = carouselRecyclerview.getCarouselLayoutManager()
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == SEARCH_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            val returnedfrom = VegName.find{ it.name == data?.getStringExtra("result") }

            if (returnedfrom==null)
                Toast.makeText(applicationContext, "Did not find the result returned!", Toast.LENGTH_LONG).show()
            else {
                Toast.makeText(applicationContext, "Got = " + returnedfrom.id, Toast.LENGTH_LONG).show()
                //Need to call eiter setthelocation() or carouselLayoutManager.scrollToPosition???

                // Now you can call this since it's a member property
                carouselLayoutManager.scrollToPosition(...)
                return
            }
        }
    }
}
</code>```

Body:
I have a rotating carousel (using carouselrecyclerview) to rotate a list of images around.

The user can call a second activity and then search the images, and then return the selected image’s ID back to the MainActivity.kt.

The MainActivity.kt receives the result  (using intent) in the onActivityResult.
I then need to call scrollToPosition (from the carouselLayoutManager) to move the carousel to the position that was selected in the second activity.

As the call to the carouselLayoutManager is within the onCreate, I can’t call it from the onActivityResult? I have tried moving the onActivityResult to within the onCreate, but then the onActivityResult is not called when returning from the second activity.

So, how can I call the code which is within the onCreate from the onActivityResult please?

Any help really appreciated as I’m struggling on this.

MainActivity.kt
...

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val carouselRecyclerview = findViewById<CarouselRecyclerview>(R.id.recycler)
    val list = ArrayList<DataModel>()
    // Load the images of the Veg
    for (mycount in 0..41) {
        list.add(DataModel(VegName[mycount].image, VegName[mycount].name))
    }
    val adapter = DataAdapter(list)
    carouselRecyclerview.adapter = adapter
    val carouselLayoutManager = carouselRecyclerview.getCarouselLayoutManager()
    carouselLayoutManager.scrollToPosition(1)
    carouselRecyclerview.setItemSelectListener(object : CarouselLayoutManager.OnSelected {
        override fun onItemSelected(position: Int) {
            var ShowIt = findViewById(R.id.textVegName) as TextView
            //Cente item
            ShowIt.text = list[position].text

        }
    })
    Searchbutton.setOnClickListener {
        val intent = Intent(this, SearchActivity::class.java)
        startActivityForResult(intent, SEARCH_ACTIVITY_REQUEST_CODE)
   }

   // Move the carousel to the  position received - THIS ISN'T CALLED?
   fun setthelocation(SetThisPlace: Int ) {
        carouselLayoutManager.scrollToPosition(SetThisPlace)
   }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == SEARCH_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            val returnedfrom = VegName.find{ it.name == data?.getStringExtra("result") }

            if (returnedfrom==null)
                Toast.makeText(applicationContext, "Did not find the result returned!", Toast.LENGTH_LONG).show()
            else {
                Toast.makeText(applicationContext, "Got = " + returnedfrom.id, Toast.LENGTH_LONG).show()
                //Need to call eiter setthelocation() or carouselLayoutManager.scrollToPosition???
                return
            }
        }
    }
}

Body:
As the call to the carouselLayoutManager is within the onCreate, I can’t call it from the onActivityResult?

I think you're confusing terms. There is no "call to the carouselLayoutManager" - that's a variable to assign to an object, not a function you call.

I have tried moving the onActivityResult to within the onCreate, but then the onActivityResult is not called when returning from the second activity.

onActivityResult is a base-class method that is invoked for you when you use startActivityForResult and close the opened activity. If you "move it to within the onCreate" all you're doing is calling the base class implementation (which does nothing).

So, how can I call the code which is within the onCreate from the onActivityResult please?

The easiest solution would be to hold on to the layout manager as a variable you can use in either onCreate or onActivityResult:

// Class-level property you can use in either function
private lateinit var carouselLayoutManager: LayoutManager

override fun onCreate(...) {
    // Replace local val with class-level property

    // Instead of this:
    // val carouselLayoutManager = carouselRecyclerview.getCarouselLayoutManager()

    // Do this: initialize member property to use here and in onActivityResult
    carouselLayoutManager = carouselRecyclerview.getCarouselLayoutManager()
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == SEARCH_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            val returnedfrom = VegName.find{ it.name == data?.getStringExtra("result") }

            if (returnedfrom==null)
                Toast.makeText(applicationContext, "Did not find the result returned!", Toast.LENGTH_LONG).show()
            else {
                Toast.makeText(applicationContext, "Got = " + returnedfrom.id, Toast.LENGTH_LONG).show()
                //Need to call eiter setthelocation() or carouselLayoutManager.scrollToPosition???

                // Now you can call this since it's a member property
                carouselLayoutManager.scrollToPosition(...)
                return
            }
        }
    }
}


问:
Is there a way to hide specific indicator values from the data window?
I have recently created a script that plots several different indicators on a chart in TradingView. Under specific scenarios, some of the indicators are not active and show "n/a" in the data window.

I know that TradingView allows us to hide all indicator values. I would like to customize which indicator values are visible. Is this possible? Thanks for your time.

答:
Plotting with color "na" will hide the plot from chart and would still show in the data window.

```<code>showPlot = input.bool(true)
plot(avg, color=showPlot?color.blue:na)
</code>```

Source:
https://www.tradingview.com/pine-script-docs/en/v5/concepts/Plots.html

Body:
Plotting with color "na" will hide the plot from chart and would still show in the data window.

showPlot = input.bool(true)
plot(avg, color=showPlot?color.blue:na)

Source:
https://www.tradingview.com/pine-script-docs/en/v5/concepts/Plots.html


问:
How can I collate values from a hashtable and turn them into percentages?
In PowerShell, I am generating hashtables where the value of a key is an integer, but this needs to be converted into a percentage with respect to the other key-value pairs. Consider the following hashtable:

There are a total of 4 key-value pairs here. However, only QuestionSet1ARL has a value of something other than 0. I therefore want to report that QuestionSet1ARL has a value of 100%. Below is a slightly different example:

Here, both QuestionSetTrust and QuestionSet4 have values of 5. They therefore makeup 50% of the values in the hashtable. If the value of QuestionSetTrust was 2 and QuestionSet4 was 1, the percentages would be 66% and 33% respectively.

I think Ill need to create a secondary hashtable (enabledSurveys) to do this (one that only contains the key-value pairs where the value was greater than 0. To do this, I have written a simple loop:

```<code>foreach ($survey in $initialSurveys.Keys) {
        # Set the ratio variable equal to the value from the hashtable. For ease of reading.
        $surveyRatio = $initialSurveys.$survey
        if ($surveyRatio -gt 0) {
            $enabledSurveys.add($survey, $surveyRatio)
        }
    }
</code>```

I think I then need to sum the values to achieve a total, and then derive contributedTotal from each of the keys. Before I continue, is there a more intuitive way to derive this information without the need for a second hashtable?

Optimal outcome:

答:
A total sum of the values is needed in order to determine percentage.</p>
```<code>$InitialSurveys = @{
    'QuestionSetTrust' = 1
    'QuestionSet4' = 5
}
$Total = 0
foreach ($Key in $InitialSurveys.Keys) {
    $Total += $InitialSurveys[$Key]
}
$ResultHash = @{}
foreach ($Key in $InitialSurveys.Keys) {
    $ResultHash[$Key] = "{0}%" -f "$([math]::Round(($InitialSurveys[$Key] / $Total * 100.0), 2))"
}
$ResultHash
</code>```

Body:
In PowerShell, I am generating hashtables where the value of a key is an integer, but this needs to be converted into a percentage with respect to the other key-value pairs. Consider the following hashtable:

There are a total of 4 key-value pairs here. However, only QuestionSet1ARL has a value of something other than 0. I therefore want to report that QuestionSet1ARL has a value of 100%. Below is a slightly different example:

Here, both QuestionSetTrust and QuestionSet4 have values of 5. They therefore makeup 50% of the values in the hashtable. If the value of QuestionSetTrust was 2 and QuestionSet4 was 1, the percentages would be 66% and 33% respectively.

I think Ill need to create a secondary hashtable (enabledSurveys) to do this (one that only contains the key-value pairs where the value was greater than 0. To do this, I have written a simple loop:

foreach ($survey in $initialSurveys.Keys) {
        # Set the ratio variable equal to the value from the hashtable. For ease of reading.
        $surveyRatio = $initialSurveys.$survey
        if ($surveyRatio -gt 0) {
            $enabledSurveys.add($survey, $surveyRatio)
        }
    }

I think I then need to sum the values to achieve a total, and then derive contributedTotal from each of the keys. Before I continue, is there a more intuitive way to derive this information without the need for a second hashtable?

Optimal outcome:

Body:
A total sum of the values is needed in order to determine percentage.

$InitialSurveys = @{
    'QuestionSetTrust' = 1
    'QuestionSet4' = 5
}
$Total = 0
foreach ($Key in $InitialSurveys.Keys) {
    $Total += $InitialSurveys[$Key]
}
$ResultHash = @{}
foreach ($Key in $InitialSurveys.Keys) {
    $ResultHash[$Key] = "{0}%" -f "$([math]::Round(($InitialSurveys[$Key] / $Total * 100.0), 2))"
}
$ResultHash


问:
How to implement retry with requests library
So i have this bit of code

```<code>statssession = requests.Session()
getstats = statssession.get('https://api.hypixel.net/player',
                                                params={'key': random.choice([key, key2]), 'uuid': playeruuid},
                                                timeout=10).json()
</code>```

I'm completely new to python with no OOP experience and this bit of code throws a random time out exception for read randomly. What I want is when it throws that exception to not just break my code but retry the request instead preferably with the library from requests itself but I have no idea how to do it so here I'm asking, any help appreciated.

答:
It looks like you're using the API incorrectly: https://api.hypixel.net/#section/Authentication/ApiKey

Try setting the key into the requests.Session headers:

statssession = requests.Session()
statssession.headers["API-Key"] = random.choice([key, key2])
```
<p>To try again after timeout, you can use a <code>try except</code> block:</p>
<pre class="lang-py prettyprint-override"><code>for _ in range(5):
    try:
        getstats = statssession.get(
            'https://api.hypixel.net/player',
            params = {'uuid': playeruuid},
            timeout=10).json()
        break
    except requests.exceptions.ReadTimeout:
        continue
</code>```

Or you can set retries within urllib3, used by requests, as outlined here: Can I set max_retries for requests.request?

Body:
So i have this bit of code

statssession = requests.Session()
getstats = statssession.get('https://api.hypixel.net/player',
                                                params={'key': random.choice([key, key2]), 'uuid': playeruuid},
                                                timeout=10).json()

I'm completely new to python with no OOP experience and this bit of code throws a random time out exception for read randomly. What I want is when it throws that exception to not just break my code but retry the request instead preferably with the library from requests itself but I have no idea how to do it so here I'm asking, any help appreciated.

Body:
It looks like you're using the API incorrectly: https://api.hypixel.net/#section/Authentication/ApiKey

Try setting the key into the requests.Session headers:

statssession = requests.Session()
statssession.headers["API-Key"] = random.choice([key, key2])

To try again after timeout, you can use a try except block:

for _ in range(5):
    try:
        getstats = statssession.get(
            'https://api.hypixel.net/player',
            params = {'uuid': playeruuid},
            timeout=10).json()
        break
    except requests.exceptions.ReadTimeout:
        continue

Or you can set retries within urllib3, used by requests, as outlined here: Can I set max_retries for requests.request?


问:
Save image from iPhone camera directly to documents folder and not to camera roll?
I am trying to figure out how to take a image with the iPhone camera and save it directly to the apps document folder, and if possible not in the camera roll.

I have my app showing the camera, and I can save the image to the camera roll, but I want to save it directly to the apps document folder.

Any idea ?

Thanks for the help.

答:
You can try doing this in your - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info method:

```<code>UIImage *pickedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImagePNGRepresentation(pickedImage);

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"imageName.png"];

NSError * error = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&error];

if (error != nil) {
    NSLog(@"Error: %@", error);
    return;
}
</code>```

Let me know if that works for you.

ContentLicense: CC BY-SA 3.0

Body:
You can try doing this in your - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info method:

UIImage *pickedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData *imageData = UIImagePNGRepresentation(pickedImage);

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"imageName.png"];

NSError * error = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&error];

if (error != nil) {
    NSLog(@"Error: %@", error);
    return;
}

Let me know if that works for you.


问:
How do I start a Camel route with autoStartup=false
I want to control when my route starts up using a RoutePolicy. Therefore, I have defined it with autoStartup=false

```<code><camel:route id="myRoute" routePolicyRef="myRoutePolicy" autoStartup="false">
    <!-- details omitted -->
</camel:route>
</code>```

To start the route, I tried:

```<code>public class MyRoutePolicy implements RoutePolicy {

    // Does NOT work!
    @Override
    public void onInit(Route route) {
        if(shouldStartRoute(route)) {
            camelContext.startRoute(route.getId());
        }
    }

    // More stuff omitted
}
</code>```

Unfortunately, nothing happens. The Javadoc for CamelContext.startRoute(String) may explain why:

Starts the given route if it has been previously stopped

How do I start a route that hasn't previously been stopped?

I'm using Camel 2.8.0 and upgrading is not an option.

I can start the route using a JMX console, but I don't want to depend on JMX.

答:
I ran into a similar problem where I was configuring .noAutoStartup(), then later calling context.startRoute(myRouteId), but it wasn't starting.

I found the problem for me was that I needed to first call context.start(), since it initializes some state inside the CamelContext which will make the subsequent startRoute call actually work.

Body:
I want to control when my route starts up using a RoutePolicy. Therefore, I have defined it with autoStartup=false

<camel:route id="myRoute" routePolicyRef="myRoutePolicy" autoStartup="false">

</camel:route>

To start the route, I tried:

public class MyRoutePolicy implements RoutePolicy {

    // Does NOT work!
    @Override
    public void onInit(Route route) {
        if(shouldStartRoute(route)) {
            camelContext.startRoute(route.getId());
        }
    }

    // More stuff omitted
}

Unfortunately, nothing happens. The Javadoc for CamelContext.startRoute(String) may explain why:

Starts the given route if it has been previously stopped

How do I start a route that hasn't previously been stopped?

I'm using Camel 2.8.0 and upgrading is not an option.

I can start the route using a JMX console, but I don't want to depend on JMX.


问:
how to compare a date from a csv file with a variable in python
I have a function where I can read out my csv file. In my csv I have the following 2 information. the studentnumber and when the student passed the exam. I need to know which students have passed the exam in less then 4 weeks. How could I compare these 2 with eachother? the dates that I have in my csv file looks something like this: 21-10-2020 15:20

row[0] = studentsname

row[12] = passed date

I have tried doing something like this where I compare row[12] with the end_date but then I get an error message saying this

Error code:

'<' not supported between instances of 'str' and 'datetime.datetime'

My code:

```<code>from datetime import datetime
end_date = datetime(day=5, month=10, year=2020, hour=23, minute=59)
fastStudent = []
allPassedStudents = []
with open("Mycsv_file, 'r') as read_obj:
    csv_dict_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_dict_reader:
        if row[12]:
            allPassedStudents.append(row[0])
            if row[12] < end_date:
                fastStudent.append[row[0]]
                print(fastStudent)
</code>```

答:
That's because row[12] is a str, not datetime.

need to change a type of row[12] to datetime, using datetime.strptime. In this case, you shoud use a format '%d-%m-%Y %H:%M' for '21-10-2020 15:20', for example.

fastStudent.append[row[0]] -> need to be changed to fastStudent.append(row[0]).

import csv
from datetime import datetime
end_date = datetime(day=5, month=10, year=2020, hour=23, minute=59)
fastStudent = []
allPassedStudents = []
with open("Mycsv_file", 'r') as read_obj:
    csv_dict_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_dict_reader:
        print(row)
        passedDate = datetime.strptime(row[12], '%d-%m-%Y %H:%M') # to convert a type of row[12] to datetime type, to enable it comparable!
        if passedDate:
            allPassedStudents.append(row[0])
            if passedDate < end_date:
                fastStudent.append(row[0]) # -> I changed [] to ()
                print(fastStudent)
                # ['Tommy'] (for exmample)
```

Body:
I have a function where I can read out my csv file. In my csv I have the following 2 information. the studentnumber and when the student passed the exam. I need to know which students have passed the exam in less then 4 weeks. How could I compare these 2 with eachother? the dates that I have in my csv file looks something like this: 21-10-2020 15:20

row[0] = studentsname

row[12] = passed date

I have tried doing something like this where I compare row[12] with the end_date but then I get an error message saying this

Error code:

'<' not supported between instances of 'str' and 'datetime.datetime'

My code:

from datetime import datetime
end_date = datetime(day=5, month=10, year=2020, hour=23, minute=59)
fastStudent = []
allPassedStudents = []
with open("Mycsv_file, 'r') as read_obj:
    csv_dict_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_dict_reader:
        if row[12]:
            allPassedStudents.append(row[0])
            if row[12] < end_date:
                fastStudent.append[row[0]]
                print(fastStudent)


问:
Angular 12 .Net 6 value null being passed to api as "null"
I have an angular 12 UI that is communicating with a .net 6 API. When a parameter in a query string is null or undefined the API is interpreting it as a string value of "null" or "undefined". Relevant code below

angular code:

```<code>getDummyUser(type: string, testId: string):
Observable<UserDto> {
var url = `api/users/get-dummy-user?type=${encodeURIComponent(type)}&testId=${encodeURIComponent(testId)}`;
return this.httpClient.get<any>(url)
  .pipe(
    finalize(() =>
      this.hideLoadingIndicators()
    ),
    catchError(err => {
      return throwError(err);
    })
  );
</code>```

}

.net 6 api parameter signature

```<code>[HttpGet]
    [Route("get-dummy-user")]
    public async Task<IActionResult> GetDummyUser
        (
        string type,
        string testId
        )
</code>```

I have tried using the [FromQuery] attribute but the result is the same. I also cannot send '' from the angular app as the API will then throw a 400 error (bad request). Has anyone had any experience in this? Thanks in advance

答:
```<code>export interface IGetDummy{
type: string;
testId?: string;
</code>```
<p>}</p>
```<code>   sendingParams=[
//what u send as parameter to thi Api
]

 getDummyUser(params:Params):{

    return this.http.get<IGetDummy>(url,{observe:'response', sendingParams})
      .pipe(
        finalize(()=>{
          this.hideLoadingIndicators();
        },catchError(err => {
  return throwError(err);
      )

}
</code>```

Body:
I have an angular 12 UI that is communicating with a .net 6 API. When a parameter in a query string is null or undefined the API is interpreting it as a string value of "null" or "undefined". Relevant code below

angular code:

getDummyUser(type: string, testId: string):
Observable<UserDto> {
var url = `api/users/get-dummy-user?type=${encodeURIComponent(type)}&testId=${encodeURIComponent(testId)}`;
return this.httpClient.get<any>(url)
  .pipe(
    finalize(() =>
      this.hideLoadingIndicators()
    ),
    catchError(err => {
      return throwError(err);
    })
  );

}

.net 6 api parameter signature

[HttpGet]
    [Route("get-dummy-user")]
    public async Task<IActionResult> GetDummyUser
        (
        string type,
        string testId
        )

I have tried using the [FromQuery] attribute but the result is the same. I also cannot send '' from the angular app as the API will then throw a 400 error (bad request). Has anyone had any experience in this? Thanks in advance

Body:
export interface IGetDummy{
type: string;
testId?: string;

}

   sendingParams=[
//what u send as parameter to thi Api
]

 getDummyUser(params:Params):{

    return this.http.get<IGetDummy>(url,{observe:'response', sendingParams})
      .pipe(
        finalize(()=>{
          this.hideLoadingIndicators();
        },catchError(err => {
  return throwError(err);
      )

}


问:
Write a function any(s1, s2) that returns the first location in the string s1 where any character in a string s2 occurs
```<code>/* Program to return first location in the string s1 where any charater in a string s2 occurs or -1 if s1 does not contain any character in s2 */

#include<stdio.h>
#include<limits.h>

int main(void)
{
    char s1 [] = "This is fun";
    char s2 [] = "fin";
    int loc = theF(s1, s2);
    printf("%d", loc);
    printf("\n");
    return 0;
}

int theF(char s1 [], char s2 [])
{
    int i = 0;
    int loc = -1;
    while (s1[i] != '\0')
    {
        int j = 0;
        while (s2[j] != '\0')
        {
            if (s2[j] == s1[i])
            {
                loc = (int)s1[i];
                return loc;
            }
            j++;
        }
        i++;
    }
    return loc;
}
</code>```

Write a function any(s1, s2) that returns
the first location in the string s1 where any
character in a string s2 occurs, or -1 if s1 does
not contain any character in s2.
For example, any("This is fun", "fin") returns
2, (‘f ’ occurs in position 8, ‘i’ occurs in 2, and
‘n’ in 10), while any("This is fun", "dead") returns
-1.

Directions ^^

Do you guys see any issues? It's returning 105 when it should be returning 8. I checked ascii table and that would have no correlation to 8 unfortunately D:

答:
This is a much clearer and simpler code from the previous one that I wrote.

so the logic is basically just to check for the first occurrence of the wantbefindloc characters inside yourstring and once found we return the location of the index j as it is the first match of the two characters.

If we loop over the whole characters and nothing already returned, this implies that no matching where found. Thus, we return -1

note that you do not need to update any of the indexes at all and no need to load header files but stdio

```<code>#include<stdio.h>

int any();

int main()
{

    int loc;

    char yourstring[] = "This is fun";
    char wantbefindloc[] = "dead";

    loc = any(yourstring, wantbefindloc);
    printf("%d", loc);

    return 0;
}

int any(char s1[], char s2[])
{
    int i, j;

    for (i = 0 ; s2[i] != '\0'; i++)
    {
        for (j = 0 ; s1[j] != '\0'; j++)
        {
            if (s1[j] == s2[i])
            {
                return j;
            }
        }
    }
    return -1;
}
</code>```

Body:
/* Program to return first location in the string s1 where any charater in a string s2 occurs or -1 if s1 does not contain any character in s2 */

#include<stdio.h>
#include<limits.h>

int main(void)
{
    char s1 [] = "This is fun";
    char s2 [] = "fin";
    int loc = theF(s1, s2);
    printf("%d", loc);
    printf("\n");
    return 0;
}

int theF(char s1 [], char s2 [])
{
    int i = 0;
    int loc = -1;
    while (s1[i] != '\0')
    {
        int j = 0;
        while (s2[j] != '\0')
        {
            if (s2[j] == s1[i])
            {
                loc = (int)s1[i];
                return loc;
            }
            j++;
        }
        i++;
    }
    return loc;
}

Write a function any(s1, s2) that returns
the first location in the string s1 where any
character in a string s2 occurs, or -1 if s1 does
not contain any character in s2.
For example, any("This is fun", "fin") returns
2, (‘f ’ occurs in position 8, ‘i’ occurs in 2, and
‘n’ in 10), while any("This is fun", "dead") returns
-1.

Directions ^^

Do you guys see any issues? It's returning 105 when it should be returning 8. I checked ascii table and that would have no correlation to 8 unfortunately D:

Body:
This is a much clearer and simpler code from the previous one that I wrote.

so the logic is basically just to check for the first occurrence of the wantbefindloc characters inside yourstring and once found we return the location of the index j as it is the first match of the two characters.

If we loop over the whole characters and nothing already returned, this implies that no matching where found. Thus, we return -1

note that you do not need to update any of the indexes at all and no need to load header files but stdio

#include<stdio.h>

int any();

int main()
{

    int loc;

    char yourstring[] = "This is fun";
    char wantbefindloc[] = "dead";

    loc = any(yourstring, wantbefindloc);
    printf("%d", loc);

    return 0;
}

int any(char s1[], char s2[])
{
    int i, j;

    for (i = 0 ; s2[i] != '\0'; i++)
    {
        for (j = 0 ; s1[j] != '\0'; j++)
        {
            if (s1[j] == s2[i])
            {
                return j;
            }
        }
    }
    return -1;
}


问:
Android - How to start creating a launcher app?
I am going to start my new app which is going to be a Home Replacement.
I have been through the example provided by google. but i am still little bit confused.

like
Where should i start?
Should i create a normal activity by extending an Activity class then just set the background image(wallpaper) and use a grid view to show all applications?

How to make Android to treat my app as a launcher process?

so many question running in my mind and please don't advise me to go through Android Launcher because it has almost more than 100 classes and what i need is just a simple start after that i know what i want from my app.

答:
I'm not sure if I understood your question correctly, but are you looking for a startup animation of some sort? If so, check this out.

How to implement application startup animation in android


答:
Your code currently rolls a die 3 times, adding the results if the roll is not 1, otherwise rerolling the die pointlessly (as the value is never used). The summed value is then appended to a list and you repeat the process, but without resetting the sum to 0 first. So it contains at least 2 errors (as ignoring the 1 and not using the reroll  doesn't appear to be what you want)

I think this is what you were after:

```<code>import random

my_stats = []

stat = 0

while len(my_stats) < 3:
    # you'd want to restart the count every time
    stat = 0
    # you'll need to keep track of the number of good rolls, can roll any number of 1's
    good_rolls = 0
    while good_rolls < 3:
        number = (random.randint(1, 6))
        if number != 1:
            stat += number          # sums the 3 rolls into stat
            good_rolls += 1

    my_stats.append(stat)

print(my_stats)
</code>```

Title: I am new, trying to roll 3d6, rerolling 1's, and put them into a list. I cant seem to get 3 "new" values in the list. The numbers just keep adding up

Body:
import random

my_stats = []

stat = 0

while len(my_stats) < 3:
    for i in range(1,4):                # generates a num (d6) but no 1's
        number = (random.randint(1, 6))
        while number == 1:
            number = (random.randint(1, 6))
        else:
            stat += number          # sums the 3 rolls into stat

    my_stats.append(stat)

print(my_stats)

I am not sure how to get 3 distinct entries in my list, just keeps adding up.

Body:
Your code currently rolls a die 3 times, adding the results if the roll is not 1, otherwise rerolling the die pointlessly (as the value is never used). The summed value is then appended to a list and you repeat the process, but without resetting the sum to 0 first. So it contains at least 2 errors (as ignoring the 1 and not using the reroll  doesn't appear to be what you want)

I think this is what you were after:

import random

my_stats = []

stat = 0

while len(my_stats) < 3:
    # you'd want to restart the count every time
    stat = 0
    # you'll need to keep track of the number of good rolls, can roll any number of 1's
    good_rolls = 0
    while good_rolls < 3:
        number = (random.randint(1, 6))
        if number != 1:
            stat += number          # sums the 3 rolls into stat
            good_rolls += 1

    my_stats.append(stat)

print(my_stats)


问:
C++ turning string into char and making it unable to compare to another string
```<code>void split_to_array(string sentence, string splitter)
{
    int index = 0;
    int last_index = sentence.find(splitter);

    int array_amount = 0;

    for (int i = 0; i < sentence.size(); i++) {
        cout << sentence[i] << endl;
        if (sentence[i] == splitter) array_amount++;
    }
}

int main()
{

    split_to_array("fdsfds fdsfds vcxvcx fdsafdsa", " ");

}
</code>```

I am trying to get the length of the array by finding the splitter argument in the string, However when I try to compare the index of the string with the splitter I get an error that I cannot compare a char with a string which is the first issue I have. When I try to turn it  into a string by using std::to_string I get a number back instead of the actual string.

答:
You cannot do this

```<code>if(sentence[i] == splitter)
</code>```

sentence[i] is a single character. splitter is a string.

I would fix it by passing a char argement for splitter. ie

```<code>void split_to_array(string sentence, char splitter)
</code>```

and

```<code> split_to_array("fdsfds fdsfds vcxvcx fdsafdsa", ' ');
</code>```

if you want to keep the same function signatures for some reasons then do

```<code> if(sentence[i] == splitter[0])
</code>```

ie compare against the first (and only) characer in splitter. This is however a very odd thing to do.

Body:
void split_to_array(string sentence, string splitter)
{
    int index = 0;
    int last_index = sentence.find(splitter);

    int array_amount = 0;

    for (int i = 0; i < sentence.size(); i++) {
        cout << sentence[i] << endl;
        if (sentence[i] == splitter) array_amount++;
    }
}

int main()
{

    split_to_array("fdsfds fdsfds vcxvcx fdsafdsa", " ");

}

I am trying to get the length of the array by finding the splitter argument in the string, However when I try to compare the index of the string with the splitter I get an error that I cannot compare a char with a string which is the first issue I have. When I try to turn it  into a string by using std::to_string I get a number back instead of the actual string.

Body:
You cannot do this

if(sentence[i] == splitter)

sentence[i] is a single character. splitter is a string.

I would fix it by passing a char argement for splitter. ie

void split_to_array(string sentence, char splitter)

and

 split_to_array("fdsfds fdsfds vcxvcx fdsafdsa", ' ');

if you want to keep the same function signatures for some reasons then do

 if(sentence[i] == splitter[0])

ie compare against the first (and only) characer in splitter. This is however a very odd thing to do.


问:
How do I use mongoose's aggregate to assign each item a score based on an equation?
I am trying to make a sorting algorithm that will find the most trendy questions,
here is the equation I use:

```<code>Rating = (AV * (1 / 50)) + (AL * 3) - (AD * 6)
</code>```

Rating is the thing I want to sort by, the ones with the highest rating would be most trendy,

AV is the average views, calculated by Views/days ago

AL is average likes, calculated by Likes/days ago

AD is average dislikes, calculated by Dislikes/days ago

here is the question scheme which the documents we are sorting:

```<code>const Question = mongoose.model(
  "Question",
  new Schema({
    title: { type: String, required: true },
    text: { type: String },
    authorUsername: { type: String, required: true },
    dateCreated: {},
    answers: { type: Array, required: true },
    likes: { type: Array, required: true },
    dislikes: { type: Array, required: true },
    tag: { type: String, required: true },
    views: {type: Array, required:true},
  })
);
</code>```

and here is an example of a question

```<code>document:_id:620935985f6865b4e85c333d,
title:"How do i make a lemon?",
text:"yeet",
authorUsername:"SweetWhite",
dateCreated:2022-02-13T16:45:12.598+00:00,
answers: Array,
likes:
0:1,
1:"SweetWhite",
dislikes: Array,
0:0,
tag:
"Social",
views:Array,
0:1,
1:"SweetWhite",
__v:0
</code>```

it is important to note I store the length of the views, likes, dislikes, arrays in the first item which is a number, so if you use $size it would be one too big.

can anybody use Question.aggregate with the equation above and the document to filter out the 15 most trendy questions(highest rating)?

Thanks!
EDIT:
here is my following work I did:

```<code>router.get('/questions/hot', async (req,res,next) => {
  try{
    const results = await Question.aggregate([
        /*{$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
        {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]},
        {$arrayElemAt:[{$ifNull:["$views",[0]]}, 0]}*/
      {$project: {rating: {$add:[
        {$divide:
          [
            {$divide: [{$arrayElemAt:[{$ifNull:["$views",[0]]}, 0]},  1]},
            50
          ]},
        {$subtract:
          [
            {$multiply: [{$divide: [{$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},  1]}, 3]},
            {$multiply: [{$divide: [{$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]},  1]}, 6]}
          ]
        }
        ]}
      }},
      {$sort: {rating:-1}},
      {$limit: 15}
    ]).exec();
    console.log(results)
    const questions = await Promise.all(results.map(({_id}) => Question.findOne({_id}).exec()));
    res.render('content', { whichOne: 5, user: req.user, questions:questions});
  }
  catch(err){
    next(err);
  }
});
</code>```

it is pretty close, there is already a score and it is functionaing, the only problem it is that the average like/days dislike/days views/days is not right, since I cant find a way to check how many days ago were it created using the date I have. so for now it is divided by 1 instead of days ago. Would appreciate if someone tells me how to do it

答:
Okay I just managed to solve this! In case this helps someone one day:</p>
```<code>router.get('/questions/hot', async (req,res,next) => {
  try{
    let now = new Date();
    const results = await Question.aggregate([
        /*{$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
        {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]},
        {$arrayElemAt:[{$ifNull:["$views",[0]]}, 0]}*/
      {$project: {rating: {$add:[
        {$divide:
          [
            {$divide: [{$arrayElemAt:[{$ifNull:["$views",[0]]}, 0]},  {$subtract:[now, '$dateCreated']}]},
            50
          ]},
        {$subtract:
          [
            {$multiply: [{$divide: [{$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]}, {$subtract:[now, '$dateCreated']}]}, 3]},
            {$multiply: [{$divide: [{$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]},  {$subtract:[now, '$dateCreated']}]}, 6]}
          ]
        }
        ]}
      }},
      {$sort: {rating:-1}},
      {$limit: 15}
    ]).exec();
    console.log(results)
    const questions = await Promise.all(results.map(({_id}) => Question.findOne({_id}).exec()));
    res.render('content', { whichOne: 5, user: req.user, questions:questions});
  }
  catch(err){
    next(err);
  }
});
</code>```

Body:
I am trying to make a sorting algorithm that will find the most trendy questions,
here is the equation I use:

Rating = (AV * (1 / 50)) + (AL * 3) - (AD * 6)

Rating is the thing I want to sort by, the ones with the highest rating would be most trendy,

AV is the average views, calculated by Views/days ago

AL is average likes, calculated by Likes/days ago

AD is average dislikes, calculated by Dislikes/days ago

here is the question scheme which the documents we are sorting:

const Question = mongoose.model(
  "Question",
  new Schema({
    title: { type: String, required: true },
    text: { type: String },
    authorUsername: { type: String, required: true },
    dateCreated: {},
    answers: { type: Array, required: true },
    likes: { type: Array, required: true },
    dislikes: { type: Array, required: true },
    tag: { type: String, required: true },
    views: {type: Array, required:true},
  })
);

and here is an example of a question

document:_id:620935985f6865b4e85c333d,
title:"How do i make a lemon?",
text:"yeet",
authorUsername:"SweetWhite",
dateCreated:2022-02-13T16:45:12.598+00:00,
answers: Array,
likes:
0:1,
1:"SweetWhite",
dislikes: Array,
0:0,
tag:
"Social",
views:Array,
0:1,
1:"SweetWhite",
__v:0

it is important to note I store the length of the views, likes, dislikes, arrays in the first item which is a number, so if you use $size it would be one too big.

can anybody use Question.aggregate with the equation above and the document to filter out the 15 most trendy questions(highest rating)?

Thanks!
EDIT:
here is my following work I did:

router.get('/questions/hot', async (req,res,next) => {
  try{
    const results = await Question.aggregate([
        /*{$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
        {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]},
        {$arrayElemAt:[{$ifNull:["$views",[0]]}, 0]}*/
      {$project: {rating: {$add:[
        {$divide:
          [
            {$divide: [{$arrayElemAt:[{$ifNull:["$views",[0]]}, 0]},  1]},
            50
          ]},
        {$subtract:
          [
            {$multiply: [{$divide: [{$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},  1]}, 3]},
            {$multiply: [{$divide: [{$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]},  1]}, 6]}
          ]
        }
        ]}
      }},
      {$sort: {rating:-1}},
      {$limit: 15}
    ]).exec();
    console.log(results)
    const questions = await Promise.all(results.map(({_id}) => Question.findOne({_id}).exec()));
    res.render('content', { whichOne: 5, user: req.user, questions:questions});
  }
  catch(err){
    next(err);
  }
});

it is pretty close, there is already a score and it is functionaing, the only problem it is that the average like/days dislike/days views/days is not right, since I cant find a way to check how many days ago were it created using the date I have. so for now it is divided by 1 instead of days ago. Would appreciate if someone tells me how to do it

Body:
Okay I just managed to solve this! In case this helps someone one day:

router.get('/questions/hot', async (req,res,next) => {
  try{
    let now = new Date();
    const results = await Question.aggregate([
        /*{$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
        {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]},
        {$arrayElemAt:[{$ifNull:["$views",[0]]}, 0]}*/
      {$project: {rating: {$add:[
        {$divide:
          [
            {$divide: [{$arrayElemAt:[{$ifNull:["$views",[0]]}, 0]},  {$subtract:[now, '$dateCreated']}]},
            50
          ]},
        {$subtract:
          [
            {$multiply: [{$divide: [{$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]}, {$subtract:[now, '$dateCreated']}]}, 3]},
            {$multiply: [{$divide: [{$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]},  {$subtract:[now, '$dateCreated']}]}, 6]}
          ]
        }
        ]}
      }},
      {$sort: {rating:-1}},
      {$limit: 15}
    ]).exec();
    console.log(results)
    const questions = await Promise.all(results.map(({_id}) => Question.findOne({_id}).exec()));
    res.render('content', { whichOne: 5, user: req.user, questions:questions});
  }
  catch(err){
    next(err);
  }
});


问:
Can i animated or transform a shadow
i want to ask something. Can i add animation style on shadow with css. The animation what i mean is the shadow can do fade in and fade out in several time.

<!DOCTYPE html>

Text-shadow effect!

```

答:
Yes you can. You could use @keyframes.

h1 {
  animation: shadow-animate 3s infinite ease;
}

@keyframes shadow-animate {
  0% {
    text-shadow: 20px 20px;
  }

  100% {
    text-shadow: 0px 0px
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>

<h1>Text-shadow effect!</h1>

</body>
</html></code>```

Title: Can i animated or transform a shadow

Body:
Yes you can. You could use @keyframes.

h1 {
  animation: shadow-animate 3s infinite ease;
}

@keyframes shadow-animate {
  0% {
    text-shadow: 20px 20px;
  }

  100% {
    text-shadow: 0px 0px
  }
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<h1>Text-shadow effect!</h1>

</body>
</html>


问:
Spring Boot clear cache manually
I was following some online lesson's playlist, test project for spring boot. Simplie CRUD stuff. It created some tables, but i decided to change some fields names, dropped table from cmd connected to mysql. After the relaunch the project does not create this table once more. Am i right, that it's stored somewhere in cache, the record that the table has been already created? Or, for example, does it store the autoincrement id's value somewhere in cache? After the second relaunch spring just does not check the existence of the table in database because of some log in cache? How can i fix it without starting the project from scratch?</p>

答:
While using Spring Data JPA, you have many ways to instantiate your database   when you launch your application. You set this behavior with the spring.jpa.hibernate.ddl-auto=none property, which has 4 values :

none: no synchronization with the database

validate: validate the schema of the database

update: update the structure of the database

create-drop: create the schema and then drop it after the application is closed

create: just create the database

This link will give you more details.

does it store the autoincrement id's value somewhere in cache?

There are many strategies for autoincrement field and it most of the time managed by the the database.

Title: Spring Boot clear cache manually


问:
Gridsplitter not showing
I am new to WPF.  I declared my Grid as so:

```<code><Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
    <ColumnDefinition Width="5"></ColumnDefinition>
    <ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
     <Grid.RowDefinitions>
         <RowDefinition Height="*"></RowDefinition>
         <RowDefinition Height="*"></RowDefinition>
         <RowDefinition Height="*"></RowDefinition>
     </Grid.RowDefinitions>
</Grid>
</code>```

I basically want that 3rd column of width 5 to be the GridSplitter and to be resizeable for the left and right columns.  So I have this code for the splitter:

```<code><GridSplitter Grid.Column="1" Grid.RowSpan="3" ResizeDirection="Columns" Height="Auto"
              VerticalAlignment="Stretch" HorizontalAlignment="Center"
              Margin="0" Background="Black"/>
</code>```

I do not see the GridSplitter in the column.  Did I set it up right?  Thanks.

答:
You have the GridSplitter centering in it's column, but it has no width defined. So you are effectively centering it with a width of zero. It also looks like you have two Grids, where you'd need one.

Seems like you want something like this:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"></ColumnDefinition>
        <ColumnDefinition Width="Auto"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <GridSplitter Grid.Column="1" Grid.RowSpan="3" ResizeDirection="Columns" Height="Auto"
         Width="5" VerticalAlignment="Stretch" Margin="0" Background="Black"/>

</Grid>
</code>```

If you need the nested Grid, then you may need to duplicate the Column definitions.

Title: Gridsplitter not showing

Body:
I am new to WPF.  I declared my Grid as so:

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
    <ColumnDefinition Width="5"></ColumnDefinition>
    <ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
     <Grid.RowDefinitions>
         <RowDefinition Height="*"></RowDefinition>
         <RowDefinition Height="*"></RowDefinition>
         <RowDefinition Height="*"></RowDefinition>
     </Grid.RowDefinitions>
</Grid>

I basically want that 3rd column of width 5 to be the GridSplitter and to be resizeable for the left and right columns.  So I have this code for the splitter:

<GridSplitter Grid.Column="1" Grid.RowSpan="3" ResizeDirection="Columns" Height="Auto"
              VerticalAlignment="Stretch" HorizontalAlignment="Center"
              Margin="0" Background="Black"/>

I do not see the GridSplitter in the column.  Did I set it up right?  Thanks.

Body:
You have the GridSplitter centering in it's column, but it has no width defined. So you are effectively centering it with a width of zero. It also looks like you have two Grids, where you'd need one.

Seems like you want something like this:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"></ColumnDefinition>
        <ColumnDefinition Width="Auto"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <GridSplitter Grid.Column="1" Grid.RowSpan="3" ResizeDirection="Columns" Height="Auto"
         Width="5" VerticalAlignment="Stretch" Margin="0" Background="Black"/>

</Grid>

If you need the nested Grid, then you may need to duplicate the Column definitions.


答:
hm, for this I would recommend you to use the NavComponent and send your data through fragments or registering for activity but I don't want to confuse you and I will try to give you a solution for this problem.

I think the easiest way to solve this (in this context) would be to launch the intent as you are doing:

MainActivity.kt ->

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val carouselRecyclerview = findViewById<CarouselRecyclerview>(R.id.recycler)
    val list = ArrayList<DataModel>()
    // Load the images of the Veg
    for (mycount in 0..41) {
        list.add(DataModel(VegName[mycount].image, VegName[mycount].name))
    }
    val adapter = DataAdapter(list)
    carouselRecyclerview.adapter = adapter
    val carouselLayoutManager = carouselRecyclerview.getCarouselLayoutManager()
    carouselLayoutManager.scrollToPosition(1)
    carouselRecyclerview.setItemSelectListener(object : CarouselLayoutManager.OnSelected {
        override fun onItemSelected(position: Int) {
            var ShowIt = findViewById(R.id.textVegName) as TextView
            //Cente item
            ShowIt.text = list[position].text

        }
    })
    Searchbutton.setOnClickListener {
        val intent = Intent(this, SearchActivity::class.java)
        startActivity(intent)
   }

   fun setTheLocation(SetThisPlace: Int ) {
        carouselLayoutManager.scrollToPosition(SetThisPlace)
   }

   // onNewIntent would receive the intent needed to execute your logic.
   // I wouldn't use onActivityResult because, IMO, It is dirty code and it is deprecated.
   override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent?.hasExtra("position") == true) {
            setTheLocation(intent.getIntExtra("position"))
        }
}
</code>```

SearchActivity.kt ->

```<code>    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        .... your code ...
        exampleOfSendingBackFunction()
    }

//Here you will send back the position to MainActivity.kt clearing all flags.
    fun exampleOfSendingBackFunction() {
         val intent = Intent(this, MainActivity::class.java).apply {
             flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or      Intent.FLAG_ACTIVITY_SINGLE_TOP
             putExtras(
                "position" to yourPositionVariable
             )
         }
         startActivity(intent)
    }
</code>```

I hope it helps :D

Title: Showing Result returned in a Carousel RecyclerView (Kotlin)

Body:
I have a rotating carousel (using carouselrecyclerview) to rotate a list of images around.

The user can call a second activity and then search the images, and then return the selected image’s ID back to the MainActivity.kt.

The MainActivity.kt receives the result  (using intent) in the onActivityResult.
I then need to call scrollToPosition (from the carouselLayoutManager) to move the carousel to the position that was selected in the second activity.

As the call to the carouselLayoutManager is within the onCreate, I can’t call it from the onActivityResult? I have tried moving the onActivityResult to within the onCreate, but then the onActivityResult is not called when returning from the second activity.

So, how can I call the code which is within the onCreate from the onActivityResult please?

Any help really appreciated as I’m struggling on this.

MainActivity.kt
...

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val carouselRecyclerview = findViewById<CarouselRecyclerview>(R.id.recycler)
    val list = ArrayList<DataModel>()
    // Load the images of the Veg
    for (mycount in 0..41) {
        list.add(DataModel(VegName[mycount].image, VegName[mycount].name))
    }
    val adapter = DataAdapter(list)
    carouselRecyclerview.adapter = adapter
    val carouselLayoutManager = carouselRecyclerview.getCarouselLayoutManager()
    carouselLayoutManager.scrollToPosition(1)
    carouselRecyclerview.setItemSelectListener(object : CarouselLayoutManager.OnSelected {
        override fun onItemSelected(position: Int) {
            var ShowIt = findViewById(R.id.textVegName) as TextView
            //Cente item
            ShowIt.text = list[position].text

        }
    })
    Searchbutton.setOnClickListener {
        val intent = Intent(this, SearchActivity::class.java)
        startActivityForResult(intent, SEARCH_ACTIVITY_REQUEST_CODE)
   }

   // Move the carousel to the  position received - THIS ISN'T CALLED?
   fun setthelocation(SetThisPlace: Int ) {
        carouselLayoutManager.scrollToPosition(SetThisPlace)
   }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == SEARCH_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            val returnedfrom = VegName.find{ it.name == data?.getStringExtra("result") }

            if (returnedfrom==null)
                Toast.makeText(applicationContext, "Did not find the result returned!", Toast.LENGTH_LONG).show()
            else {
                Toast.makeText(applicationContext, "Got = " + returnedfrom.id, Toast.LENGTH_LONG).show()
                //Need to call eiter setthelocation() or carouselLayoutManager.scrollToPosition???
                return
            }
        }
    }
}

Body:
hm, for this I would recommend you to use the NavComponent and send your data through fragments or registering for activity but I don't want to confuse you and I will try to give you a solution for this problem.

I think the easiest way to solve this (in this context) would be to launch the intent as you are doing:

MainActivity.kt ->

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val carouselRecyclerview = findViewById<CarouselRecyclerview>(R.id.recycler)
    val list = ArrayList<DataModel>()
    // Load the images of the Veg
    for (mycount in 0..41) {
        list.add(DataModel(VegName[mycount].image, VegName[mycount].name))
    }
    val adapter = DataAdapter(list)
    carouselRecyclerview.adapter = adapter
    val carouselLayoutManager = carouselRecyclerview.getCarouselLayoutManager()
    carouselLayoutManager.scrollToPosition(1)
    carouselRecyclerview.setItemSelectListener(object : CarouselLayoutManager.OnSelected {
        override fun onItemSelected(position: Int) {
            var ShowIt = findViewById(R.id.textVegName) as TextView
            //Cente item
            ShowIt.text = list[position].text

        }
    })
    Searchbutton.setOnClickListener {
        val intent = Intent(this, SearchActivity::class.java)
        startActivity(intent)
   }

   fun setTheLocation(SetThisPlace: Int ) {
        carouselLayoutManager.scrollToPosition(SetThisPlace)
   }

   // onNewIntent would receive the intent needed to execute your logic.
   // I wouldn't use onActivityResult because, IMO, It is dirty code and it is deprecated.
   override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        if (intent?.hasExtra("position") == true) {
            setTheLocation(intent.getIntExtra("position"))
        }
}

SearchActivity.kt ->

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        .... your code ...
        exampleOfSendingBackFunction()
    }

//Here you will send back the position to MainActivity.kt clearing all flags.
    fun exampleOfSendingBackFunction() {
         val intent = Intent(this, MainActivity::class.java).apply {
             flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or      Intent.FLAG_ACTIVITY_SINGLE_TOP
             putExtras(
                "position" to yourPositionVariable
             )
         }
         startActivity(intent)
    }

I hope it helps :D


问:
How to get key value pairs of the objects from complex JSON using jq and map? (Active Campaign)
I have following JSON. I want to get key-value pair objects based on their role. In this example there are 3 roles(Presenter, Approver, Customer) but there can be more as it is dynamic.

JSON

{
   "Presenter Name": "Roney",
   "Presenter Email": "roney@domain.com",
   "Approver Name": "Tim",
   "Approver Email": "tim@domain.com",
   "Customer Name": "Alex",
   "Customer Email": "alex@domain.com",
   "Invoice": "001",
   "Date": "2022-02-14"
}
```
<p>Expected output using jq, map,</p>
<pre class="lang-json prettyprint-override"><code>{
    "Presenter": {
      "email_address": "roney@domain.com",
      "name": "Roney",
      "role": "Presenter"
    },
    "Approver": {
      "email_address": "tim@domain.com",
      "name": "Tim",
      "role": "Approver"
    },
    "Customer": {
      "email_address": "alex@domain.com",
      "name": "Alex",
      "role": "Customer"
    }
}
</code>```

I have tried till following but didn't get what to do next. Please advice.

to_entries |map( { (.key): { name: .value, email_address:.value, role: .key} } ) | add

答:
Here's another, shorter approach that doesn't use group_by. Instead, this directly iterates over the initial object using reduce and imediately sets all the fields accordingly if the key followed the space-separated role-key pattern.

reduce (to_entries[] | .key /= " ") as {key: [$role, $key], $value} ({};
  if $key then
    .[$role] += {({Email: "email_address", Name: "name"}[$key]): $value, $role}
  else . end
)
```
<pre class="lang-json prettyprint-override"><code>{
  "Presenter": {
    "name": "Roney",
    "role": "Presenter",
    "email_address": "roney@domain.com"
  },
  "Approver": {
    "name": "Tim",
    "role": "Approver",
    "email_address": "tim@domain.com"
  },
  "Customer": {
    "name": "Alex",
    "role": "Customer",
    "email_address": "alex@domain.com"
  }
}
</code>```

Demo

Body:
I have following JSON. I want to get key-value pair objects based on their role. In this example there are 3 roles(Presenter, Approver, Customer) but there can be more as it is dynamic.

JSON

{
   "Presenter Name": "Roney",
   "Presenter Email": "roney@domain.com",
   "Approver Name": "Tim",
   "Approver Email": "tim@domain.com",
   "Customer Name": "Alex",
   "Customer Email": "alex@domain.com",
   "Invoice": "001",
   "Date": "2022-02-14"
}

Expected output using jq, map,

{
    "Presenter": {
      "email_address": "roney@domain.com",
      "name": "Roney",
      "role": "Presenter"
    },
    "Approver": {
      "email_address": "tim@domain.com",
      "name": "Tim",
      "role": "Approver"
    },
    "Customer": {
      "email_address": "alex@domain.com",
      "name": "Alex",
      "role": "Customer"
    }
}

I have tried till following but didn't get what to do next. Please advice.

to_entries |map( { (.key): { name: .value, email_address:.value, role: .key} } ) | add

Body:
Here's another, shorter approach that doesn't use group_by. Instead, this directly iterates over the initial object using reduce and imediately sets all the fields accordingly if the key followed the space-separated role-key pattern.

reduce (to_entries[] | .key /= " ") as {key: [$role, $key], $value} ({};
  if $key then
    .[$role] += {({Email: "email_address", Name: "name"}[$key]): $value, $role}
  else . end
)

{
  "Presenter": {
    "name": "Roney",
    "role": "Presenter",
    "email_address": "roney@domain.com"
  },
  "Approver": {
    "name": "Tim",
    "role": "Approver",
    "email_address": "tim@domain.com"
  },
  "Customer": {
    "name": "Alex",
    "role": "Customer",
    "email_address": "alex@domain.com"
  }
}

Demo


问:
Laravel Joining 5 Tables using WhereNotIn
I have 5 tables:

orders

order_subcontractor

Subcontractors

categories

category_subcontractor

Obviously, category_subcontractor and order_subcontractor are the pivot tables and a category has many orders.

So I would like retrieve Subcontractors from a Category which are not in an specific Order using orderID and CategoryID.

enter image description here

I used the following query, but empty data is returned.

```<code>$subcontractors = Subcontractor::join('category_subcontractor', 'subcontractors.id', '=', 'category_subcontractor.subcontractor_id')
        ->join('Categories', 'category_subcontractor.category_id', '=', 'categories.id')
        ->join('orders', 'categories.id', '=', 'orders.category_id')
        ->where('categories.id', '=', $catID)
        ->where('orders.id', '=', $orderID)
         ->whereNotIn('category_id',function($query){
            $query->select('orders.category_id')->from('orders');
         })
        ->orderBy('subcontractors.created_at', 'desc')
        ->get(['subcontractors.id as value', 'subcontractor_name as name']);
</code>```

ER-Diagram

答:
Finally, I figured it out how to fetch the exact data. It could be inefficient because I fetch the demanded data in three queries however, it works.

Here is what I have done:

First I fetched all the subcontractors which are belongs to a category by joining the following 3 tables:

categories

category_subcontractor

subcontractor

```$q1 = Subcontractor::join('category_subcontractor', 'subcontractors.id', '=', 'category_subcontractor.subcontractor_id')
        ->join('Categories', 'category_subcontractor.category_id', '=', 'categories.id')
        ->where('categories.id', '=', $catID)
        ->pluck('subcontractors.id as value')
        ->toArray();```

Second, I fetched all the subcontractors which are added to an order by doing the following tables:

subcontractors

order_subcontractors

orders

```$q2 = Subcontractor::join('subcontractor_orders', 'subcontractors.id', '=', 'subcontractor_orders.subcontractor_id')
        ->join('orders', 'subcontractor_orders.order_id', '=', 'orders.id')
        ->where('orders.id', '=', $orderID)
        ->where('orders.category_id', '=', $catID)
        ->pluck('subcontractors.id as value')
        ->toArray();```

Lastly, I got the difference between $q1 and $q2 and query from the subcontractor table again using the last query result as follow:

```$differenceArray = array_diff($q1, $q2);

 $subcontractors =  Subcontractor::whereIn('id', $differenceArray)
            ->get(['subcontractors.id as value', 'subcontractors.subcontractor_name as name']);```

Body:
I have 5 tables:

orders

order_subcontractor

Subcontractors

categories

category_subcontractor

Obviously, category_subcontractor and order_subcontractor are the pivot tables and a category has many orders.

So I would like retrieve Subcontractors from a Category which are not in an specific Order using orderID and CategoryID.

enter image description here

I used the following query, but empty data is returned.

$subcontractors = Subcontractor::join('category_subcontractor', 'subcontractors.id', '=', 'category_subcontractor.subcontractor_id')
        ->join('Categories', 'category_subcontractor.category_id', '=', 'categories.id')
        ->join('orders', 'categories.id', '=', 'orders.category_id')
        ->where('categories.id', '=', $catID)
        ->where('orders.id', '=', $orderID)
         ->whereNotIn('category_id',function($query){
            $query->select('orders.category_id')->from('orders');
         })
        ->orderBy('subcontractors.created_at', 'desc')
        ->get(['subcontractors.id as value', 'subcontractor_name as name']);

ER-Diagram

Body:
Finally, I figured it out how to fetch the exact data. It could be inefficient because I fetch the demanded data in three queries however, it works.

Here is what I have done:

First I fetched all the subcontractors which are belongs to a category by joining the following 3 tables:

categories

category_subcontractor

subcontractor

$q1 = Subcontractor::join('category_subcontractor', 'subcontractors.id', '=', 'category_subcontractor.subcontractor_id')
        ->join('Categories', 'category_subcontractor.category_id', '=', 'categories.id')
        ->where('categories.id', '=', $catID)
        ->pluck('subcontractors.id as value')
        ->toArray();

Second, I fetched all the subcontractors which are added to an order by doing the following tables:

subcontractors

order_subcontractors

orders

$q2 = Subcontractor::join('subcontractor_orders', 'subcontractors.id', '=', 'subcontractor_orders.subcontractor_id')
        ->join('orders', 'subcontractor_orders.order_id', '=', 'orders.id')
        ->where('orders.id', '=', $orderID)
        ->where('orders.category_id', '=', $catID)
        ->pluck('subcontractors.id as value')
        ->toArray();

Lastly, I got the difference between $q1 and $q2 and query from the subcontractor table again using the last query result as follow:

$differenceArray = array_diff($q1, $q2);

 $subcontractors =  Subcontractor::whereIn('id', $differenceArray)
            ->get(['subcontractors.id as value', 'subcontractors.subcontractor_name as name']);