问:
SFML Ressource Manager class , null pointer on textures
I wrote a chess game and am now trying to change the design to include a Ressource Manager class (I have heard this is more efficient?). I am having issues though with null pointers regarding textures. I am getting the same errors both in this minimal example and on my main application.

Expected behavior

I am expecting 4 circles to appear on the screen distanced by 100 pixels.

Actual behavior

The screen flashes, then closes immediately with a segmentation fault

Minimally Reproducible Example

RessourceManager.hpp

#pragma once
#include <vector>
#include <unordered_map>
#include <SFML/Graphics.hpp>
#include <memory>

using namespace std;

typedef unordered_map<string, shared_ptr<sf::Texture>> textureMap;

class RessourceManager {
    string m_textureNames[1] = {"circle.png"};
    textureMap m_textures;

    public:
    RessourceManager(); // Constructor

    void loadRessources();
    void addTexture(const string& name);
    shared_ptr<sf::Texture> getTexture(const string &name);
};
```
<h2>RessourceManager.cpp</h2>
<pre class="lang-cpp prettyprint-override"><code>#include "RessourceManager.hpp"
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

RessourceManager::RessourceManager() {};

void RessourceManager::addTexture(const string& name) {
    shared_ptr<sf::Texture> texture = make_shared<sf::Texture>();
    texture->loadFromFile(name);
    m_textures.emplace(name, move(texture));
};

shared_ptr<sf::Texture> RessourceManager::getTexture(const string &name) {
    for(auto it = m_textures.begin();it != m_textures.end(); ++it) {
        if(it->first == name) {
            cout << "found" <<endl;
            return move(it->second);
        }
    }
    return nullptr;
};

void RessourceManager::loadRessources() {
    for(size_t i = 0; i < 1; ++i)  addTexture(m_textureNames[i]);
}
</code>```

main.cpp

#include <SFML/Graphics.hpp>
#include "RessourceManager.hpp"

void drawSquares(sf::RenderWindow&, RessourceManager&);

int main(){
    sf::RenderWindow window(sf::VideoMode(600, 480), "SFML window");
    RessourceManager ressources;
    ressources.loadRessources();

    while (window.isOpen()){
        sf::Event event;
        while (window.pollEvent(event)){
            if (event.type == sf::Event::Closed) window.close();
        }
        drawSquares(window, ressources);
        window.display();
    }
    return 0;
}

void drawSquares(sf::RenderWindow& window ,RessourceManager& ressources) {
    for(int i = 20; i <= 320; ++i) {
        shared_ptr<sf::Texture> temp = ressources.getTexture("circle.png");
        sf::Sprite s(*temp);
        s.setPosition(i, i);

        window.draw(s);
    }
}
```
<h3>Output console</h3>
```found
found
[1]    4445 segmentation fault  sudo ./main
```

Aditional information

Here I am using shared_ptr because I want multiple Sprites to point to the same texture (for instance 8 black pawns or 8 white pawns in a chess game). Further, I need these textures to move dynamically around on the screen so I must have them in the main loop in a standalone function.

Things I have tried

In drawSquares() I tried to first define an array shared_ptr<sf::Texture> textures[5];, populate it with the textures returned from ressources.getTexture() and then use these textures on the sprites in the for loop, but with no success.

I have tried using unique_ptr

I have tried to write sf::Sprite s(*(ressources.getTexture("circle.png"))); immediately, but also doesn't work.

I have read the SFML documentation on Textures and c++ variable scope/life time information, but I still can't understand what I am doing wrong in here.

答:
Answer was found

Thanks to metaquarks on Discord, removing the move() wrappers in move(it -> second) and .emplace(name. move(texture)) fixed the problem.

This is because after calling get(), the only thing keeping the texture alive is the pointer that was returned which is in this example dereferenced and passed as a non-owning reference, so it just dies. If one does not return using move(), both shared pointers keep it alive, and when the returned one eventually goes out of scope, it still exists because it is inside the map.

Body:
I wrote a chess game and am now trying to change the design to include a Ressource Manager class (I have heard this is more efficient?). I am having issues though with null pointers regarding textures. I am getting the same errors both in this minimal example and on my main application.

Expected behavior

I am expecting 4 circles to appear on the screen distanced by 100 pixels.

Actual behavior

The screen flashes, then closes immediately with a segmentation fault

Minimally Reproducible Example

RessourceManager.hpp

#pragma once
#include <vector>
#include <unordered_map>
#include <SFML/Graphics.hpp>
#include <memory>

using namespace std;

typedef unordered_map<string, shared_ptr<sf::Texture>> textureMap;

class RessourceManager {
    string m_textureNames[1] = {"circle.png"};
    textureMap m_textures;

    public:
    RessourceManager(); // Constructor

    void loadRessources();
    void addTexture(const string& name);
    shared_ptr<sf::Texture> getTexture(const string &name);
};

RessourceManager.cpp

#include "RessourceManager.hpp"
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

RessourceManager::RessourceManager() {};

void RessourceManager::addTexture(const string& name) {
    shared_ptr<sf::Texture> texture = make_shared<sf::Texture>();
    texture->loadFromFile(name);
    m_textures.emplace(name, move(texture));
};

shared_ptr<sf::Texture> RessourceManager::getTexture(const string &name) {
    for(auto it = m_textures.begin();it != m_textures.end(); ++it) {
        if(it->first == name) {
            cout << "found" <<endl;
            return move(it->second);
        }
    }
    return nullptr;
};

void RessourceManager::loadRessources() {
    for(size_t i = 0; i < 1; ++i)  addTexture(m_textureNames[i]);
}

main.cpp

#include <SFML/Graphics.hpp>
#include "RessourceManager.hpp"

void drawSquares(sf::RenderWindow&, RessourceManager&);

int main(){
    sf::RenderWindow window(sf::VideoMode(600, 480), "SFML window");
    RessourceManager ressources;
    ressources.loadRessources();

    while (window.isOpen()){
        sf::Event event;
        while (window.pollEvent(event)){
            if (event.type == sf::Event::Closed) window.close();
        }
        drawSquares(window, ressources);
        window.display();
    }
    return 0;
}

void drawSquares(sf::RenderWindow& window ,RessourceManager& ressources) {
    for(int i = 20; i <= 320; ++i) {
        shared_ptr<sf::Texture> temp = ressources.getTexture("circle.png");
        sf::Sprite s(*temp);
        s.setPosition(i, i);

        window.draw(s);
    }
}

Output console

found
found
[1]    4445 segmentation fault  sudo ./main

Aditional information

Here I am using shared_ptr because I want multiple Sprites to point to the same texture (for instance 8 black pawns or 8 white pawns in a chess game). Further, I need these textures to move dynamically around on the screen so I must have them in the main loop in a standalone function.

Things I have tried

In drawSquares() I tried to first define an array shared_ptr<sf::Texture> textures[5];, populate it with the textures returned from ressources.getTexture() and then use these textures on the sprites in the for loop, but with no success.

I have tried using unique_ptr

I have tried to write sf::Sprite s(*(ressources.getTexture("circle.png"))); immediately, but also doesn't work.

I have read the SFML documentation on Textures and c++ variable scope/life time information, but I still can't understand what I am doing wrong in here.


来源: stackexchange

问:
scrape live scores from oddsportal live odds page using requests
I want to scrape inplay odds and scores.
I succeed to get live odds data using the below code, but without finding live scores:

```<code>import requests, re, time
from bs4 import BeautifulSoup

url = f"https://fb.oddsportal.com/feed/livegames/live/1/0.dat?_{int(time.time() * 1000)}"
headers = {'User-Agent': 'curl/7.64.0','Referer': 'https://www.oddsportal.com/inplay-odds/live-now/soccer/'}
r = requests.get(url, headers=headers)

live_html = re.findall(r'<table class=.*table>', r.text)[0].replace("\\","")
soup = BeautifulSoup(live_html, 'html.parser')

</code>```

I tried to search from from Developper Tools > Sources > Page, but can't find any source that provide live scores

答:
Where there is a will there is a way.

Have you tried using Selenium? (I've heard it might be slower however)

If not try OCR you can decipher the text for every frame change.

ContentLicense: CC BY-SA 4.0

Body:
I want to scrape inplay odds and scores.
I succeed to get live odds data using the below code, but without finding live scores:

import requests, re, time
from bs4 import BeautifulSoup

url = f"https://fb.oddsportal.com/feed/livegames/live/1/0.dat?_{int(time.time() * 1000)}"
headers = {'User-Agent': 'curl/7.64.0','Referer': 'https://www.oddsportal.com/inplay-odds/live-now/soccer/'}
r = requests.get(url, headers=headers)

live_html = re.findall(r'
', r.text)[0].replace("\\","")
soup = BeautifulSoup(live_html, 'html.parser')

I tried to search from from Developper Tools > Sources > Page, but can't find any source that provide live scores


问:
Pyinstaller failed to made exe out of script
Pyinstaller on my system was working fine but after I tried to install google.colab which didn't went through, I am getting error and its failing everytime on several files. I've no idea what went wrong and I even tried to re install all my modules but still getting this error. I searched all over stackoverflow but didn't find the answer or similar question.Here is the error log. Any help would be appreciated.</p>
```<code>393 INFO: Python: 3.10.1
411 INFO: Platform: Windows-10-10.0.19043-SP0
411 INFO: wrote C:\Users\dell\Desktop\ZillowAddres\New folder\ZILLOWADDRESS.spec
416 INFO: UPX is not available.
432 INFO: Extending PYTHONPATH with paths
['C:\\Users\\dell\\Desktop\\ZillowAddres\\New folder']
833 INFO: checking Analysis
834 INFO: Building Analysis because Analysis-00.toc is non existent
834 INFO: Initializing module dependency graph...
837 INFO: Caching module graph hooks...
849 INFO: Analyzing base_library.zip ...
5704 INFO: Processing pre-find module path hook distutils from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\PyInstaller\\hooks\\pre_find_module_path\\hook-distutils.py'.
5705 INFO: distutils: retargeting to non-venv dir 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib'
6927 INFO: Caching module dependency graph...
7134 INFO: running Analysis Analysis-00.toc
7150 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by C:\Users\dell\AppData\Local\Programs\Python\Python310\python.exe
7204 INFO: Analyzing C:\Users\dell\Desktop\ZillowAddres\New folder\ZILLOWADDRESS.py
8174 INFO: Processing pre-safe import module hook urllib3.packages.six.moves from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\PyInstaller\\hooks\\pre_safe_import_module\\hook-urllib3.packages.six.moves.py'.
13593 INFO: Processing pre-find module path hook site from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\PyInstaller\\hooks\\pre_find_module_path\\hook-site.py'.
13594 INFO: site: retargeting to fake-dir 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\PyInstaller\\fake-modules'
21345 INFO: Processing pre-safe import module hook six.moves from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\PyInstaller\\hooks\\pre_safe_import_module\\hook-six.moves.py'.
C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\abstracts.py:130: SyntaxWarning: "is" with a literal. Did you mean "=="?
  if group is 'connector_python':
C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\optionfiles.py:98: SyntaxWarning: "is" with a literal. Did you mean "=="?
  if group is 'connector_python':
37892 INFO: Processing module hooks...
37893 INFO: Loading module hook 'hook-certifi.py' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\_pyinstaller_hooks_contrib\\hooks\\stdhooks'...
37899 INFO: Loading module hook 'hook-cryptography.py' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\_pyinstaller_hooks_contrib\\hooks\\stdhooks'...
38167 INFO: Loading module hook 'hook-IPython.py' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\_pyinstaller_hooks_contrib\\hooks\\stdhooks'...
Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\utils\timing.py", line 27, in <module>
    import resource
ModuleNotFoundError: No module named 'resource'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 2, in <module>
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\__init__.py", line 49, in <module>
    from .terminal.embed import embed
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\terminal\embed.py", line 19, in <module>
    from IPython.terminal.ipapp import load_default_config
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\terminal\ipapp.py", line 30, in <module>
    from IPython.core.magics import ScriptMagics
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\magics\__init__.py", line 21, in <module>
    from .execution import ExecutionMagics
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\magics\execution.py", line 46, in <module>
    from IPython.utils.timing import clock, clock2
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\utils\timing.py", line 64, in <module>
    clocku = clocks = clock = time.clock
AttributeError: module 'time' has no attribute 'clock'
Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\utils\timing.py", line 27, in <module>
    import resource
ModuleNotFoundError: No module named 'resource'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\pkgutil.py", line 495, in find_loader
    spec = importlib.util.find_spec(fullname)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\importlib\util.py", line 94, in find_spec
    parent = __import__(parent_name, fromlist=['__path__'])
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\__init__.py", line 49, in <module>
    from .terminal.embed import embed
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\terminal\embed.py", line 19, in <module>
    from IPython.terminal.ipapp import load_default_config
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\terminal\ipapp.py", line 30, in <module>
    from IPython.core.magics import ScriptMagics
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\magics\__init__.py", line 21, in <module>
    from .execution import ExecutionMagics
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\magics\execution.py", line 46, in <module>
    from IPython.utils.timing import clock, clock2
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\utils\timing.py", line 64, in <module>
    clocku = clocks = clock = time.clock
AttributeError: module 'time' has no attribute 'clock'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 365, in get_module_file_attribute
    loader = pkgutil.find_loader(package)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\pkgutil.py", line 501, in find_loader
    raise ImportError(msg.format(fullname, type(ex), ex)) from ex
ImportError: Error while finding loader for 'IPython.extensions' (<class 'AttributeError'>: module 'time' has no attribute 'clock')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\depend\imphook.py", line 361, in _load_hook_module
    self._hook_module = importlib_load_source(self.hook_module_name, self.hook_filename)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\compat.py", line 606, in importlib_load_source
    return mod_loader.load_module()
  File "<frozen importlib._bootstrap_external>", line 548, in _check_name_wrapper
  File "<frozen importlib._bootstrap_external>", line 1063, in load_module
  File "<frozen importlib._bootstrap_external>", line 888, in load_module
  File "<frozen importlib._bootstrap>", line 290, in _load_module_shim
  File "<frozen importlib._bootstrap>", line 719, in _load
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-IPython.py", line 34, in <module>
    datas += collect_data_files('IPython.extensions', include_py_files=True)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 723, in collect_data_files
    pkg_base, pkg_dir = get_package_paths(package)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 518, in get_package_paths
    file_attr = get_module_file_attribute(package)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 383, in get_module_file_attribute
    raise ImportError('Unable to load module attribute') from e
ImportError: Unable to load module attribute

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\Scripts\pyinstaller.exe\__main__.py", line 7, in <module>
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\__main__.py", line 124, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\__main__.py", line 58, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\building\build_main.py", line 793, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\building\build_main.py", line 725, in build
    exec(code, spec_namespace)
  File "C:\Users\dell\Desktop\ZillowAddres\New folder\ZILLOWADDRESS.spec", line 7, in <module>
    a = Analysis(['ZILLOWADDRESS.py'],
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\building\build_main.py", line 277, in __init__
    self.__postinit__()
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\building\datastruct.py", line 155, in __postinit__
    self.assemble()
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\building\build_main.py", line 445, in assemble
    self.graph.process_post_graph_hooks(self)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\depend\analysis.py", line 326, in process_post_graph_hooks
    module_hook.post_graph(analysis)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\depend\imphook.py", line 398, in post_graph
    self._load_hook_module()
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\depend\imphook.py", line 364, in _load_hook_module
    raise ImportErrorWhenRunningHook(self.hook_module_name, self.hook_filename)
PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_IPython required by hook for module C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-IPython.py. Please check whether module __PyInstaller_hooks_0_IPython actually exists and whether the hook is compatible with your version of C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-IPython.py: You might want to read more about hooks in the manual and provide a pull-request to improve PyInstaller.```
</code>```

答:
Initial review it looks like Ipython might be outdated or out of synch. Here are my suggestions:

Apologies, but first I have to ask; does your python script package run properly outside of pyinstaller? If not, please share any other errors you are receiving.

Confirm that your IPython version is not outdated. If outdated pip install latest version.

Try reinstalling pip

Check in pysintaller output logs if you have them available to see if python version has changed since last build. I recently had to issue with 3.10 and I had setup an virtual environment with 3.9.10.

If none of this works, please share pyinstaller spec file and requirements.txt for further assistance if possible.

Best of luck!

Body:
Pyinstaller on my system was working fine but after I tried to install google.colab which didn't went through, I am getting error and its failing everytime on several files. I've no idea what went wrong and I even tried to re install all my modules but still getting this error. I searched all over stackoverflow but didn't find the answer or similar question.Here is the error log. Any help would be appreciated.

393 INFO: Python: 3.10.1
411 INFO: Platform: Windows-10-10.0.19043-SP0
411 INFO: wrote C:\Users\dell\Desktop\ZillowAddres\New folder\ZILLOWADDRESS.spec
416 INFO: UPX is not available.
432 INFO: Extending PYTHONPATH with paths
['C:\\Users\\dell\\Desktop\\ZillowAddres\\New folder']
833 INFO: checking Analysis
834 INFO: Building Analysis because Analysis-00.toc is non existent
834 INFO: Initializing module dependency graph...
837 INFO: Caching module graph hooks...
849 INFO: Analyzing base_library.zip ...
5704 INFO: Processing pre-find module path hook distutils from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\PyInstaller\\hooks\\pre_find_module_path\\hook-distutils.py'.
5705 INFO: distutils: retargeting to non-venv dir 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib'
6927 INFO: Caching module dependency graph...
7134 INFO: running Analysis Analysis-00.toc
7150 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by C:\Users\dell\AppData\Local\Programs\Python\Python310\python.exe
7204 INFO: Analyzing C:\Users\dell\Desktop\ZillowAddres\New folder\ZILLOWADDRESS.py
8174 INFO: Processing pre-safe import module hook urllib3.packages.six.moves from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\PyInstaller\\hooks\\pre_safe_import_module\\hook-urllib3.packages.six.moves.py'.
13593 INFO: Processing pre-find module path hook site from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\PyInstaller\\hooks\\pre_find_module_path\\hook-site.py'.
13594 INFO: site: retargeting to fake-dir 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\PyInstaller\\fake-modules'
21345 INFO: Processing pre-safe import module hook six.moves from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\PyInstaller\\hooks\\pre_safe_import_module\\hook-six.moves.py'.
C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\abstracts.py:130: SyntaxWarning: "is" with a literal. Did you mean "=="?
  if group is 'connector_python':
C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\mysql\connector\optionfiles.py:98: SyntaxWarning: "is" with a literal. Did you mean "=="?
  if group is 'connector_python':
37892 INFO: Processing module hooks...
37893 INFO: Loading module hook 'hook-certifi.py' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\_pyinstaller_hooks_contrib\\hooks\\stdhooks'...
37899 INFO: Loading module hook 'hook-cryptography.py' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\_pyinstaller_hooks_contrib\\hooks\\stdhooks'...
38167 INFO: Loading module hook 'hook-IPython.py' from 'C:\\Users\\dell\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\_pyinstaller_hooks_contrib\\hooks\\stdhooks'...
Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\utils\timing.py", line 27, in <module>
    import resource
ModuleNotFoundError: No module named 'resource'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 2, in <module>
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\__init__.py", line 49, in <module>
    from .terminal.embed import embed
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\terminal\embed.py", line 19, in <module>
    from IPython.terminal.ipapp import load_default_config
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\terminal\ipapp.py", line 30, in <module>
    from IPython.core.magics import ScriptMagics
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\magics\__init__.py", line 21, in <module>
    from .execution import ExecutionMagics
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\magics\execution.py", line 46, in <module>
    from IPython.utils.timing import clock, clock2
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\utils\timing.py", line 64, in <module>
    clocku = clocks = clock = time.clock
AttributeError: module 'time' has no attribute 'clock'
Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\utils\timing.py", line 27, in <module>
    import resource
ModuleNotFoundError: No module named 'resource'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\pkgutil.py", line 495, in find_loader
    spec = importlib.util.find_spec(fullname)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\importlib\util.py", line 94, in find_spec
    parent = __import__(parent_name, fromlist=['__path__'])
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\__init__.py", line 49, in <module>
    from .terminal.embed import embed
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\terminal\embed.py", line 19, in <module>
    from IPython.terminal.ipapp import load_default_config
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\terminal\ipapp.py", line 30, in <module>
    from IPython.core.magics import ScriptMagics
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\magics\__init__.py", line 21, in <module>
    from .execution import ExecutionMagics
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\core\magics\execution.py", line 46, in <module>
    from IPython.utils.timing import clock, clock2
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\IPython\utils\timing.py", line 64, in <module>
    clocku = clocks = clock = time.clock
AttributeError: module 'time' has no attribute 'clock'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 365, in get_module_file_attribute
    loader = pkgutil.find_loader(package)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\pkgutil.py", line 501, in find_loader
    raise ImportError(msg.format(fullname, type(ex), ex)) from ex
ImportError: Error while finding loader for 'IPython.extensions' (<class 'AttributeError'>: module 'time' has no attribute 'clock')

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\depend\imphook.py", line 361, in _load_hook_module
    self._hook_module = importlib_load_source(self.hook_module_name, self.hook_filename)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\compat.py", line 606, in importlib_load_source
    return mod_loader.load_module()
  File "<frozen importlib._bootstrap_external>", line 548, in _check_name_wrapper
  File "<frozen importlib._bootstrap_external>", line 1063, in load_module
  File "<frozen importlib._bootstrap_external>", line 888, in load_module
  File "<frozen importlib._bootstrap>", line 290, in _load_module_shim
  File "<frozen importlib._bootstrap>", line 719, in _load
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-IPython.py", line 34, in <module>
    datas += collect_data_files('IPython.extensions', include_py_files=True)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 723, in collect_data_files
    pkg_base, pkg_dir = get_package_paths(package)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 518, in get_package_paths
    file_attr = get_module_file_attribute(package)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 383, in get_module_file_attribute
    raise ImportError('Unable to load module attribute') from e
ImportError: Unable to load module attribute

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\Scripts\pyinstaller.exe\__main__.py", line 7, in <module>
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\__main__.py", line 124, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\__main__.py", line 58, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\building\build_main.py", line 793, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\building\build_main.py", line 725, in build
    exec(code, spec_namespace)
  File "C:\Users\dell\Desktop\ZillowAddres\New folder\ZILLOWADDRESS.spec", line 7, in <module>
    a = Analysis(['ZILLOWADDRESS.py'],
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\building\build_main.py", line 277, in __init__
    self.__postinit__()
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\building\datastruct.py", line 155, in __postinit__
    self.assemble()
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\building\build_main.py", line 445, in assemble
    self.graph.process_post_graph_hooks(self)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\depend\analysis.py", line 326, in process_post_graph_hooks
    module_hook.post_graph(analysis)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\depend\imphook.py", line 398, in post_graph
    self._load_hook_module()
  File "C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\PyInstaller\depend\imphook.py", line 364, in _load_hook_module
    raise ImportErrorWhenRunningHook(self.hook_module_name, self.hook_filename)
PyInstaller.exceptions.ImportErrorWhenRunningHook: Failed to import module __PyInstaller_hooks_0_IPython required by hook for module C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-IPython.py. Please check whether module __PyInstaller_hooks_0_IPython actually exists and whether the hook is compatible with your version of C:\Users\dell\AppData\Local\Programs\Python\Python310\lib\site-packages\_pyinstaller_hooks_contrib\hooks\stdhooks\hook-IPython.py: You might want to read more about hooks in the manual and provide a pull-request to improve PyInstaller.```


问:
Python list withing list distinct elements
I have a list that looks like this:

```<code>a = [[99 , 2],[2,99]]
</code>```

My objective is to get a list that has one of the elements because they are similar combinations:

so I need another list b that is either:

```<code>b = [[99,2]]
</code>```

or

```<code>b= [[2,99]]
</code>```

How do I go about it in the most efficient manner without any libraries, answers with libraries are also appreciated since I would wanna know what are the stuffs already out there to ease my pain with learning how to code.

Thank you

答:
There might be many different ways to do it, but one option is to use frozenset in set:

a = [[99,2],[1,2,3],[2,99],[2,3,1]]
b = set(frozenset(x) for x in a) # alternatively, set(map(frozenset, a))
print(b) # {frozenset({1, 2, 3}), frozenset({2, 99})}
b = [list(x) for x in b]
print(b) # [[1, 2, 3], [2, 99]]
```
<p>Another option is to use (sorted) tuples to represent the "uniquified" elements:</p>
<pre class="lang-py prettyprint-override"><code>b = set(tuple(sorted(x)) for x in a)
</code>```

However, frozenset seems faster: Hashing frozenset versus tuple of sorted

Body:
I have a list that looks like this:

a = [[99 , 2],[2,99]]

My objective is to get a list that has one of the elements because they are similar combinations:

so I need another list b that is either:

b = [[99,2]]

or

b= [[2,99]]

How do I go about it in the most efficient manner without any libraries, answers with libraries are also appreciated since I would wanna know what are the stuffs already out there to ease my pain with learning how to code.

Thank you

Body:
There might be many different ways to do it, but one option is to use frozenset in set:

a = [[99,2],[1,2,3],[2,99],[2,3,1]]
b = set(frozenset(x) for x in a) # alternatively, set(map(frozenset, a))
print(b) # {frozenset({1, 2, 3}), frozenset({2, 99})}
b = [list(x) for x in b]
print(b) # [[1, 2, 3], [2, 99]]

Another option is to use (sorted) tuples to represent the "uniquified" elements:

b = set(tuple(sorted(x)) for x in a)

However, frozenset seems faster: Hashing frozenset versus tuple of sorted


问:
Jbang on cygwin shell
$ curl -Ls https://sh.jbang.dev | bash -s - app install --fresh --force quarkus@quarkusio
Downloading JBang...
Error downloading JBang</p>

答: Use jbang 0.88. Fixed the bug that made it fail on Cygwin shell.</p>

Title: Jbang on cygwin shell


问:
Does a relaxed memory-order spinlock always break synchronization?
Consider the following code:

```<code>int nonatom = 0;
std::atomic<int> atom{0};

// thread 1
nonatom = 1;
atom.store(1, std::memory_order_release);

// thread 2
while (atom.load(std::memory_order_relaxed)!=1); // spinlock waits for t1
atom.store(2, std::memory_order_relaxed);

// thread 3
if (atom.load(std::memory_oder_acquire)==2) // consider the case that this is true
    int foo = nonatom; // read non-atomic
// Is foo guaranteed to be 1?
// Undefined behavior?
</code>```

In the case that thread 3 reads the value 2 from atom, is it guaranteed to see the value 1 in nonatom?

Judging from the definition of the happens-before and synchronize-with relations, I would say that it cannot be said that the write to nonatom happens-before the read, because the t3's acquire does not sync with the release in thread 1, because it does not read from the release-sequence but instead reads the value from a store of another thread, thread 2. In this case there would be a data-race between thread 1 and 3 because the operations compete for the same non-atomic and one does not happen-before the other.

However, it is commonly informally said that a release guarantees that writes cannot be reordered after it while an acquire guarantees that reads cannot be reordered before it, which would make it seemingly logically impossible for nonatom to be read while or before it is written to.

My analysis of this is that by the standard alone, the code is incorrect, but could it actually break on any realistic implementation, given how release and acquire are usually implemented in machine code? What is your assessment of this example?

答:
The atom.store(2, std::memory_order_relaxed); in the example breaks the release sequence headed by atom.store(1, std::memory_order_release);. Even if memory_order_release were used in place of memory_order_relaxed it would still break it. And because of the failed release-acquire there is a data race on nonatom.

But atomic read-modify-write operations don’t break release sequence, thus replacing atom.store(2, std::memory_order_relaxed); with atom.fetch_add(1, std::memory_order_relaxed); or atom.exchange(2, std::memory_order_relaxed); would fix the race and foo would be guaranteed to be 1.

Body:
Consider the following code:

int nonatom = 0;
std::atomic<int> atom{0};

// thread 1
nonatom = 1;
atom.store(1, std::memory_order_release);

// thread 2
while (atom.load(std::memory_order_relaxed)!=1); // spinlock waits for t1
atom.store(2, std::memory_order_relaxed);

// thread 3
if (atom.load(std::memory_oder_acquire)==2) // consider the case that this is true
    int foo = nonatom; // read non-atomic
// Is foo guaranteed to be 1?
// Undefined behavior?

In the case that thread 3 reads the value 2 from atom, is it guaranteed to see the value 1 in nonatom?

Judging from the definition of the happens-before and synchronize-with relations, I would say that it cannot be said that the write to nonatom happens-before the read, because the t3's acquire does not sync with the release in thread 1, because it does not read from the release-sequence but instead reads the value from a store of another thread, thread 2. In this case there would be a data-race between thread 1 and 3 because the operations compete for the same non-atomic and one does not happen-before the other.

However, it is commonly informally said that a release guarantees that writes cannot be reordered after it while an acquire guarantees that reads cannot be reordered before it, which would make it seemingly logically impossible for nonatom to be read while or before it is written to.

My analysis of this is that by the standard alone, the code is incorrect, but could it actually break on any realistic implementation, given how release and acquire are usually implemented in machine code? What is your assessment of this example?


问:
interal error with querybuilder of cakephp on Prod
I'm working under wamp with php 7.4.26 @windows.
I have a project under cakephp. It works well on Dev Environnement.

However when I upload the code on PROD (linux/ PHP 7.4), it gives me an internal error (500). I know what's wrong, but I don't know why this happens only on linux.

```<code>$users = TableRegistry::getTableLocator()->get('users');
$user = $users->find('all')->contain(['Products' => ['sort' => ['Products.id' => 'DESC']]])->first();

SELECT
products.id AS `products__id`,
products.name AS `products__name`

FROM products products
ORDER BY Products.id DESC -- Products vs products!!
</code>```

The problem is that the "P" in Product is capitalized in the "sort". So to solve the problem I have to do this: ['sort' => ['products.id' => 'DESC']]

Question is: how to make it so that there is no check on the case (like with windows@WAMP)

答:
This seems not to be php related, but more likely coming from the SQL engine you use which is different under the WAMP context and the linux server.
WAMP lets the user choose between MariaDB and MySQL, and it seems you don't mention which database engine is used on the linux side.

The fact is that either MySQL or MariaDB are said, according to a quick search, to be case insensitive on table names by default.
So, i think you should at first glance try to get the information about which SQL engine is used on the linux server, and then try to change the collation used for storing the table names. If you cannot change it, you will have to adapt your code to it.

But at last, since relying on case sensitivity can be source of errors, relying on case insensitivity can also be source of errors, at your place I would avoid both.

See this post about collation on an SQL server :
https://dba.stackexchange.com/questions/163808/sql-server-on-linux-case-sensitivity

Body:
I'm working under wamp with php 7.4.26 @windows.
I have a project under cakephp. It works well on Dev Environnement.

However when I upload the code on PROD (linux/ PHP 7.4), it gives me an internal error (500). I know what's wrong, but I don't know why this happens only on linux.

$users = TableRegistry::getTableLocator()->get('users');
$user = $users->find('all')->contain(['Products' => ['sort' => ['Products.id' => 'DESC']]])->first();

SELECT
products.id AS `products__id`,
products.name AS `products__name`

FROM products products
ORDER BY Products.id DESC -- Products vs products!!

The problem is that the "P" in Product is capitalized in the "sort". So to solve the problem I have to do this: ['sort' => ['products.id' => 'DESC']]

Question is: how to make it so that there is no check on the case (like with windows@WAMP)


问:
React router v6 access route params and pass as props
In react router v6, how can I pass route params to a component without the need to use useParams() in the component?

This is what I want to do:

```<code><Route
  path='/'
  element={ProfileComponent username={'thedefault'}
/>
<Route
  exact
  path='/u/:username/'
  render={(props) =>
    <ProfileComponent username={props.match.params.username}/>
  }
/>
</code>```

I don't want to put useParams() in the component because this tightly couples it to the URL. For example, what if I wanted to render another ProfileComponent elsewhere, with a different username to that in the URL. It seems to violate best practice for unit testing unless I can do it like my example.

答:
I don't want to put useParams() in the component because this
tightly couples it to the URL. For example, what if I wanted to render
another ProfileComponent elsewhere, with a different username to that
in the URL. It seems to violate best practice for unit testing unless
I can do it like my example.

Any route using a username route match param would still be accessible via the useParams hook, but I think I understand what you are after. If I understand your question correctly you are asking how to map a route match param to a component prop in a generic way.

For this you can simply use a wrapper component to "sip" the route match param and pass it along to your component on any specific prop.

```<code>const ProfileComponentWrapper = () => {
  const { username } = useParams();
  return <ProfileComponent username={username} />;
};
</code>```

...

```<code><Route
  path='/u/:username/'
  element={<ProfileComponentWrapper />}
/>
</code>```

Body:
In react router v6, how can I pass route params to a component without the need to use useParams() in the component?

This is what I want to do:

<Route
  path='/'
  element={ProfileComponent username={'thedefault'}
/>
<Route
  exact
  path='/u/:username/'
  render={(props) =>
    <ProfileComponent username={props.match.params.username}/>
  }
/>

I don't want to put useParams() in the component because this tightly couples it to the URL. For example, what if I wanted to render another ProfileComponent elsewhere, with a different username to that in the URL. It seems to violate best practice for unit testing unless I can do it like my example.

Body:
I don't want to put useParams() in the component because this
tightly couples it to the URL. For example, what if I wanted to render
another ProfileComponent elsewhere, with a different username to that
in the URL. It seems to violate best practice for unit testing unless
I can do it like my example.

Any route using a username route match param would still be accessible via the useParams hook, but I think I understand what you are after. If I understand your question correctly you are asking how to map a route match param to a component prop in a generic way.

For this you can simply use a wrapper component to "sip" the route match param and pass it along to your component on any specific prop.

const ProfileComponentWrapper = () => {
  const { username } = useParams();
  return <ProfileComponent username={username} />;
};

...

<Route
  path='/u/:username/'
  element={<ProfileComponentWrapper />}
/>


问:
Dynamically retrieve user country to rectrict results from Google Places API
I'm developing my personal project and I'm working for first time with the Google Places API - I would like to retrict the user's post/search to each user's country.

So I need visitor from Australia just been able to get address results for "au", basically, but for each country.

Is there anything easier that this Getting visitors country from their IP to retrieve the visitors country and pass it as the componentRestrictions? Is it the best/recommendable way to do it?

Thanks ahead!

```<code>function initialize() {

 var input = document.getElementById('address');
  var options = {
   // fields: ["address_components", "geometry"],
    strictBounds: false,
    types: ["address"],
  componentRestrictions: { country: ["au","nz"] }
   };

      var autocomplete = new google.maps.places.Autocomplete(input,options);

</code>```

I forgot to mention that I'm using Nominatim to display the user location so maybe better using this to restrict?

```<code> data.address['country_code']
</code>```

答:
Solved by passing the nominatim country_code (I use that to retrieve user's location) to the Google component via geoLocationSuccess():</p>
```<code>function geoLocationSuccess(pos) {
  // get user lat,long
  var myLat = pos.coords.latitude,
    myLng = pos.coords.longitude,
    loadingTimeout;

  var loading = function () {
     $address.val("Fetching location...");
  };

  loadingTimeout = setTimeout(loading, 600);

  var request = $.get(
    "https://nominatim.openstreetmap.org/reverse?format=json&lat=" +
      myLat +
      "&lon=" +
      myLng
  )
    .done(function (data) {

      if (loadingTimeout) {
        clearTimeout(loadingTimeout);
        loadingTimeout = null;

        // Restrict Google Places API to this country?
        var countrycode = data.address['country_code'];
         var input = document.getElementById('address');
          var options = {
           // fields: ["address_components", "geometry"],
            strictBounds: false,
            types: ["address"],
          componentRestrictions: { country: countrycode }
           };

      var autocomplete = new google.maps.places.Autocomplete(input,options);

     }
    })
    .fail(function () {
      // handle error
     alertify.error('We can´t access your device location.');
     $address.val("Type your location");
    });

}
</code>```

Body:
I'm developing my personal project and I'm working for first time with the Google Places API - I would like to retrict the user's post/search to each user's country.

So I need visitor from Australia just been able to get address results for "au", basically, but for each country.

Is there anything easier that this Getting visitors country from their IP to retrieve the visitors country and pass it as the componentRestrictions? Is it the best/recommendable way to do it?

Thanks ahead!

function initialize() {

 var input = document.getElementById('address');
  var options = {
   // fields: ["address_components", "geometry"],
    strictBounds: false,
    types: ["address"],
  componentRestrictions: { country: ["au","nz"] }
   };

      var autocomplete = new google.maps.places.Autocomplete(input,options);

I forgot to mention that I'm using Nominatim to display the user location so maybe better using this to restrict?

 data.address['country_code']

Body:
Solved by passing the nominatim country_code (I use that to retrieve user's location) to the Google component via geoLocationSuccess():

function geoLocationSuccess(pos) {
  // get user lat,long
  var myLat = pos.coords.latitude,
    myLng = pos.coords.longitude,
    loadingTimeout;

  var loading = function () {
     $address.val("Fetching location...");
  };

  loadingTimeout = setTimeout(loading, 600);

  var request = $.get(
    "https://nominatim.openstreetmap.org/reverse?format=json&lat=" +
      myLat +
      "&lon=" +
      myLng
  )
    .done(function (data) {

      if (loadingTimeout) {
        clearTimeout(loadingTimeout);
        loadingTimeout = null;

        // Restrict Google Places API to this country?
        var countrycode = data.address['country_code'];
         var input = document.getElementById('address');
          var options = {
           // fields: ["address_components", "geometry"],
            strictBounds: false,
            types: ["address"],
          componentRestrictions: { country: countrycode }
           };

      var autocomplete = new google.maps.places.Autocomplete(input,options);

     }
    })
    .fail(function () {
      // handle error
     alertify.error('We can´t access your device location.');
     $address.val("Type your location");
    });

}


问:
Capture standard error of shell in makefile
I have a problem with the shell function in makefiles. Doing this:

```<code>var := $(shell some-command)
</code>```

Allows me to capture the stdout of some-command.

Doing this:

```<code>var := $(shell some-command 2>&1)
</code>```

Allows me to capture the stdout and the stderr of some-command.

How do I capture the stderr of the shell itself?

This makefile ilustrates the problem:

```<code>var1 := $(shell date 2>&1)
var2 := $(shell ls aaa 2>&1)
var3 := $(shell a-command-which-does-not-exist 2>&1)

show-me:
    @echo var1: \"$(var1)\"
    @echo var2: \"$(var2)\"
    @echo var3: \"$(var3)\"
</code>```

It will produce:

```<code>/bin/sh: 1: a-command-which-does-not-exist: not found
var1: "So 6. Feb 00:37:05 CET 2022"
var2: "ls: cannot access aaa: No such file or directory"
var3: ""
</code>```

I would like to capture /bin/sh: 1: a-command-which-does-not-exist: not found into var3. Is this possible?

答:
You have to run it in a subshell:

```<code>var3 := $(shell $(SHELL) -c 'a-command-which-does-not-exist' 2>&1)
</code>```

There's no other way unfortunately.

ETA OK, I figured it out.  The problem is that if the shell invoked by the $(shell ...) function exits with an error code of 127 (which is the shell's exit code for when it can't find a program to run), then GNU make will explicitly write its output to stderr rather than capture it (if you examine the function.c:func_shell_base() function you'll see this).

Any change to the shell that you invoke that ensures it doesn't exit with the 127 exit code will "fix" the problem:

```<code>$ cat Makefile
out := $(shell bad-program 2>&1 || exit 1)
$(info out = $out)

$ make
out = /bin/sh: 1: bad-program: not found
make: *** No targets.  Stop.
</code>```

This might be a bug in GNU make.  I'll need to consider it.

Body:
I have a problem with the shell function in makefiles. Doing this:

var := $(shell some-command)

Allows me to capture the stdout of some-command.

Doing this:

var := $(shell some-command 2>&1)

Allows me to capture the stdout and the stderr of some-command.

How do I capture the stderr of the shell itself?

This makefile ilustrates the problem:

var1 := $(shell date 2>&1)
var2 := $(shell ls aaa 2>&1)
var3 := $(shell a-command-which-does-not-exist 2>&1)

show-me:
    @echo var1: \"$(var1)\"
    @echo var2: \"$(var2)\"
    @echo var3: \"$(var3)\"

It will produce:

/bin/sh: 1: a-command-which-does-not-exist: not found
var1: "So 6. Feb 00:37:05 CET 2022"
var2: "ls: cannot access aaa: No such file or directory"
var3: ""

I would like to capture /bin/sh: 1: a-command-which-does-not-exist: not found into var3. Is this possible?

Body:
You have to run it in a subshell:

var3 := $(shell $(SHELL) -c 'a-command-which-does-not-exist' 2>&1)

There's no other way unfortunately.

ETA OK, I figured it out.  The problem is that if the shell invoked by the $(shell ...) function exits with an error code of 127 (which is the shell's exit code for when it can't find a program to run), then GNU make will explicitly write its output to stderr rather than capture it (if you examine the function.c:func_shell_base() function you'll see this).

Any change to the shell that you invoke that ensures it doesn't exit with the 127 exit code will "fix" the problem:

$ cat Makefile
out := $(shell bad-program 2>&1 || exit 1)
$(info out = $out)

$ make
out = /bin/sh: 1: bad-program: not found
make: *** No targets.  Stop.

This might be a bug in GNU make.  I'll need to consider it.


问:
How do I delete the last line of a text file using the echo command in windows?
How do I delete the last line of a text file using the echo command in windows?</p>

答:
Have a look for a 'tail' command/equivalent (plenty on google depending on OS version).

then

copy oldfile tempfile

tail -1 > oldfile

Regards
Michael.

OwnerDisplayName: fguser

ContentLicense: CC BY-SA 2.5


问:
Finding in elements in a tuple and filtering them
Assuming I have a tuple like:

```<code>[('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]
</code>```

I want to filter out the list and produce a new one with elements that begin with 'img'. So my new list will look like:

```<code>[('img-1','iii'), ('img-2','jjj')]
</code>```

Thanks!

答:
```<code>tuple_filter = lambda t, i, w: filter(lambda a: a[i].startswith(w), t)
newtuple = tuple_filter(thetuple, 0, 'img')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Assuming I have a tuple like:

[('text-1','xxx'), ('img-1','iii'), ('img-2','jjj'), ('text-2','xxx')]

I want to filter out the list and produce a new one with elements that begin with 'img'. So my new list will look like:

[('img-1','iii'), ('img-2','jjj')]

Thanks!


问:
Pip is not linking to my upgraded Python version. Package python3-pip is not available, but is referred to by another package
Having issues linking pip to python 3.7. Both pip and pip3 been installed but linking to Python 2.7.

I have tried to reinstall Python3 and then pip no progress.

I get the following message:

Package python3-pip is not available, but is referred to by another package.

This may mean that the package is missing, has been obsoleted, or
is only available from another source

$ python --version
Python 3.7.4

$ pip -V
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/__init__.py:83: RequestsDependencyWarning: Old version of cryptography ([1, 2, 3]) may cause slowdown.
  warnings.warn(warning, RequestsDependencyWarning)
pip 19.2.1 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7)

$ pip3 -V
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/__init__.py:83: RequestsDependencyWarning: Old version of cryptography ([1, 2, 3]) may cause slowdown.
  warnings.warn(warning, RequestsDependencyWarning)
pip 19.2.1 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7)

$ sudo apt-get install python3-pip
[sudo] password for TarikDev:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package python3-pip is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'python3-pip' has no installation candidate
```

答:
I tried this and it worked for me:

Step1: sudo apt-get update.

Step2: sudo apt-get install python3-pip

Then check for pip version by typing:

$ pip -V

pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)


问:
The enum type is unscoped prefer enum class over enum?
and I'm new to C++ and I'm wondering if anyone can help me to understand why

```<code>enum difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE };
difficulty myDiffiuclty = EASY
</code>```

and

```<code>enum shipCost { FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50 };
shipCost myShipCost = BOMBER_COST;
</code>```

are underlined in green? it says it prefers enum class, but when I change it to enum class then

```<code>enum class difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE };
difficulty myDiffiuclty = EASY;

enum class shipCost { FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50 };
shipCost myShipCost = BOMBER_COST;
</code>```

EASY becomes underlined in red and
myShipCost is underlined in green, BOMBER_COST underlined in red and CRUISER_COST is underlined in red

```<code>const int ALIEN_POINTS = 150;
int aliensKilled = 10;
int score = aliensKilled * ALIEN_POINTS;
cout << "score: " << score << endl;

enum difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE };
difficulty myDifficulty = EASY;

enum shipCost { FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50 };
shipCost myShipCost = BOMBER_COST;
cout << "\nTo upgrade my ship to a cruiser will cost "
    << (CRUISER_COST - myShipCost) << " Resource Points.\n";

system("pause");
return 0;
</code>```

答:
Now that you understand the difference, from the answers above, I'd like to point out a couple of places where the "new" way of doing things breaks down, and what you can do about it.

Consider this (abbreviated) actual example I ran into, porting some audio software I wrote in C to modern C++ (C++17):

```<code>typedef enum sample_type_e {
   sample_type_uint16,
   sample_type_double
}sample_type_t;
</code>```

Now, the first thing to know is that the typedef here is no longer required; you can read more about that elsewhere.  Moving on...

This code, compiled in Visual Studio 2019, will result in the error you describe.

Now, one approach to fixing this would seem to be to move to the new syntax-- but watch what happens:

```<code>enum class SampleType {
   uint16,
   double
}
</code>```

Oops.

That's not going to work-- double is a reserved word.  Now, you could, in exasperation, do this:

```<code>enum class SampleType {
   uint16,
   type_double
}
</code>```

...but that's not very consistent, and by the time you get to this:

```<code>enum class SampleType {
   type_uint16,
   type_double
}
</code>```

...you have arguably achieved the exact opposite of at least one of the purported benefits of this new feature: being terse, where possible, without losing context.

The nuisance in my supposedly-contrived but actually real-world example is that you can't scope a reserved word: they're always reserved.  (Tangent point of interest: there are languages where that is never true...)

This is called "being unlucky"; it happens a lot more often than language designers like to admit, and it always comes up when you don't have one of them in the room with you.

So, if something like that happens to come up for you, and you just really don't like what the results of trying to use "class enum" wind up looking like, what do you do?

Well, it turns out you can probably make the entire original problem go away by using another language feature that is considered good practice to use wherever possible: namespacing.  If I merely namespace that original declaration (minus the crufty typedef), I get:

```<code>namespace audiostuff {
    enum sample_type_e {
       sample_type_uint16,
       sample_type_double
    };
};
</code>```

...and as long as any code using that stuff is either in the same namespace, or has

```<code>using namespace audiostuff;
</code>```

at the top, or, alternately, uses is like this:

```<code>audiostuff::sample_type_e my_sample_type_var;
</code>```

...then, lo and behold, Visual Studio stops complaining-- and other compilers should as well.

The complaint, after all, is about reminding you that you should avoid cluttering up the global namespace-- especially by accident.  "class enum" is one way to do that, but using an explicit namespace is as well.

Body:
and I'm new to C++ and I'm wondering if anyone can help me to understand why

enum difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE };
difficulty myDiffiuclty = EASY

and

enum shipCost { FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50 };
shipCost myShipCost = BOMBER_COST;

are underlined in green? it says it prefers enum class, but when I change it to enum class then

enum class difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE };
difficulty myDiffiuclty = EASY;

enum class shipCost { FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50 };
shipCost myShipCost = BOMBER_COST;

EASY becomes underlined in red and
myShipCost is underlined in green, BOMBER_COST underlined in red and CRUISER_COST is underlined in red

const int ALIEN_POINTS = 150;
int aliensKilled = 10;
int score = aliensKilled * ALIEN_POINTS;
cout << "score: " << score << endl;

enum difficulty { NOVICE, EASY, NORMAL, HARD, UNBEATABLE };
difficulty myDifficulty = EASY;

enum shipCost { FIGHTER_COST = 25, BOMBER_COST, CRUISER_COST = 50 };
shipCost myShipCost = BOMBER_COST;
cout << "\nTo upgrade my ship to a cruiser will cost "
    << (CRUISER_COST - myShipCost) << " Resource Points.\n";

system("pause");
return 0;

Body:
Now that you understand the difference, from the answers above, I'd like to point out a couple of places where the "new" way of doing things breaks down, and what you can do about it.

Consider this (abbreviated) actual example I ran into, porting some audio software I wrote in C to modern C++ (C++17):

typedef enum sample_type_e {
   sample_type_uint16,
   sample_type_double
}sample_type_t;

Now, the first thing to know is that the typedef here is no longer required; you can read more about that elsewhere.  Moving on...

This code, compiled in Visual Studio 2019, will result in the error you describe.

Now, one approach to fixing this would seem to be to move to the new syntax-- but watch what happens:

enum class SampleType {
   uint16,
   double
}

Oops.

That's not going to work-- double is a reserved word.  Now, you could, in exasperation, do this:

enum class SampleType {
   uint16,
   type_double
}

...but that's not very consistent, and by the time you get to this:

enum class SampleType {
   type_uint16,
   type_double
}

...you have arguably achieved the exact opposite of at least one of the purported benefits of this new feature: being terse, where possible, without losing context.

The nuisance in my supposedly-contrived but actually real-world example is that you can't scope a reserved word: they're always reserved.  (Tangent point of interest: there are languages where that is never true...)

This is called "being unlucky"; it happens a lot more often than language designers like to admit, and it always comes up when you don't have one of them in the room with you.

So, if something like that happens to come up for you, and you just really don't like what the results of trying to use "class enum" wind up looking like, what do you do?

Well, it turns out you can probably make the entire original problem go away by using another language feature that is considered good practice to use wherever possible: namespacing.  If I merely namespace that original declaration (minus the crufty typedef), I get:

namespace audiostuff {
    enum sample_type_e {
       sample_type_uint16,
       sample_type_double
    };
};

...and as long as any code using that stuff is either in the same namespace, or has

using namespace audiostuff;

at the top, or, alternately, uses is like this:

audiostuff::sample_type_e my_sample_type_var;

...then, lo and behold, Visual Studio stops complaining-- and other compilers should as well.

The complaint, after all, is about reminding you that you should avoid cluttering up the global namespace-- especially by accident.  "class enum" is one way to do that, but using an explicit namespace is as well.


问:
Win32 CryptProtectData Method
I was reading this: https://learn.microsoft.com/en-us/windows/win32/seccrypto/example-c-program-using-cryptprotectdata

I was wondering about this method. Does this only store it in the process memory while the process is running? If so, is there a persistent data storage that the win32 api provides that's secure and does not create any files on the filesystem? Some sort of keychain/keyvalue store that's secure?

My intention here is to secure a secure login token that can be used for two weeks by a program I am writing for the user to login. I don't think this data should be stored in a file that is accessible by anyone. If someone were to find out about the file, they could steal the file and login with someone else's account as long as the token is valid. Environment variables and the windows registry are also not acceptable solutions. This needs to be inaccessible by the user.

答:
There's nothing wrong with storing your login token in a file (or in the registry, which I personally would prefer) provided that you encrypt it properly.  The documentation for CryptProtectData has  this to say:

Typically, only a user with the same logon credential as the user who encrypted the data can decrypt the data. In addition, the encryption and decryption usually must be done on the same computer.

So you're already halfway there.  Only the user (and machine) that 'own' the token can decrypt it.

In addition to that, there is this parameter:

[in, optional] pOptionalEntropy

A pointer to a DATA_BLOB structure that contains a password or other additional entropy used to encrypt the data. The [same] DATA_BLOB structure used in the encryption phase must also be used in the decryption phase

So this should be something known only to your program (a GUID would be the obvious choice).  Then, only that program can decrypt - and hence use - the token.

You might take some steps in your code to obfuscate this, such as storing it in some mangled form and only demangling it just before you use it.  Then call SecureZeroMemory when you're done with it to make life harder for potential snoopers.

Title: Win32 CryptProtectData Method


问:
Single object from queryset
I need help with a little issue I am having with my project. I have a model where I have a foreign key with many entries and I would like to take just one item of these entries.
In fact, my problem is something like that:
I need to obtain the single mission id, in order to have other functions.
The code is working fine, my problem is that I don't know the righe order to obtain the mission item from this queryset:

models.py

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

from flight.models import LogEntry
from user.models import Instructor, Student

# Create your models here.

TRAINING_COURSE_CHOICES = (
    ('PPL', 'PPL'),
    ('CPL', 'CPL'),
    ('IR', 'IR'),
    ('ATPL', 'ATPL'),
)

class TrainingCourse(models.Model):
    name = models.CharField(max_length=20, choices=TRAINING_COURSE_CHOICES)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class StudentTrainingCourse(models.Model):
    training_course = models.ForeignKey(
        TrainingCourse, on_delete=models.PROTECT)
    student = models.ForeignKey(Student, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.student.first_name + ' ' + self.student.last_name + ' ' + self.training_course.name

class Mission(models.Model):
    name = models.CharField(max_length=200)
    training_course = models.ForeignKey(
        TrainingCourse, on_delete=models.CASCADE)
    note = models.TextField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.training_course.name + ' ' + self.name

class StudentMission(models.Model):
    mission = models.ForeignKey(Mission, on_delete=models.PROTECT)
    student_training_course = models.ForeignKey(
        StudentTrainingCourse, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['mission__name']

    def __str__(self):
        return self.mission.name

class LearningObjective(models.Model):
    name = models.CharField(max_length=300)
    mission = models.ForeignKey(Mission, on_delete=models.DO_NOTHING)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

GRADING_VALUE = (
    ('1', '1'),
    ('2', '2'),
    ('3', '3'),
    ('4', '4'),
    ('5', '5'),
)

class MissionEntry(models.Model):
    student = models.ForeignKey(
        Student, on_delete=models.DO_NOTHING, blank=True, null=True)
    mission = models.ForeignKey(
        Mission, on_delete=models.DO_NOTHING, null=True, blank=True)
    log_entry = models.ForeignKey(
        LogEntry, on_delete=models.DO_NOTHING, blank=True, null=True)
    learning_objective = models.ForeignKey(
        LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True)
    grade = models.CharField(
        max_length=10, choices=GRADING_VALUE, blank=True, null=True)
    note = models.TextField(blank=True, null=True)
    debriefing = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.mission) + ' ' + str(self.log_entry)

    class Meta:
        verbose_name_plural = 'Mission Entries'

class MissionEntryStatus(models.Model):
    student_mission = models.ForeignKey(
        StudentMission, on_delete=models.PROTECT, null=True, blank=True)
    mission = models.ForeignKey(
        Mission, on_delete=models.PROTECT, null=True, blank=True)
    student = models.ForeignKey(Student, on_delete=models.PROTECT)
    is_completed = models.BooleanField(default=False)
    is_failed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
</code>```

views.py

```<code>def student_mission_list(request, pk):
    student = Student.objects.get(id=pk)
    student_training_course = StudentTrainingCourse.objects.get(
        student_id=student)

    missions = StudentMission.objects.filter(
        student_training_course_id=student_training_course)

    context = {
        'student': student,
        'missions': missions,
    }
    return render(request, 'mission/student_mission_list.html', context)
</code>```

In fact, in student_mission_list I need to retrieve the mission_id!!! The problem is that, if I try to retrieve that from StudentTraining or MissionEntryStatus model, I have multiple missions; but i'd like to have just the corresponding mission_id, but I am not able to find a way.
Is there any suggestion? Probably I have to modify the database, but I don't know where.
Thank you very much to all of you for your help

答:
The way you have it set up now, a StudentTrainingCourse can have only ONE student but, because a ForeignKey is a ManyToOne relationship, MANY students can have that same StudentTrainingCourse.  What I think you want is for a Student to have ONE StudentTrainingCourse, but a StudentTrainingCourse to have MANY Students.  My guess is what you need is:

class Student(models.Model):
    ...

    training_course = models.ForeignKey(StudentTrainingCourse, on_delete=models.CASCADE)

    ...
```
<p>Then you can get the particular mission id like:</p>
<pre class="lang-py prettyprint-override"><code>def student_mission_list(request, pk):
    student = Student.objects.get(id=pk)
    training_course = student.training_course
    mission = Mission.objects.get(training_course=training_course)
    # If you just want the mission ID:
    mission_id = mission.pk

    missions = StudentMission.objects.filter(
        student_training_course_id=student_training_course)

    context = {
        'student': student,
        'missions': missions,
    }
    return render(request, 'mission/student_mission_list.html', context)

</code>```

Title: Single object from queryset

Body:
I need help with a little issue I am having with my project. I have a model where I have a foreign key with many entries and I would like to take just one item of these entries.
In fact, my problem is something like that:
I need to obtain the single mission id, in order to have other functions.
The code is working fine, my problem is that I don't know the righe order to obtain the mission item from this queryset:

models.py

from django.db import models

from flight.models import LogEntry
from user.models import Instructor, Student

# Create your models here.

TRAINING_COURSE_CHOICES = (
    ('PPL', 'PPL'),
    ('CPL', 'CPL'),
    ('IR', 'IR'),
    ('ATPL', 'ATPL'),
)

class TrainingCourse(models.Model):
    name = models.CharField(max_length=20, choices=TRAINING_COURSE_CHOICES)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class StudentTrainingCourse(models.Model):
    training_course = models.ForeignKey(
        TrainingCourse, on_delete=models.PROTECT)
    student = models.ForeignKey(Student, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.student.first_name + ' ' + self.student.last_name + ' ' + self.training_course.name

class Mission(models.Model):
    name = models.CharField(max_length=200)
    training_course = models.ForeignKey(
        TrainingCourse, on_delete=models.CASCADE)
    note = models.TextField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.training_course.name + ' ' + self.name

class StudentMission(models.Model):
    mission = models.ForeignKey(Mission, on_delete=models.PROTECT)
    student_training_course = models.ForeignKey(
        StudentTrainingCourse, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['mission__name']

    def __str__(self):
        return self.mission.name

class LearningObjective(models.Model):
    name = models.CharField(max_length=300)
    mission = models.ForeignKey(Mission, on_delete=models.DO_NOTHING)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

GRADING_VALUE = (
    ('1', '1'),
    ('2', '2'),
    ('3', '3'),
    ('4', '4'),
    ('5', '5'),
)

class MissionEntry(models.Model):
    student = models.ForeignKey(
        Student, on_delete=models.DO_NOTHING, blank=True, null=True)
    mission = models.ForeignKey(
        Mission, on_delete=models.DO_NOTHING, null=True, blank=True)
    log_entry = models.ForeignKey(
        LogEntry, on_delete=models.DO_NOTHING, blank=True, null=True)
    learning_objective = models.ForeignKey(
        LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True)
    grade = models.CharField(
        max_length=10, choices=GRADING_VALUE, blank=True, null=True)
    note = models.TextField(blank=True, null=True)
    debriefing = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.mission) + ' ' + str(self.log_entry)

    class Meta:
        verbose_name_plural = 'Mission Entries'

class MissionEntryStatus(models.Model):
    student_mission = models.ForeignKey(
        StudentMission, on_delete=models.PROTECT, null=True, blank=True)
    mission = models.ForeignKey(
        Mission, on_delete=models.PROTECT, null=True, blank=True)
    student = models.ForeignKey(Student, on_delete=models.PROTECT)
    is_completed = models.BooleanField(default=False)
    is_failed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

views.py

def student_mission_list(request, pk):
    student = Student.objects.get(id=pk)
    student_training_course = StudentTrainingCourse.objects.get(
        student_id=student)

    missions = StudentMission.objects.filter(
        student_training_course_id=student_training_course)

    context = {
        'student': student,
        'missions': missions,
    }
    return render(request, 'mission/student_mission_list.html', context)

In fact, in student_mission_list I need to retrieve the mission_id!!! The problem is that, if I try to retrieve that from StudentTraining or MissionEntryStatus model, I have multiple missions; but i'd like to have just the corresponding mission_id, but I am not able to find a way.
Is there any suggestion? Probably I have to modify the database, but I don't know where.
Thank you very much to all of you for your help

Body:
The way you have it set up now, a StudentTrainingCourse can have only ONE student but, because a ForeignKey is a ManyToOne relationship, MANY students can have that same StudentTrainingCourse.  What I think you want is for a Student to have ONE StudentTrainingCourse, but a StudentTrainingCourse to have MANY Students.  My guess is what you need is:

class Student(models.Model):
    ...

    training_course = models.ForeignKey(StudentTrainingCourse, on_delete=models.CASCADE)

    ...

Then you can get the particular mission id like:

def student_mission_list(request, pk):
    student = Student.objects.get(id=pk)
    training_course = student.training_course
    mission = Mission.objects.get(training_course=training_course)
    # If you just want the mission ID:
    mission_id = mission.pk

    missions = StudentMission.objects.filter(
        student_training_course_id=student_training_course)

    context = {
        'student': student,
        'missions': missions,
    }
    return render(request, 'mission/student_mission_list.html', context)


问:
Does closing the Application browser window end the session?
In a spring MVC app , does closing the Application browser window ends the session ?
And when a new window is opened then a new session is started
Is my understanding correct?</p>

答:
Starting with some details first and then answering your specific questions below.

If you have a network inspection tool, you'll notice that the first time your browser interacts with the server, there is a header in the response that looks like Set-Cookie: JSESSIONID=<session_id> (assuming Tomcat). The server has created a session and has given that session ID. The server will typically create a new session when either the request did not have a session ID or the session ID was invalid. This cookie is stored in the browser's cookie store and will be sent in subsequent requests as a Cookie header.

If the cookie does not define an expiration, the browser will treat this cookie as a session cookie, which is transient or will only live until the browser is closed. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie.

So closing your browser would only lose the client-side reference (session ID) to the session. While the session on the server is orphaned (assuming nothing else has a reference to the session ID), the session is still very much alive. If there are no further requests for that session, the session will eventually timeout and end. You can configure the timeout via this property - server.servlet.session.timeout.

Now to answer your exact questions:

Q: Does closing the Application browser window ends the session?

The browser cookie store will no longer contain the session ID after closing. The server session will be orphaned and eventually timeout/end.

Q: And when a new window is opened then a new session is started

If the browser is already open and you made a request the server once before, opening another window that hits the server would not create a new session. Both windows share the same cookie store.

But if you were to open a new window after launching the browser process or clearing your cookies, a new session would be created. Again, this is due to the request from browser to server not containing the session ID.


问:
script files not loading in rev-manifest.json (gulp)
I have this gulpfile.js where I'm minifying my js files the problem is that when I'm doing gulp build this task is creating the minified js files but not entering the key-value pairs in the rev-manifest.json.

```<code>gulp.task('js', function (done) {
console.log('minifying js...');
gulp.src('./assets/**/*.js')
    .pipe(uglify())
    .pipe(rev())
    .pipe(gulp.dest('./public/assets'))
    .pipe(rev.manifest({
        cwd: 'public',
        merge: true
    }))
    .pipe(gulp.dest('./public/assets'));
done()
</code>```

});

I have a similar task for my scss files which converts scss to CSS and then minifies it. this is working absolutely fine adding proper key-value pairs in the rev-manifest.json

```<code>gulp.task('css', function (done) {
console.log('minifying css...');
gulp.src('./assets/sass/**/*.scss')
    .pipe(sass())
    .pipe(cssnano())
    .pipe(gulp.dest('./assets.css'));

gulp.src('./assets/**/*.css')
    .pipe(rev())
    .pipe(gulp.dest('./public/assets'))
    .pipe(rev.manifest({
        cwd: 'public',
        merge: true
    }))
    .pipe(gulp.dest('./public/assets'));
done();
</code>```

});

this is what rev-manifest.json looks like

See it's only adding the css files here but not js files.
my rev-manifest.json is present inside public/assets/

答:
In my case, manifests were not merging, they were getting overwritten. gulp.dest() causes the file to be overwritten. We indeed have to pass the path of the manifest as parameter before the options if we want the merge to work, here is the working code :</p>
```<code>const gulp = require('gulp');

const sass = require('gulp-sass')(require('sass'));
const cssnano = require('gulp-cssnano');
const rev = require('gulp-rev');
const uglify = require('gulp-uglify-es').default;
const imagemin = require('gulp-imagemin');
const del = require('del');

gulp.task('css', function(done){
    console.log('minifying css...');
    gulp.src('./assets/sass/**/*.scss')
    .pipe(sass())
    .pipe(cssnano())
    .pipe(gulp.dest('./assets/'));

    return gulp.src('./assets/**/*.css')
    .pipe(rev())
    .pipe(gulp.dest('./public/assets/'))
    .pipe(rev.manifest('public/assets/rev-manifest.json', {
        base: './public/assets',
        merge: true // merge with the existing manifest (if one exists)
     }))
    .pipe(gulp.dest('./public/assets/'));
    done();
});

gulp.task('js', function (done) {
    console.log('minifying js...');
    gulp.src('./assets/**/*.js')
        .pipe(uglify())
        .pipe(rev())
        .pipe(gulp.dest('./public/assets/'))
        .pipe(rev.manifest('public/assets/rev-manifest.json', {
            base: './public/assets',
            merge: true // merge with the existing manifest (if one exists)
        }))
        .pipe(gulp.dest('./public/assets/'));
    done()
});

gulp.task('images', function(done){
    console.log('compressing images...');
    gulp.src('./assets/**/*.+(png|jpg|gif|svg|jpeg)')
    .pipe(imagemin())
    .pipe(rev())
    .pipe(gulp.dest('./public/assets/'))
    .pipe(rev.manifest('public/assets/rev-manifest.json', {
        base: './public/assets',
        merge: true // merge with the existing manifest (if one exists)
     }))
    .pipe(gulp.dest('./public/assets/'));
    done();
});

// empty the public/assets directory
gulp.task('clean:assets', function(done){
    del.sync('./public/assets');
    done();
});

gulp.task('build', gulp.series('clean:assets', 'css', 'js', 'images'), function(done){
    console.log('Building assets');
    done();
});

</code>```

Body:
I have this gulpfile.js where I'm minifying my js files the problem is that when I'm doing gulp build this task is creating the minified js files but not entering the key-value pairs in the rev-manifest.json.

gulp.task('js', function (done) {
console.log('minifying js...');
gulp.src('./assets/**/*.js')
    .pipe(uglify())
    .pipe(rev())
    .pipe(gulp.dest('./public/assets'))
    .pipe(rev.manifest({
        cwd: 'public',
        merge: true
    }))
    .pipe(gulp.dest('./public/assets'));
done()

});

I have a similar task for my scss files which converts scss to CSS and then minifies it. this is working absolutely fine adding proper key-value pairs in the rev-manifest.json

gulp.task('css', function (done) {
console.log('minifying css...');
gulp.src('./assets/sass/**/*.scss')
    .pipe(sass())
    .pipe(cssnano())
    .pipe(gulp.dest('./assets.css'));

gulp.src('./assets/**/*.css')
    .pipe(rev())
    .pipe(gulp.dest('./public/assets'))
    .pipe(rev.manifest({
        cwd: 'public',
        merge: true
    }))
    .pipe(gulp.dest('./public/assets'));
done();

});

this is what rev-manifest.json looks like

See it's only adding the css files here but not js files.
my rev-manifest.json is present inside public/assets/

Body:
In my case, manifests were not merging, they were getting overwritten. gulp.dest() causes the file to be overwritten. We indeed have to pass the path of the manifest as parameter before the options if we want the merge to work, here is the working code :

const gulp = require('gulp');

const sass = require('gulp-sass')(require('sass'));
const cssnano = require('gulp-cssnano');
const rev = require('gulp-rev');
const uglify = require('gulp-uglify-es').default;
const imagemin = require('gulp-imagemin');
const del = require('del');

gulp.task('css', function(done){
    console.log('minifying css...');
    gulp.src('./assets/sass/**/*.scss')
    .pipe(sass())
    .pipe(cssnano())
    .pipe(gulp.dest('./assets/'));

    return gulp.src('./assets/**/*.css')
    .pipe(rev())
    .pipe(gulp.dest('./public/assets/'))
    .pipe(rev.manifest('public/assets/rev-manifest.json', {
        base: './public/assets',
        merge: true // merge with the existing manifest (if one exists)
     }))
    .pipe(gulp.dest('./public/assets/'));
    done();
});

gulp.task('js', function (done) {
    console.log('minifying js...');
    gulp.src('./assets/**/*.js')
        .pipe(uglify())
        .pipe(rev())
        .pipe(gulp.dest('./public/assets/'))
        .pipe(rev.manifest('public/assets/rev-manifest.json', {
            base: './public/assets',
            merge: true // merge with the existing manifest (if one exists)
        }))
        .pipe(gulp.dest('./public/assets/'));
    done()
});

gulp.task('images', function(done){
    console.log('compressing images...');
    gulp.src('./assets/**/*.+(png|jpg|gif|svg|jpeg)')
    .pipe(imagemin())
    .pipe(rev())
    .pipe(gulp.dest('./public/assets/'))
    .pipe(rev.manifest('public/assets/rev-manifest.json', {
        base: './public/assets',
        merge: true // merge with the existing manifest (if one exists)
     }))
    .pipe(gulp.dest('./public/assets/'));
    done();
});

// empty the public/assets directory
gulp.task('clean:assets', function(done){
    del.sync('./public/assets');
    done();
});

gulp.task('build', gulp.series('clean:assets', 'css', 'js', 'images'), function(done){
    console.log('Building assets');
    done();
});


问:
facebook C# sdk can't get authenticated
I can't get authenticated. I click the login button, I enter username and password, but still the FacebookWebcontext.Current is like this:

So what is the problem, why doesn't it authenticate. is there a way to see what is the problem? What settings are wrong, or if facebook refused to issue the authentication for the app?

答: checkout the "samples" folder from the source code, for examples.</p>

Title: facebook C# sdk can't get authenticated


问:
C++ doesn't give me an output
I'm trying to loop through a 2d array and find the sum of some numbers but for some reason, I don't get any output from the compilier.
Here is my code:</p>
```<code>#include <iostream>
using namespace std;

int main()
{
    int arr[3][3] = { {2,5,7},
                      {3,6,8},
                      {5,8,6} };

    int oddSum = 0;
    int evenSum = 0;

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            while (arr[i][j] != 2 && arr[i][j] % 2 == 0)
            {
                evenSum += arr[i][j];
            }

            while (arr[i][j] != 3 && arr[i][j] % 3 == 0)
            {
                oddSum += arr[i][j];
            }
        }
    }

    cout << "oddSum = " << oddSum << endl;
    cout << "evenSum = " << evenSum << endl;

    return 0;

}
</code>```

答: As arr[i][j] is not updated within your while loops, if that condition is true, it will never be false and the loop will never exit.

Title: C++ doesn't give me an output

Body:
I'm trying to loop through a 2d array and find the sum of some numbers but for some reason, I don't get any output from the compilier.
Here is my code:

#include <iostream>
using namespace std;

int main()
{
    int arr[3][3] = { {2,5,7},
                      {3,6,8},
                      {5,8,6} };

    int oddSum = 0;
    int evenSum = 0;

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            while (arr[i][j] != 2 && arr[i][j] % 2 == 0)
            {
                evenSum += arr[i][j];
            }

            while (arr[i][j] != 3 && arr[i][j] % 3 == 0)
            {
                oddSum += arr[i][j];
            }
        }
    }

    cout << "oddSum = " << oddSum << endl;
    cout << "evenSum = " << evenSum << endl;

    return 0;

}


问:
How to protect a web API in an APIM instance in an external mode VNet and access the web API through APIM only from the internet
I’m trying to protect a web API that is in an API Management instance that is in a subnet with NSG inbound rules definition in a VNet using Visual Studio 2022.
I need help defining the network elements and connecting them together so that I may call the web API from the internet but only through API Management. I don’t want the web API to be reachable directly from the internet.
I have followed the following steps using as reference Microsoft’s documentation at https://learn.microsoft.com/en-gb/azure/api-management/virtual-network-concepts?tabs=stv2.

Create a .Net Core web API

Publish the .Net Core web API to API Management instance.

Assign web API to API Management instance in Azure when publishing using wizard. The Vnet and subnet is created automatically by the wizard.

Create NSG inbound rules for the API Management’s subnet
Created inbound rule with service tag to allow internet to reach vnet on port 80.

In the web API I created an access restriction to allow traffic with service tag from API Manager from the same region as API Manager.

In subnet-1 I have created service endpoint policies to allow traffic to specific azure resources from my virtual network over service endpoints to service endpoints Microsoft.Web.

After creating this access restriction in the API I’m no longer able to reach the API either from API Manager or directly from the internet.

API Manager is in a virtual network named vnet01 and subnet named subnet-1.

I created a public IP address.

In API Management Service in the Virtual Networks blade in the left menu I select Vnet named vnet01, subnet named subnet-1 and the public IP address.

Then I get the following error.
Failed to scale API Management service
API Management service stv2 platform deployment into /subscriptions/4ddc-9f81-3f4bb28b6579/resourcegroups/sogeti/providers/microsoft.network/virtualnetworks/vnet01/subnets/subnet-1 is not supported, as it already contains API Management service(s) with stv1 platform in it as suggested by presence of /subscriptions/3dadbf93- 3f4bb28b6579/resourceGroups/Sogeti/providers/Microsoft.Network/virtualNetworks/vnet01/subnets/subnet-1/resourceNavigationLinks/9ajlnOOH. Please select a different subnet and try again. Refer to https://aka.ms/apim-infrastructure for definition of stv1 vs stv2.

Could somebody please let me know what I’m doing wrong? My final objective is to have the API reachable only through API Management.

答: I was able to resolve the issue by creating an access restriction (networking menu on the left) for the web API that allowed access to the API Manager's Vnet/ subnet. So I am able to call the API through the API Management instance but not directly from the internet.</p>


问:
Getting 401 unauthorized for Laravel sanctum
I am using Laravel Sanctum with Vuejs SPA. Both reside on same top level domain

```<code>Laravel backend : app.demo.localhost
Vue SPA : app-spa.demo.localhost
</code>```

Login and logout (endpoints) are working correctly when called from VueJS SPA using axios and XSRF-TOKEN is succesfully set, but when I call other api end points it gives me 401 unauthorized.

In axios this is being set

```<code>axios.defaults.withCredentials = true;
</code>```

I have the below configurations

In Laravel .env

```<code>SESSION_DRIVER=cookie
SESSION_DOMAIN=.demo.localhost
SANCTUM_STATEFUL_DOMAINS=app-spa.demo.localhost
</code>```

In Routes/Api.php

```<code>Route::middleware('auth:sanctum')->get('api/user', function (Request $request) {
   return $request->user();
});
</code>```

In cors.php

```<code>'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,
</code>```

Could someone help me out please?

答:
Hi i found a solution.

My SPA is Vue v3 working on 3000 port.
Also my backend is working on 80 port. (laravel 8.1)

Make Stateful Domains in config/sanctum.php like that

```<code> 'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost:3000',
    env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
</code>```

Adding only one and correct domain on their, worked for me magically. I wrote before there whole possible variant of ports, it made me crazy and cost a couple days and nights.

Body:
I am using Laravel Sanctum with Vuejs SPA. Both reside on same top level domain

Laravel backend : app.demo.localhost
Vue SPA : app-spa.demo.localhost

Login and logout (endpoints) are working correctly when called from VueJS SPA using axios and XSRF-TOKEN is succesfully set, but when I call other api end points it gives me 401 unauthorized.

In axios this is being set

axios.defaults.withCredentials = true;

I have the below configurations

In Laravel .env

SESSION_DRIVER=cookie
SESSION_DOMAIN=.demo.localhost
SANCTUM_STATEFUL_DOMAINS=app-spa.demo.localhost

In Routes/Api.php

Route::middleware('auth:sanctum')->get('api/user', function (Request $request) {
   return $request->user();
});

In cors.php

'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

Could someone help me out please?

Body:
Hi i found a solution.

My SPA is Vue v3 working on 3000 port.
Also my backend is working on 80 port. (laravel 8.1)

Make Stateful Domains in config/sanctum.php like that

 'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
    '%s%s',
    'localhost:3000',
    env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),

Adding only one and correct domain on their, worked for me magically. I wrote before there whole possible variant of ports, it made me crazy and cost a couple days and nights.