question_id
int64 59.5M
79.4M
| creation_date
stringlengths 8
10
| link
stringlengths 60
163
| question
stringlengths 53
28.9k
| accepted_answer
stringlengths 26
29.3k
| question_vote
int64 1
410
| answer_vote
int64 -9
482
|
---|---|---|---|---|---|---|
63,786,661 | 2020-9-8 | https://stackoverflow.com/questions/63786661/python-argparse-select-a-list-from-choices | How do you use argparse to provide a list of arguments from a group of choices. For example, lets say I want something like: python sample.py --p1 ['a','b'] --p2 ['x','y'] Where p1 can only be any or all from list of 'a', 'b', 'c' and p2 can only be any or all from list of 'x', 'y', 'z' | I found a way to get the behavior you want, but with a different syntax than what you present. You have to specify each choice with a unique parameter name/value pair. If that's ok, then the following works: parser = argparse.ArgumentParser(prog='game.py') parser.add_argument('--p1', choices=['a', 'b', 'c'], action='append') args = parser.parse_args(['--p1', 'a', '--p1', 'b']) print(args) Result: Namespace(p1=['a', 'b']) but this fails appropriately: parser = argparse.ArgumentParser(prog='game.py') parser.add_argument('--p1', choices=['a', 'b', 'c'], action='append') args = parser.parse_args(['--p1', 'a', '--p1', 'b', '--p1', 'x']) print(args) Result: usage: game.py [-h] [--p1 {a,b,c}] game.py: error: argument --p1: invalid choice: 'x' (choose from 'a', 'b', 'c') I can find nothing in the docs that suggests that ArgumentParser will take a list of valid values as a parameter value, which is what your version would require. | 10 | 10 |
63,785,462 | 2020-9-7 | https://stackoverflow.com/questions/63785462/problems-instaling-libpq-dev-in-ubuntu-20-04 | I am currently trying to install libpq-dev to install psycopg2. The problem is, when I try to install it, an error occurs saying I don't have the latest libpq5 version. However when I try to download the newer version of libpq5 the system says that I already have the latest version. An example of the error. lhmendes@lhmendes-GA-78LMT-S2P:~$ sudo apt-get install libpq-dev Reading package lists... Done Building dependency tree Reading state information... Done Some packages could not be installed. This may mean that you have requested an impossible situation or if you are using the unstable distribution that some required packages have not yet been created or been moved out of Incoming. The following information may help to resolve the situation: The following packages have unmet dependencies: libpq-dev : Depends: libpq5 (= 12.4-0ubuntu0.20.04.1) but 12.4-1.pgdg20.04+1 is to be installed E: Unable to correct problems, you have held broken packages. lhmendes@lhmendes-GA-78LMT-S2P:~$ sudo apt-get install libpq5 Reading package lists... Done Building dependency tree Reading state information... Done libpq5 is already the newest version (12.4-1.pgdg20.04+1). 0 upgraded, 0 newly installed, 0 to remove and 4 not upgraded. | I would say you have installed the latest libpq (12.4-1) but libpq-dev needs older version (12.4-0) and this makes problem. You may try to install older libpq apt-get install libpq==12.4-0ubuntu0.20.04.1 but if other program uses the latest version then older version can make problem with this program. pgdg20 in 12.4-1.pgdg20.04+1 means it is not module from standard ubuntu repo but from some other repo - probably postgresql repo - and maybe this repo has also the latest version libpq-dev. You would search 12.4-1.pgdg20.04+1 in Google and maybe you could find also libpg-dev with 12.4-1.pgdg20.04+1 I found libpq-dev 12.4-1.pgdg20.04+1 and you can download .deb file and install it. Or you can add this postgresql repo and install with apt-get. This method will also inform about updates and then you could install updates automatically. | 43 | 15 |
63,782,494 | 2020-9-7 | https://stackoverflow.com/questions/63782494/django-rest-framework-how-to-ignore-unique-primary-key-constraint-when-valida | I am attempting to store large amounts of transit data in a PostgreSQL database, where a client uploads multiple records at a time (in the tens of thousands). I only want one arrival time per stop, per route, per trip and the unique identifier for that stop, route, and trip is the primary key for my table (and a foreign key in a different table). I am trying use Django's update_or_create in my serializer to either create the entry for that arrival time or update the arrival time with the latest data if it already exists. Unfortunately, while calling is_valid() on my serializer, it identifies that the repeat records violate the uniqueness constraint of the primary keys (which makes sense), giving me this error message: 'real_id': [ErrorDetail(string='actual with this real id already exists.', code='unique')] I want to override this behavior since if the primary key isn't unique it will just update the entry. I have already tried looping over and removing validators like so: def run_validators(self, value): for validator in self.validators: self.validators.remove(validator) super(ActualSerializer, self).run_validators(value) I have also tried removing all validators using the extra_kwargs field of my serializer Meta class like so: extra_kwargs = { 'name': {'validators': []} } I don't really want to do the insertion in my view since ideally the serializer is parsing out the values and validating the other constraints. But none of these solutions have changed anything. I can't find anything else on SO that would address my problem (but if someone finds an answer I missed, that would be a godsend). I think my question is somewhat similar to this question but that one doesn't have a good answer. For reference, my serializers file: from .models import Future, Actual from rest_framework import serializers class ActualSerializer(serializers.ModelSerializer): def create(self, validated_data): actual, created = Actual.objects.update_or_create( real_id=validated_data['real_id'], defaults={'arrival': validated_data.get('arrival', None)} ) return actual class Meta: model = Actual fields = ['real_id', 'arrival'] class FutureSerializer(serializers.ModelSerializer): class Meta: model = Future fields = ['row_id', 'stop_id', 'route_id', 'record_time', 'predicted_arrival', 'delay', 'real_id'] My models: from django.db import models import json class Actual(models.Model): real_id = models.CharField(max_length=100, primary_key=True) arrival = models.BigIntegerField(null=True) def __str__(self): return json.dumps([self.real_id, self.arrival]) class Future(models.Model): row_id = models.BigAutoField(primary_key=True) stop_id = models.CharField(max_length=20) route_id = models.CharField(max_length=10) record_time = models.BigIntegerField() predicted_arrival = models.IntegerField(null=True) delay = models.IntegerField() real_id = models.ForeignKey(Actual, on_delete=models.CASCADE) def __str__(self): return json.dumps([self.row_id, self.stop_id, self.route_id, self.record_time, self.predicted_arrival, self.delay, self.real_id]) And finally, my view: class ArrivalData(APIView): queryset = Future.objects.all() permission_classes = [OperationAllowed] def post(self, request: Request, format=None) -> Response: parsed_data = json.loads(request.data['data']) actual_arrivals = [] for datum in parsed_data: saved_time = None if datum['predicted_arrival'] is not None and -200 < datum['predicted_arrival'] - datum['record_time'] < 0: saved_time = datum['predicted_arrival'] actual_arrivals.append({ 'real_id': datum['real_id'], 'arrival': saved_time, }) actual_serializer = ActualSerializer(data=actual_arrivals, many=True) if actual_serializer.is_valid(raise_exception=False): actual_serializer.save() future_serializer = FutureSerializer(data=parsed_data, many=True) if future_serializer.is_valid(): future_serializer.save() return Response("Data saved") return Response(str(actual_serializer.errors)) | So, turns out the unique constraint is a field-level validator which is why trying to remove it at the class level wasn't working. I explicitly declared the field in the serializer class without any validators real_id = serializers.CharField(validators=[]), which fixed the problem. This page ultimately helped me if anyone else has this issue. | 8 | 9 |
63,779,927 | 2020-9-7 | https://stackoverflow.com/questions/63779927/typeerror-categorical-crossentropy-missing-2-required-positional-arguments | Import libraries and models, from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D import keras.backend as k batch_size = 128 num_classes = 10 epochs = 12 Below the written code, #Loss and Optimizer optimizer = keras.optimizers.Adam() loss = keras.losses.categorical_crossentropy() Below the type error, which I badly faced and i can't make the solution, --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-8-f3fea941b382> in <module>() 1 #Loss and Optimizer 2 optimizer = keras.optimizers.Adam() ----> 3 loss = keras.losses.categorical_crossentropy() /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py in wrapper(*args, **kwargs) 199 """Call target, and fall back on dispatchers if there is a TypeError.""" 200 try: --> 201 return target(*args, **kwargs) 202 except (TypeError, ValueError): 203 # Note: convert_to_eager_tensor currently raises a ValueError, not a TypeError: categorical_crossentropy() missing 2 required positional arguments: 'y_true' and 'y_pred' Need help to solve this problem, please help me. Advanced thanks. | This is the correct implementation for getting a Categorical Crossentropy class object. loss = keras.losses.CategoricalCrossentropy() keras.losses.categorical_crossentropy this is a function which requires 2 parameters. | 6 | 13 |
63,779,711 | 2020-9-7 | https://stackoverflow.com/questions/63779711/find-paired-records-after-groupby-python | I have a dataframe like this: df = pd.DataFrame( [['101', 'a', 'in', '10'], ['101', 'a', 'out', '10'], ['102', 'b', 'in', '20'], ['103', 'c', 'in', '30'], ['103', 'c', 'out', '40']], columns=['col1', 'col2', 'col3', 'col4'] ) I want to group by col1 and find paired records that have the same value in col2 and col4, but one has 'in' in col3 one has 'out' in col3. The expected outcome is: df_out = pd.DataFrame( [['101', 'a', 'in', '10'], ['101', 'a', 'out', '10']], columns=['col1', 'col2', 'col3', 'col4'] ) Thank you for the help. | Let us try transform with nunique out = df[df.groupby(['col1','col2','col4'])['col3'].transform('nunique')==2] Out[187]: col1 col2 col3 col4 0 101 a in 10 1 101 a out 10 | 6 | 3 |
63,758,186 | 2020-9-5 | https://stackoverflow.com/questions/63758186/how-to-catch-exceptions-thrown-by-functions-executed-using-multiprocessing-proce | How can I catch exceptions from a process that was executed using multiprocessing.Process()? Consider the following python script that executes a simple failFunction() (which immediately throws a runtime error) inside of a child process using mulitprocessing.Process() #!/usr/bin/env python3 import multiprocessing, time # this function will be executed in a child process asynchronously def failFunction(): raise RuntimeError('trust fall, catch me!') # execute the helloWorld() function in a child process in the background process = multiprocessing.Process( target = failFunction, ) process.start() # <this is where async stuff would happen> time.sleep(1) # try (and fail) to catch the exception try: process.join() except Exception as e: print( "This won't catch the exception" ) As you can see from the following execution, attempting to wrap the .join() does not actually catch the exception user@host:~$ python3 example.py Process Process-1: Traceback (most recent call last): File "/usr/lib/python3.7/multiprocessing/process.py", line 297, in _bootstrap self.run() File "/usr/lib/python3.7/multiprocessing/process.py", line 99, in run self._target(*self._args, **self._kwargs) File "example4.py", line 6, in failFunction raise RuntimeError('trust fall, catch me!') RuntimeError: trust fall, catch me! user@host:~$ How can I update the above script to actually catch the exception from the function that was executed inside of a child process using multiprocessing.Process()? | This can be achieved by overloading the run() method in the multiprocessing.Proccess() class with a try..except statement and setting up a Pipe() to get and store any raised exceptions from the child process into an instance field for named exception: #!/usr/bin/env python3 import multiprocessing, traceback, time class Process(multiprocessing.Process): def __init__(self, *args, **kwargs): multiprocessing.Process.__init__(self, *args, **kwargs) self._pconn, self._cconn = multiprocessing.Pipe() self._exception = None def run(self): try: multiprocessing.Process.run(self) self._cconn.send(None) except Exception as e: tb = traceback.format_exc() self._cconn.send((e, tb)) #raise e # You can still rise this exception if you need to @property def exception(self): if self._pconn.poll(): self._exception = self._pconn.recv() return self._exception # this function will be executed in a child process asynchronously def failFunction(): raise RuntimeError('trust fall, catch me!') # execute the helloWorld() function in a child process in the background process = Process( target = failFunction, ) process.start() # <this is where async stuff would happen> time.sleep(1) # catch the child process' exception try: process.join() if process.exception: raise process.exception except Exception as e: print( "Exception caught!" ) Example execution: user@host:~$ python3 example.py Exception caught! user@host:~$ Solution taken from this answer: https://stackoverflow.com/a/33599967/1174102 | 8 | 5 |
63,721,614 | 2020-9-3 | https://stackoverflow.com/questions/63721614/unhashable-type-in-fastapi-request | I am writing a post-api using fastapi. The required request-format is: { "leadid":LD123, "parties":[ { "uid":123123, "cust_name":"JOhn Doe", }, ...]} The fastapi code in python is: class Customer(BaseModel): UID: str CustName: str class PackageIn(BaseModel): lead_id: str parties: Set[Customer] # threshold: Optional[int] = 85 app = FastAPI() @app.post('/') async def nm_v2(package:PackageIn): return {"resp":"Response"} When I visit the SwaggerUI to submit the response, the error is "422 Error: Unprocessable Entity". Also, the SwaggerUI doc states { "detail": [ { "loc": [ "body" ], "msg": "unhashable type: 'Customer'", "type": "type_error" } ] } I do not know how to create this dict() structure for request payload without creating a separate pydantic based class called Customer. Pl tell me how to rectify the error. | Pytdantic BaseClass is not hashable. There is a discussion about this feature, i guess it will not be implemented. There is workaround in the discussion, for your case you can try this: from pydantic import BaseModel from typing import Set class MyBaseModel(BaseModel): def __hash__(self): # make hashable BaseModel subclass return hash((type(self),) + tuple(self.__dict__.values())) class Customer(MyBaseModel): # Use hashable sublclass for your model UID: str CustName: str class PackageIn(BaseModel): lead_id: str parties: Set[Customer] # threshold: Optional[int] = 85 data = { "lead_id": 'LD123', "parties": [ { "UID": 123123, "CustName": "JOhn Doe", }]} PackageIn.parse_obj(data) # This part fastapi will make on post request, just for test > <PackageIn lead_id='LD123' parties={<Customer UID='123123' CustName='JOhn Doe'>}> | 16 | 19 |
63,729,195 | 2020-9-3 | https://stackoverflow.com/questions/63729195/how-to-terminate-loop-run-in-executor-with-processpoolexecutor-gracefully | How to terminate loop.run_in_executor with ProcessPoolExecutor gracefully? Shortly after starting the program, SIGINT (ctrl + c) is sent. def blocking_task(): sleep(3) async def main(): exe = concurrent.futures.ProcessPoolExecutor(max_workers=4) loop = asyncio.get_event_loop() tasks = [loop.run_in_executor(exe, blocking_task) for i in range(3)] await asyncio.gather(*tasks) if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: print('ctrl + c') With max_workers equal or lesser than the the number of tasks everything works. But if max_workers is greater, the output of the above code is as follows: Process ForkProcess-4: Traceback (most recent call last): File "/usr/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3.8/concurrent/futures/process.py", line 233, in _process_worker call_item = call_queue.get(block=True) File "/usr/lib/python3.8/multiprocessing/queues.py", line 97, in get res = self._recv_bytes() File "/usr/lib/python3.8/multiprocessing/connection.py", line 216, in recv_bytes buf = self._recv_bytes(maxlength) File "/usr/lib/python3.8/multiprocessing/connection.py", line 414, in _recv_bytes buf = self._recv(4) File "/usr/lib/python3.8/multiprocessing/connection.py", line 379, in _recv chunk = read(handle, remaining) KeyboardInterrupt ctrl + c I would like to catch the exception (KeyboardInterrupt) only once and ignore or mute the other exception(s) in the process pool, but how? Update extra credit: Can you explain (the reason for) the multi exception? Does adding a signal handler work on Windows? If not, is there a solution that works without a signal handler? | You can use the initializer parameter of ProcessPoolExecutor to install a handler for SIGINT in each process. Update: On Unix, when the process is created, it becomes a member of the process group of its parent. If you are generating the SIGINT with Ctrl+C, then the signal is being sent to the entire process group. import asyncio import concurrent.futures import os import signal import sys from time import sleep def handler(signum, frame): print('SIGINT for PID=', os.getpid()) sys.exit(0) def init(): signal.signal(signal.SIGINT, handler) def blocking_task(): sleep(15) async def main(): exe = concurrent.futures.ProcessPoolExecutor(max_workers=5, initializer=init) loop = asyncio.get_event_loop() tasks = [loop.run_in_executor(exe, blocking_task) for i in range(2)] await asyncio.gather(*tasks) if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: print('ctrl + c') Ctrl-C shortly after start: ^CSIGINT for PID= 59942 SIGINT for PID= 59943 SIGINT for PID= 59941 SIGINT for PID= 59945 SIGINT for PID= 59944 ctrl + c | 9 | 6 |
63,762,387 | 2020-9-6 | https://stackoverflow.com/questions/63762387/how-to-group-fastapi-endpoints-in-swagger-ui | I started programming using FastAPI framework and it comes with a builtin Swagger interface to handle requests and responses. I have completed nearly 20 APIs and its hard to manage and recognise APIs on Swagger interface. Someone told me to add sections in Swagger interface to distinguish APIs, but I couldn't find any examples and I need help. | You can add tags to your path parameter, for example. If you have something like this, using tags is extremely helpful. @app.delete("/items", tags=["Delete Methods"]) @app.put("/items", tags=["Put Methods"]) @app.post("/items", tags=["Post Methods"]) @app.get("/items", tags=["Get Methods"]) async def handle_items(): return @app.get("/something", tags=["Get Methods"]) async def something(): return You will get this, also if you want to add description and you don't want to keep repating yourself (For example adding same description in all parameters) You can use openapi_tags (I prefer this) from fastapi import FastAPI tags_metadata = [ {"name": "Get Methods", "description": "One other way around"}, {"name": "Post Methods", "description": "Keep doing this"}, {"name": "Delete Methods", "description": "KILL 'EM ALL"}, {"name": "Put Methods", "description": "Boring"}, ] app = FastAPI(openapi_tags=tags_metadata) @app.delete("/items", tags=["Delete Methods"]) @app.put("/items", tags=["Put Methods"]) @app.post("/items", tags=["Post Methods"]) @app.get("/items", tags=["Get Methods"]) async def handle_items(): return This will give the same look without repetition | 18 | 46 |
63,761,991 | 2020-9-6 | https://stackoverflow.com/questions/63761991/how-to-scrape-a-javascript-website-in-python | I am trying to scrape a website. I have tried using two methods but both do not provide me with the full website source code that I am looking for. I am trying to scrape the news titles from the website URL provided below. URL: "https://www.todayonline.com/" These are the two methods I have tried but failed. Method 1: Beautiful Soup tdy_url = "https://www.todayonline.com/" page = requests.get(tdy_url).text soup = BeautifulSoup(page) soup # Returns me a HTML with javascript text soup.find_all('h3') ### Returns me empty list [] Method 2: Selenium + BeautifulSoup tdy_url = "https://www.todayonline.com/" options = Options() options.headless = True driver = webdriver.Chrome("chromedriver",options=options) driver.get(tdy_url) time.sleep(10) html = driver.page_source soup = BeautifulSoup(html) soup.find_all('h3') ### Returns me only less than 1/4 of the 'h3' tags found in the original page source Please help. I have tried scraping other news websites and it is so much easier. Thank you. | You can access data via API (check out the Network tab): For example, import requests url = "https://www.todayonline.com/api/v3/news_feed/7" data = requests.get(url).json() | 6 | 3 |
63,757,476 | 2020-9-5 | https://stackoverflow.com/questions/63757476/error-while-using-confluent-kafka-python-library-with-aws-lambda | I am trying to use the confluent-kafka python library to administer my cluster via a lambda function but the function fails with the error: "Unable to import module 'Test': No module named 'confluent_kafka.cimpl'" My requirements.txt requests confluent-kafka To create the zip file I moved my code to the site-packages location of the virtual env and zipped everything. Python Code: import confluent_kafka.admin import requests def lambda_handler(event, context): print("Hello World") I am using the macOS 10.X. On Linux, I noticed that pip install creates a separate confluent_kafka.libs which does not get created on mac | I created the required layer and can verity that it works. The technique used includes docker tool described in the recent AWS blog: How do I create a Lambda layer using a simulated Lambda environment with Docker? Thus for this question, I verified it as follows: Create empty folder, e.g. mylayer. Go to the folder and create requirements.txt file with the content of echo requests > requirements.txt echo confluent-kafka >> requirements.txt Run the following docker command: docker run -v "$PWD":/var/task "lambci/lambda:build-python3.8" /bin/sh -c "pip install -r requirements.txt -t python/lib/python3.8/site-packages/; exit" Create layer as zip: zip -r mylayer.zip python > /dev/null Create lambda layer based on mylayer.zip in the AWS Console. Don't forget to specify Compatible runtimes to python3.8. Test the layer in lambda using the following lambda function: import confluent_kafka.admin import requests def lambda_handler(event, context): print(dir(confluent_kafka.admin)) print(dir(requests)) print("Hello World") The function executes correctly: ['AdminClient', 'BrokerMetadata', 'CONFIG_SOURCE_DEFAULT_CONFIG', 'CONFIG_SOURCE_DYNAMIC_BROKER_CONFIG', 'CONFIG_SOURCE_DYNAMIC_DEFAULT_BROKER_CONFIG', 'CONFIG_SOURCE_DYNAMIC_TOPIC_CONFIG', 'CONFIG_SOURCE_STATIC_BROKER_CONFIG', 'CONFIG_SOURCE_UNKNOWN_CONFIG', 'ClusterMetadata', 'ConfigEntry', 'ConfigResource', 'ConfigSource', 'Enum', 'KafkaException', 'NewPartitions', 'NewTopic', 'PartitionMetadata', 'RESOURCE_ANY', 'RESOURCE_BROKER', 'RESOURCE_GROUP', 'RESOURCE_TOPIC', 'RESOURCE_UNKNOWN', 'TopicMetadata', '_AdminClientImpl', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'concurrent', 'functools'] ['ConnectTimeout', 'ConnectionError', 'DependencyWarning', 'FileModeWarning', 'HTTPError', 'NullHandler', 'PreparedRequest', 'ReadTimeout', 'Request', 'RequestException', 'RequestsDependencyWarning', 'Response', 'Session', 'Timeout', 'TooManyRedirects', 'URLRequired', '__author__', '__author_email__', '__build__', '__builtins__', '__cached__', '__cake__', '__copyright__', '__description__', '__doc__', '__file__', '__license__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__title__', '__url__', '__version__', '_check_cryptography', '_internal_utils', 'adapters', 'api', 'auth', 'certs', 'chardet', 'check_compatibility', 'codes', 'compat', 'cookies', 'delete', 'exceptions', 'get', 'head', 'hooks', 'logging', 'models', 'options', 'packages', 'patch', 'post', 'put', 'request', 'session', 'sessions', 'ssl', 'status_codes', 'structures', 'urllib3', 'utils', 'warnings'] Hello World | 8 | 8 |
63,755,912 | 2020-9-5 | https://stackoverflow.com/questions/63755912/why-does-pylint-complain-about-unnecessary-elif-after-return-no-else-return | why does pylint complain about this code block? R1705: Unnecessary "elif" after "return" (no-else-return) def f(a): if a == 1: return 1 elif a == 2: return 2 return 3 To prevent the error, I had to create a temporary variable, which feels less pleasant. def f(a): if a == 1: b = 1 elif a == 2: b = 2 else: b = 3 return b Solution: def f(a): if a == 1: return 1 if a == 2: return 2 return 3 | The purpose of an else block is to define code that will not be executed if the condition is true, so execution wouldn't continue on to the next block. However, in your code, the main conditional block has a return statement, meaning execution will leave the function, so there's no need for an else block: all subsequent code after the return will, by definition, not be executed if the condition is true. It's redundant. It can be replaced with a simple if. | 19 | 17 |
63,754,895 | 2020-9-5 | https://stackoverflow.com/questions/63754895/how-to-create-windows-service-using-python | I have written a python script which will be installed in as windows service. Below is the code: import datetime import logging from logging.handlers import RotatingFileHandler import os import time from random import randint import win32serviceutil import win32service import win32event import servicemanager import socket def setup_logger(logger_name, log_file, level=logging.ERROR): log_formatter = logging.Formatter('%(asctime)s %(message)s') my_handler = RotatingFileHandler(log_file, maxBytes=100 * 1024 * 1024, backupCount=5) my_handler.setFormatter(log_formatter) my_handler.setLevel(level) l = logging.getLogger(logger_name) l.handlers[:] = [] l.addHandler(my_handler) curr_path = os.getcwd() log_file = "F:\\Projects\\TestService\\logs\\application.log" setup_logger('debug', log_file) log = logging.getLogger('debug') class AppServerSvc(win32serviceutil.ServiceFramework): _svc_name_ = "test_service" _svc_display_name_ = "Test Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) socket.setdefaulttimeout(60) self.isrunning = False def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.isrunning = False def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.isrunning = True self.main() def main(self): while self.isrunning: log.error("Running {}".format(randint(00, 99))) time.sleep(10) if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) I have run the command python test_service.py install to install the service and got the correct output Installing service test_service Service installed. When I open services tab I can see my service listed there. When I click on start service I am getting below error: Can anyone please tell me what is wrong in the code due to which its not starting the service. Please help. Thanks UPDATE: I ran the service in debug mode in cmd and looks like it is working fine. But from the services tab, its not working and showing above error. > python test_service.py debug Debugging service test_service - press Ctrl+C to stop. Info 0x40001002 - The test_service service has started. When starting the service, it gives same error: > python test_service.py start Starting service test_service Error starting service: The service did not respond to the start or control request in a timely fashion. Not sure why its not running and in debug mode it runs fine. Please help. | Anyone facing this issue, just copy pywintypes36.dll from Python36\Lib\site-packages\pywin32_system32 to Python36\Lib\site-packages\win32 Helpful commands: Install a service: python app.py install Uninstall a service: python app.py remove Start a service: python app.py start Update service: python app.py update | 6 | 6 |
63,754,311 | 2020-9-5 | https://stackoverflow.com/questions/63754311/unidentifiedimageerror-cannot-identify-image-file | Hello I am training a model with TensorFlow and Keras, and the dataset was downloaded from https://www.microsoft.com/en-us/download/confirmation.aspx?id=54765 This is a zip folder that I split in the following directories: . βββ test β βββ Cat β βββ Dog βββ train βββ Cat βββ Dog Test.cat and test.dog have each folder 1000 jpg photos, and train.cat and traing.dog have each folder 11500 jpg photos. The load is doing with this code: batch_size = 16 # Data augmentation and preprocess train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True, validation_split=0.20) # set validation split # Train dataset train_generator = train_datagen.flow_from_directory( 'PetImages/train', target_size=(244, 244), batch_size=batch_size, class_mode='binary', subset='training') # set as training data # Validation dataset validation_generator = train_datagen.flow_from_directory( 'PetImages/train', target_size=(244, 244), batch_size=batch_size, class_mode='binary', subset='validation') # set as validation data test_datagen = ImageDataGenerator(rescale=1./255) # Test dataset test_datagen = test_datagen.flow_from_directory( 'PetImages/test') THe model is training with the following code: history = model.fit(train_generator, validation_data=validation_generator, epochs=5) And i get the following input: Epoch 1/5 1150/1150 [==============================] - ETA: 0s - loss: 0.0505 - accuracy: 0.9906 But when the epoch is in this point I get the following error: UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f9e185347d0> How can I solve this, in order to finish the training? Thanks | Try this function to check if the image are all in correct format. import os from PIL import Image folder_path = 'data\img' extensions = [] for fldr in os.listdir(folder_path): sub_folder_path = os.path.join(folder_path, fldr) for filee in os.listdir(sub_folder_path): file_path = os.path.join(sub_folder_path, filee) print('** Path: {} **'.format(file_path), end="\r", flush=True) im = Image.open(file_path) rgb_im = im.convert('RGB') if filee.split('.')[1] not in extensions: extensions.append(filee.split('.')[1]) | 7 | 15 |
63,732,353 | 2020-9-3 | https://stackoverflow.com/questions/63732353/error-could-not-build-wheels-for-opencv-python-which-use-pep-517-and-cannot-be | I was trying to install OpenCV4 in a docker on jetson nano. It has jetpack 4.4 s os. The docker was successfully created and Tensorflow is running but while installing OpenCV using pip it is showing CMake error. root@5abf405fb92d:~# pip3 install opencv-python Collecting opencv-python Downloading opencv-python-4.4.0.42.tar.gz (88.9 MB) |ββββββββββββββββββββββββββββββββ| 88.9 MB 2.5 kB/s Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done Requirement already satisfied: numpy>=1.13.3 in /usr/local/lib/python3.6/dist-packages (from opencv-python) (1.18.4) Building wheels for collected packages: opencv-python Building wheel for opencv-python (PEP 517) ... error ERROR: Command errored out with exit status 1: command: /usr/bin/python3 /usr/local/lib/python3.6/dist-packages/pip/_vendor/pep517/_in_process.py build_wheel /tmp/tmpqpzwrofy cwd: /tmp/pip-install-93nxibky/opencv-python Complete output (9 lines): File "/tmp/pip-build-env-o_hualnr/overlay/lib/python3.6/site-packages/skbuild/setuptools_wrap.py", line 560, in setup cmkr = cmaker.CMaker(cmake_executable) File "/tmp/pip-build-env-o_hualnr/overlay/lib/python3.6/site-packages/skbuild/cmaker.py", line 95, in __init__ self.cmake_version = get_cmake_version(self.cmake_executable) File "/tmp/pip-build-env-o_hualnr/overlay/lib/python3.6/site-packages/skbuild/cmaker.py", line 82, in get_cmake_version "Problem with the CMake installation, aborting build. CMake executable is %s" % cmake_executable) Traceback (most recent call last): Problem with the CMake installation, aborting build. CMake executable is cmake ---------------------------------------- ERROR: Failed building wheel for opencv-python Failed to build opencv-python ERROR: Could not build wheels for opencv-python which use PEP 517 and cannot be installed directly | I had the same problem and i did this, pip install --upgrade pip setuptools wheel then install opencv again, pip install opencv-python this worked for me | 46 | 97 |
63,733,994 | 2020-9-4 | https://stackoverflow.com/questions/63733994/recursive-operation-in-pandas | I have a DataFrame like this: vals = {"operator": [1, 1, 1, 2, 3, 5], "nextval": [2, 3, 6, 4, 5, 6]} df = pd.DataFrame(vals) operator nextval 0 1 2 1 1 3 2 1 6 3 2 4 4 3 5 5 5 6 What I'm trying to do is get a list of all the possible paths from a starting point, like 1, and an ending point, like 6, using the operators and nextvals, not strictly the shortest path. The output can be flexible, but I'm looking for something like this or that communicates this: 1 -> 6 1 -> 2 -> 4 1 -> 3 -> 5 -> 6 I'm able to get it close, but not sure how to get the recursion right since the dict can't handle 2 same keys: import pandas as pd vals = {"operator": [1, 1, 1, 2, 3, 5], "nextval": [2, 3, 6, 4, 5, 6]} df = pd.DataFrame(vals) df1 = df.set_index("operator") dictvals = {} for x in df1.index.unique(): dictvals[x] = [] df2 = df1.loc[x] if isinstance(df2, pd.DataFrame): for idx, rowdata in df2.iterrows(): dictvals[x].append(rowdata["nextval"]) else: dictvals[x] = df2[0] print(dictvals) {1: [2, 3, 6], 2: 4, 3: 5, 5: 6} | Check with networkx , you need a direction graph with 'root' to 'leaf' path import networkx as nx G=nx.from_pandas_edgelist(df,source='operator',target='nextval', edge_attr=None, create_using=nx.DiGraph()) road=[] for n in G: if G.out_degree(n)==0: #leaf road.append(nx.shortest_path(G, 1, n)) road Out[82]: [[1, 2, 4], [1, 3, 5, 6]] Update import networkx as nx G=nx.from_pandas_edgelist(df,source='operator',target='nextval', edge_attr=None, create_using=nx.DiGraph()) road=[] for n in G: if G.out_degree(n)==0: #leaf road.append(list(nx.all_simple_paths(G, 1, n))) road Out[509]: [[[1, 3, 5, 6], [1, 6]], [[1, 2, 4]]] | 8 | 4 |
63,741,028 | 2020-9-4 | https://stackoverflow.com/questions/63741028/type-hint-for-a-tuple-whose-length-is-a-known-big-number | I currently type hint a function returning tuple as follows: FuncOutput = Tuple[nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image] Is there a way to do this in a concise manner where I can specify the length without typing it so many times? | No. typing.Tuple only supports typing each element or a variable number of elements. | 8 | 5 |
63,733,644 | 2020-9-4 | https://stackoverflow.com/questions/63733644/set-log-level-with-structlog | I am trying to setup structlog and set log level. My code looks like this: import structlog import logging filepath=open("out.log",'a') logging.basicConfig( level=logging.INFO ) structlog.configure( processors=[structlog.stdlib.filter_by_level], wrapper_class=structlog.BoundLogger, context_class=dict, logger_factory=structlog.PrintLoggerFactory(filepath), ) logger = structlog.getLogger() logger.info('test') This fails: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.8/site-packages/structlog/_base.py", line 189, in _proxy_to_logger args, kw = self._process_event(method_name, event, event_kw) File "/usr/local/lib/python3.8/site-packages/structlog/_base.py", line 149, in _process_event event_dict = proc(self._logger, method_name, event_dict) File "/usr/local/lib/python3.8/site-packages/structlog/stdlib.py", line 381, in filter_by_level if logger.isEnabledFor(_NAME_TO_LEVEL[name]): AttributeError: 'PrintLogger' object has no attribute 'isEnabledFor' Okay, sure. I am not supposed to use PrintLogger with stdlib processors. But I want to filter by log level (because that's how logging usually works, eh?) So how do I do that? I assume I need to use some other logger factory, but which one? Of course structlog.stdlib.LoggerFactory works, but it doesn't redirect to a file. So I said: okay I will create my own filter: def my_filter_by_level(logger, name, event_dict): if True: return event_dict else: raise DropEvent ... processors=[my_filter_by_level], And when I try to use the logger I get: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.8/site-packages/structlog/_base.py", line 190, in _proxy_to_logger return getattr(self._logger, method_name)(*args, **kw) TypeError: msg() got an unexpected keyword argument 'organization' This is coming from logger = logger.bind(**{"organization": "blah"}) but... why? What is wrong with my processor? | Well, the reason my filter didn't work is this: https://www.structlog.org/en/stable/processors.html#adapting Last filter in chain is special and can't just return a dictionary. And the following filter did the trick: def my_filter_by_level(logger, name, event_dict): this_level = structlog.stdlib._NAME_TO_LEVEL[name] set_level = structlog.stdlib._NAME_TO_LEVEL[loglevel] if this_level >= set_level: return event_dict else: raise structlog.DropEvent | 15 | 0 |
63,729,692 | 2020-9-3 | https://stackoverflow.com/questions/63729692/check-if-numpy-array-is-stored-in-shared-memory | In Python 3.8+, is it possible to check whether a numpy array is being stored in shared memory? In the following example, a numpy array sharedArr was created using the buffer of a multiprocessing.shared_memory.SharedMemory object. Will like to know if we can write a function that can detect whether SharedMemory is used. import numpy as np from multiprocessing import shared_memory if __name__ == '__main__': # Created numpy array `sharedArr`in shared memory arr = np.zeros(5) shm = shared_memory.SharedMemory(create=True, size=arr.nbytes) sharedArr = np.ndarray(arr.shape, dtype=arr.dtype, buffer=shm.buf) sharedArr[:] = arr[:] # How to tell if numpy array is stored in shared memory? print(type(sharedArr)) # <class 'numpy.ndarray'> print(hex(id(sharedArr))) # 0x7fac99469f30 shm.close() shm.unlink() | In this particular case, you can use the base attribute of the shared array. The attribute is a reference to the underlying object from which this array derives its memory. This is None for most arrays, to indicate that such an array owns its data. Running this code on my machine indicates that this array's base is a mmap object: >>> sharedArr.base <mmap.mmap at 0x11a4aa670> If you still have a reference to the shared memory object from which the array was allocated, you can compare the array's base to the shared memory segment's memory map: >>> sharedArr.base is shm._mmap True If you don't have the shm object lying around, as you wouldn't in a standalone function which could hypothetically perform this task, I doubt there's a portable and foolproof way to do it. Since NumPy provides its own memory-map object, it may suffice for your case to do the former check. That is, make the assumption that if the array is backed by a vanilla, builtin Python memory map, it is allocated from shared memory: import mmap def array_is_from_shared_memory(arr): return isinstance(arr.base, mmap.mmap) This works in your particular example, but you'd have to be careful with it, clearly document the assumptions that it makes, and test that it provides you with the actual information you need in your exact application. | 6 | 6 |
63,728,242 | 2020-9-3 | https://stackoverflow.com/questions/63728242/importerror-cannot-import-name-unknown-location | The project structure my_package βββ my_package β βββ __init__.py β βββ my_module.py βββ setup.py The module my_module.py has a single func function I am attempting to import. The setup.py file has the following content. from setuptools import setup, find_packages setup( name='my_package', packages=find_packages(where='my_package'), version='1.0' ) The import API I'm installing the package with: virtualenv --python=/usr/bin/python3.8 venv source venv/bin/activate python my_package/setup.py install To then import it with: import my_package from my_package import my_module However, the second import fails with: ImportError: cannot import name 'my_module' from 'my_package' (unknown location) Further more, running dir(my_package) reveals that indeed the my_module name did not get imported. ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__'] Similar questions on SO setup.py installed package can't be imported provided solution proved non sucessfull. ImportError: cannot import name 'Serial' from 'serial' (unknown location) adding a __init__.py file in my_package/my_package didn't work. Git repo I've placed an example of the issue at GitLab | You're running your test.py script in the parent directory of your my_package directory. As a result, test.py will try and import the my_package subdirectory as a package/module, not your installed package. You will need to move to a directory that doesn't contain your source code and then run test. This could be as simply as running it inside a subdirectory test in the my_package main directory. Just make sure you cd into that directory explicitly, instead of running it with a full path (like, for example, python3.8 my_package/test/test.py, because then it will still import the wrong my_package. The reason for this (and cause of your problem) is that Python automatically includes the current working directory in your sys.path, at the start, and will thus try and import the main my_package directory as a package. | 7 | 9 |
63,723,763 | 2020-9-3 | https://stackoverflow.com/questions/63723763/error-using-drive-mount-with-google-colab | I had been working on Colab using: from google.colab import drive .mount('/content/gdrive') with no problems, until today. I don't know why this error was raised: Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly&response_type=code Enter your authorization code: Β·Β·Β·Β·Β·Β·Β·Β·Β·Β· --------------------------------------------------------------------------- TIMEOUT Traceback (most recent call last) <ipython-input-4-d05fe204dd76> in <module>() 1 from google.colab import drive ----> 2 drive.mount('/content/gdrive') 4 frames /usr/local/lib/python3.6/dist-packages/google/colab/drive.py in mount(mountpoint, force_remount, timeout_ms, use_metadata_server) 223 oauth_prompt, 224 problem_and_stopped, --> 225 drive_exited, 226 ]) 227 if case == 0: /usr/local/lib/python3.6/dist-packages/pexpect/spawnbase.py in expect(self, pattern, timeout, searchwindowsize, async_, **kw) 342 compiled_pattern_list = self.compile_pattern_list(pattern) 343 return self.expect_list(compiled_pattern_list, --> 344 timeout, searchwindowsize, async_) 345 346 def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1, /usr/local/lib/python3.6/dist-packages/pexpect/spawnbase.py in expect_list(self, pattern_list, timeout, searchwindowsize, async_, **kw) 370 return expect_async(exp, timeout) 371 else: --> 372 return exp.expect_loop(timeout) 373 374 def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1, /usr/local/lib/python3.6/dist-packages/pexpect/expect.py in expect_loop(self, timeout) 179 return self.eof(e) 180 except TIMEOUT as e: --> 181 return self.timeout(e) 182 except: 183 self.errored() /usr/local/lib/python3.6/dist-packages/pexpect/expect.py in timeout(self, err) 142 exc = TIMEOUT(msg) 143 exc.__cause__ = None # in Python 3.x we can use "raise exc from None" --> 144 raise exc 145 146 def errored(self): TIMEOUT: <pexpect.popen_spawn.PopenSpawn object at 0x7f58fb7ab4e0> searcher: searcher_re: 0: re.compile('google.colab.drive MOUNTED') 1: re.compile('root@e7a376888b95-b97a84955c154714b7850ceb4ecf0e8e: ') 2: re.compile('(Go to this URL in a browser: https://.*)$') 3: re.compile('Drive File Stream encountered a problem and has stopped') 4: re.compile('drive EXITED') <pexpect.popen_spawn.PopenSpawn object at 0x7f58fb7ab4e0> searcher: searcher_re: 0: re.compile('google.colab.drive MOUNTED') 1: re.compile('root@e7a376888b95-b97a84955c154714b7850ceb4ecf0e8e: ') 2: re.compile('(Go to this URL in a browser: https://.*)$') 3: re.compile('Drive File Stream encountered a problem and has stopped') 4: re.compile('drive EXITED') As everyone knows, this code opens a new tab where you have to select a Google account, click on the 'Allow' button, and copy a long password to Colab EDIT: I tried to do the same in another way with: #Installing PyDrive !pip install PyDrive #Importing modules from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials #Authenticating and creating the PyDrive client auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) #Getting the file downloaded2 = drive.CreateFile({'id':"1QGtoo1wqCP2yrjl8kFu4kTfjWqh3EOdt"}) # replace the id with id of file you want to access downloaded2.GetContentFile('estructura_cc_felipe.xlsx') But it raises this error: Go to the following link in your browser: https://accounts.google.com/o/oauth2/auth?client_id=32555940559.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Faccounts.reauth+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&code_challenge=WkM1RS8Flu1_txc3jn4V_FfutgZuRaHSzYbDvs134PM&code_challenge_method=S256&access_type=offline&response_type=code&prompt=select_account Enter verification code: Β·Β·Β·Β·Β·Β·Β·Β·Β·Β· --------------------------------------------------------------------------- AuthorizationError Traceback (most recent call last) <ipython-input-2-bb96e063f8ef> in <module>() 6 7 #Authenticating and creating the PyDrive client ----> 8 auth.authenticate_user() 9 gauth = GoogleAuth() 10 gauth.credentials = GoogleCredentials.get_application_default() 1 frames /usr/local/lib/python3.6/dist-packages/google/colab/auth.py in authenticate_user(clear_output) 147 context_manager = _output.temporary if clear_output else _noop 148 with context_manager(): --> 149 _gcloud_login() 150 _install_adc() 151 colab_tpu_addr = _os.environ.get('COLAB_TPU_ADDR', '') /usr/local/lib/python3.6/dist-packages/google/colab/auth.py in _gcloud_login() 97 _os.remove(name) 98 if gcloud_process.returncode: ---> 99 raise _errors.AuthorizationError('Error fetching credentials') 100 101 AuthorizationError: Error fetching credentials Does anyone know what is wrong? I have been working for a long time importing files located on my Google drive and never had these problems. | It turns out that if you manually copy the auth code from the auth button instead of clicking the copy button, it works | 21 | 37 |
63,727,290 | 2020-9-3 | https://stackoverflow.com/questions/63727290/why-doesnt-python-give-any-error-when-quotes-around-a-string-do-not-match | I've started learning Python recently and I don't understand why Python behaves like this: >>> "OK" 'OK' >>> """OK""" 'OK' >>> "not Ok' File "<stdin>", line 1 "not Ok' ^ SyntaxError: EOL while scanning string literal >>> "not OK""" 'not OK' Why doesn't it give an error for the last statement as the number of quotes does not match? | The final """ is not recognized as a triple-quotation, but a single " (to close the current string literal) followed by an empty string ""; the two juxtaposed string literals are concatenated. The same behavior can be more readily recognized by putting a space between the closing and opening ". >>> "not OK" "" 'not OK' | 69 | 112 |
63,719,618 | 2020-9-3 | https://stackoverflow.com/questions/63719618/how-to-reduce-the-space-between-the-axes-and-the-first-and-last-bar | There is a big space between the border/x-axe of the graph and the first and last bar in a bar plot in pyplot (red arrows in the first picture). In the image below, it looks fine in the graph on the left, but it's wasting a lot of space in the graph on the right. The larger the graph, the larger the space. See how much space is wasted in the second picture: Any idea how to fix that? The code: plt.figure(figsize=figsize) grid = plt.GridSpec(figsize[1], figsize[0], wspace=120/figsize[0]) plt.suptitle(feature.upper()) # NaN plot plt.subplot(grid[:, :2]) plt.title('PrΓ©sence') plt.ylabel('occurences') plt.bar([0, 1], [df.shape[0] - nan, nan], color=['#4caf50', '#f44336']) plt.xticks([0, 1], ['RenseignΓ©', 'Absent'], rotation='vertical') # Distrib plot plt.subplot(grid[:, 2:]) plt.title('Distribution') x_pos = [i for i, _ in enumerate(sizes)] plt.bar(x_pos, sizes) plt.xticks(x_pos, labels, rotation='vertical') plt.show() df is my pandas DataFrame, nan the amount of null value for the feature I'm plotting, sizes is the number of occurrences for each value, and labels are the corresponding label's value. | You can use plt.margins(x=0, tight=True). The default margins are 0.05 which means that 5% of the distance between the first and last x-values is used as a margin. Choosing a small value such as plt.margins(x=0-01, tight=True) would leave a bit of margin, so the bars don't look glued to the axes. In some situations wider margins are desired. For example when drawing only two very narrow bars. So, the exact value for a plot to look nice depends on multiple factors as well as on personal preferences. Note that plt.margins is best called after the last function that adds elements to the plot. Also note that plt.xlim has a similar function of changing the drawing limits. Here is an example that sets xlim to have the same distance between the axes and the bars as between the bars themselves. import matplotlib.pyplot as plt fig, axes = plt.subplots(ncols=3, figsize=(12, 3)) for ax in axes: width = 0.4 ax.bar([0, 1, 2], [2, 3, 5], width=width, color='turquoise') if ax == axes[0]: ax.margins(x=0.01) ax.set_title('1% margins') elif ax == axes[1]: ax.margins(x=0.1) ax.set_title('10% margins') else: ax.set_xlim(-1+width/2, 3-width/2) ax.set_title('setting xlim') plt.show() | 9 | 11 |
63,718,559 | 2020-9-3 | https://stackoverflow.com/questions/63718559/finding-most-similar-sentences-among-all-in-python | Suggestions / refer links /codes are appreciated. I have a data which is having more than 1500 rows. Each row has a sentence. I am trying to find out the best method to find the most similar sentences among all. What I have tried I have tried K-mean algorithm which groups similar sentences in a cluster. But I found a drawback in which I have to pass K to create a cluster. It is hard to guess K. I tried elbo method to guess the clusters but grouping all together isn't sufficient. In this approach I am getting all the data grouped. I am looking for data which is similar above 0.90% data should be returned with ID. I tried cosine similarity in which I used TfidfVectorizer to create matrix and then passed in cosine similarity. Even this approach didn't worked properly. What I am looking for I want an approach where I can pass a threshold example 0.90 data in all rows which are similar to each other above 0.90% should be returned as a result. Data Sample ID | DESCRIPTION ----------------------------- 10 | Cancel ASN WMS Cancel ASN 11 | MAXPREDO Validation is corect 12 | Move to QC 13 | Cancel ASN WMS Cancel ASN 14 | MAXPREDO Validation is right 15 | Verify files are sent every hours for this interface from Optima 16 | MAXPREDO Validation are correct 17 | Move to QC 18 | Verify files are not sent Expected result Above data which are similar upto 0.90% should get as a result with ID ID | DESCRIPTION ----------------------------- 10 | Cancel ASN WMS Cancel ASN 13 | Cancel ASN WMS Cancel ASN 11 | MAXPREDO Validation is corect # even spelling is not correct 14 | MAXPREDO Validation is right 16 | MAXPREDO Validation are correct 12 | Move to QC 17 | Move to QC | Why did it not work for you with cosine similarity and the TFIDF-vectorizer? I tried it and it works with this code: import pandas as pd import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity df = pd.DataFrame(columns=["ID","DESCRIPTION"], data=np.matrix([[10,"Cancel ASN WMS Cancel ASN"], [11,"MAXPREDO Validation is corect"], [12,"Move to QC"], [13,"Cancel ASN WMS Cancel ASN"], [14,"MAXPREDO Validation is right"], [15,"Verify files are sent every hours for this interface from Optima"], [16,"MAXPREDO Validation are correct"], [17,"Move to QC"], [18,"Verify files are not sent"] ])) corpus = list(df["DESCRIPTION"].values) vectorizer = TfidfVectorizer() X = vectorizer.fit_transform(corpus) threshold = 0.4 for x in range(0,X.shape[0]): for y in range(x,X.shape[0]): if(x!=y): if(cosine_similarity(X[x],X[y])>threshold): print(df["ID"][x],":",corpus[x]) print(df["ID"][y],":",corpus[y]) print("Cosine similarity:",cosine_similarity(X[x],X[y])) print() The threshold can be adjusted as well, but will not yield the results you want with a threshold of 0.9. The output for a threshold of 0.4 is: 10 : Cancel ASN WMS Cancel ASN 13 : Cancel ASN WMS Cancel ASN Cosine similarity: [[1.]] 11 : MAXPREDO Validation is corect 14 : MAXPREDO Validation is right Cosine similarity: [[0.64183024]] 12 : Move to QC 17 : Move to QC Cosine similarity: [[1.]] 15 : Verify files are sent every hours for this interface from Optima 18 : Verify files are not sent Cosine similarity: [[0.44897995]] With a threshold of 0.39 all your expected sentences are features in the output, but an additional pair with the indices [15,18] can be found as well: 10 : Cancel ASN WMS Cancel ASN 13 : Cancel ASN WMS Cancel ASN Cosine similarity: [[1.]] 11 : MAXPREDO Validation is corect 14 : MAXPREDO Validation is right Cosine similarity: [[0.64183024]] 11 : MAXPREDO Validation is corect 16 : MAXPREDO Validation are correct Cosine similarity: [[0.39895808]] 12 : Move to QC 17 : Move to QC Cosine similarity: [[1.]] 14 : MAXPREDO Validation is right 16 : MAXPREDO Validation are correct Cosine similarity: [[0.39895808]] 15 : Verify files are sent every hours for this interface from Optima 18 : Verify files are not sent Cosine similarity: [[0.44897995]] | 6 | 12 |
63,718,582 | 2020-9-3 | https://stackoverflow.com/questions/63718582/split-time-range-into-multiple-time-periods-based-on-interval-in-python | I have a time-range and an interval, I need to split the time range into multiple time periods based on interval value. For example, time range is 9:30 to 11:30 and the interval is 30, the output time periods should be in a list as datetime objects Output: [ 2020-08-24 9:30 - 2020-08-24 10:00, 2020-08-24 10:00 - 2020-08-24 10:30 2020-08-24 10:30 - 2020-08-24 11:00, 2020-08-24 11:00 - 2020-08-24 11:30 ] | You can do arithmetic on datetime objects by adding timedelta objects. You probably need to decide exactly what behaviour is required if the interval per period is not an exact divisor of the total, but this example would give a final short period in that case. import datetime tstart = datetime.datetime(2020,8,24,9,30) tend = datetime.datetime(2020,8,24,11,30) interval = datetime.timedelta(minutes=30) periods = [] period_start = tstart while period_start < tend: period_end = min(period_start + interval, tend) periods.append((period_start, period_end)) period_start = period_end print(periods) This gives (with newlines inserted for readability): [(datetime.datetime(2020, 8, 24, 9, 30), datetime.datetime(2020, 8, 24, 10, 0)), (datetime.datetime(2020, 8, 24, 10, 0), datetime.datetime(2020, 8, 24, 10, 30)), (datetime.datetime(2020, 8, 24, 10, 30), datetime.datetime(2020, 8, 24, 11, 0)), (datetime.datetime(2020, 8, 24, 11, 0), datetime.datetime(2020, 8, 24, 11, 30))] For the string output format that you want, you could do something like this: def format_time(dt): return dt.strftime("%Y-%m-%d %H:%M") print(['{} - {}'.format(format_time(start), format_time(end)) for start, end in periods]) to give: ['2020-08-24 09:30 - 2020-08-24 10:00', '2020-08-24 10:00 - 2020-08-24 10:30', '2020-08-24 10:30 - 2020-08-24 11:00', '2020-08-24 11:00 - 2020-08-24 11:30'] | 6 | 5 |
63,718,246 | 2020-9-3 | https://stackoverflow.com/questions/63718246/how-to-generate-2d-mesh-from-two-1d-arrays-and-convert-it-into-a-dataframe | For example, I have two arrays: import numpy as np x = np.array([1,2,3]) y = np.array([10, 11]) How can I generate a pandas dataframe with every combination of x and y, like below? x y 1 10 1 11 2 10 2 11 3 10 3 11 | import pandas as pd import numpy as np x = np.array([1,2,3]) y = np.array([10, 11]) pd.DataFrame({'x':np.repeat(x,y.shape[0]), 'y':np.tile(y,x.shape[0])}) yields: x y 0 1 10 1 1 11 2 2 10 3 2 11 4 3 10 5 3 11 | 6 | 3 |
63,713,241 | 2020-9-2 | https://stackoverflow.com/questions/63713241/segmentation-fault-using-python-shared-memory | The function store_in_shm writes a numpy array to the shared memory while the second function read_from_shm creates a numpy array using data in the same shared memory space and returns the numpy array. However, running the code in Python 3.8 gives the following segmentation error: zsh: segmentation fault python foo.py Why is there no problem accessing the numpy array from inside the function read_from_shm, but a segmentation error appears when accessing the numpy array again outside of the function? Output: From read_from_shm(): [0 1 2 3 4 5 6 7 8 9] zsh: segmentation fault python foo.py % /Users/athena/opt/anaconda3/envs/test/lib/python3.8/multiprocessing/resource_tracker.py:203: UserWarning: resource_tracker: There appear to be 1 leaked shared_memory objects to clean up at shutdown warnings.warn('resource_tracker: There appear to be %d ' foo.py import numpy as np from multiprocessing import shared_memory def store_in_shm(data): shm = shared_memory.SharedMemory(name='foo', create=True, size=data.nbytes) shmData = np.ndarray(data.shape, dtype=data.dtype, buffer=shm.buf) shmData[:] = data[:] shm.close() return shm def read_from_shm(shape, dtype): shm = shared_memory.SharedMemory(name='foo', create=False) shmData = np.ndarray(shape, dtype, buffer=shm.buf) print('From read_from_shm():', shmData) return shmData if __name__ == '__main__': data = np.arange(10) shm = store_in_shm(data) shmData = read_from_shm(data.shape, data.dtype) print('From __main__:', shmData) # no seg fault if we comment this line shm.unlink() | Basically the problem seems to be that the underlying mmap'ed file (owned by shm within read_from_shm) is being closed when shm is garbage collected when the function returns. Then shmData refers back to it, which is where you get the segfault (for referring to a closed mmap) This seems to be a known bug, but it can be solved by keeping a reference to shm. Additionally all SharedMemory instances want to be close()'d with exactly one of them being unlink()'ed when it is no longer necessary. If you don't call shm.close() yourself, it will be called at GC as mentioned, and on Windows if it is the only one currently "open" the shared memory file will be deleted. When you call shm.close() inside store_in_shm, you introduce an OS dependency as on windows the data will be deleted, and MacOS and Linux, it will retain until unlink is called. Finally though this doesn't appear in your code, another problem currently exists where accessing data from independent processes (rather than child processes) can similarly delete the underlying mmap too soon. SharedMemory is a very new library, and hopefully all the kinks will work out soon. You can re-write the given example to retain a reference to the "second" shm and just use either one to unlink: import numpy as np from multiprocessing import shared_memory def store_in_shm(data): shm = shared_memory.SharedMemory(name='foo', create=True, size=data.nbytes) shmData = np.ndarray(data.shape, dtype=data.dtype, buffer=shm.buf) shmData[:] = data[:] #there must always be at least one `SharedMemory` object open for it to not # be destroyed on Windows, so we won't `shm.close()` inside the function, # but rather after we're done with everything. return shm def read_from_shm(shape, dtype): shm = shared_memory.SharedMemory(name='foo', create=False) shmData = np.ndarray(shape, dtype, buffer=shm.buf) print('From read_from_shm():', shmData) return shm, shmData #we need to keep a reference of shm both so we don't # segfault on shmData and so we can `close()` it. if __name__ == '__main__': data = np.arange(10) shm1 = store_in_shm(data) #This is where the *Windows* previously reclaimed the memory resulting in a # FileNotFoundError because the tempory mmap'ed file had been released. shm2, shmData = read_from_shm(data.shape, data.dtype) print('From __main__:', shmData) shm1.close() shm2.close() #on windows "unlink" happens automatically here whether you call `unlink()` or not. shm2.unlink() #either shm1 or shm2 | 6 | 7 |
63,712,706 | 2020-9-2 | https://stackoverflow.com/questions/63712706/sql-server-pivot-one-column-and-keep-other-columns | I am trying to pivot a table in SQL Server (52M+ observations) however I am not getting the results I need. There are 15 descriptions each with a value that I need to pivot. Original Dataframe: ID | Date | Description| Value ------------------------------------------------- P1 | 2016-12-31 | ABC | 900 P2 | 2016-11-30 | XYZ | 800 P3 | 2016-10-31 | MNO | 700 Desired Results ID | Date | ABC | XYZ | MNO ------------------------------------------------- P1 | 2016-12-31 | 900 | | P2 | 2016-11-30 | | 800 | P3 | 2016-10-31 | | | 700 I have tried pivoting this in PySpark and SQL, but have not gotten a working result. SQL Attempt: SELECT [Date] ,[ID] ,[Description] ,[Value] FROM [DB].[TABLE] WHERE ( ([Description] IN ('ABC','XYZ', 'MNO')) PIVOT( COUNT([Value]) FOR Description IN ( [ABC], [XYZ], [MNO]) ) AS pivot_table; I tried this in Pyspark however it doesnt work either: df.groupBy("ID","Date").pivot("Description").sum("Value") | Use conditional aggregation: select id, date, max(case when description = 'ABC' then value end) as abc, max(case when description = 'DEF' then value end) as def, max(case when description = 'MNO' then value end) as mno from mytable group by id, date | 6 | 7 |
63,706,985 | 2020-9-2 | https://stackoverflow.com/questions/63706985/convert-sha256-digest-to-uuid-in-python | Given a sha256 hash of a str in python: import hashlib hash = hashlib.sha256('foobar'.encode('utf-8')) How can the hash be converted to a UUID? Note: there will obviously be a many-to-one mapping of hexdigest to UUID given that a hexdigest has 2^256 possible values and a UUID has 2^128. Thank you in advance for your consideration and response. | Given that UUID takes a 32 hex character input string and hexdigest produces 64 characters, a simple approach would be to sub-index the resulting hash digest to achieve the appropriate string length: import hashlib import uuid hash = hashlib.sha256('foobar'.encode('utf-8')) uuid.UUID(hash.hexdigest()[::2]) | 6 | 9 |
63,702,163 | 2020-9-2 | https://stackoverflow.com/questions/63702163/vs-code-does-not-change-python-environment | I am using VS-Code and anaconda environment for python interpreter. I select the exact anaconda base environment by ctrl + shift + ` and it also reflects in the downside panel of vscode. But, when I checked the python version it shows my system's default python environment 3.7.9. If you see the below screenshot than, the anaconda environment is with 3.8.3. Please give me solution, Thank you. | To check & change vs code interpreter: In top left menu bar Click view In the dropdown menu, Click Command Palette Click Python: Select Interpreter Choose & Click on your desired Interpreter Another way to be sure to use anconda interpreter, open anaconda navigator and launch vs code from there. original vs code How-To | 6 | -3 |
63,597,239 | 2020-8-26 | https://stackoverflow.com/questions/63597239/is-there-any-post-load-in-pydantic | Previously I used the marshmallow library with the Flask. Some time ago I have tried FastAPI with Pydantic. At first glance pydantic seems similar to masrhmallow but on closer inspection they differ. And for me the main difference between them is post_load methods which are from marshmallow. I can't find any analogs for it in pydantic. post_load is decorator for post-processing methods. Using it I can handle return object on my own, can do whatever I want: class ProductSchema(Schema): alias = fields.Str() category = fields.Str() brand = fields.Str() @post_load def check_alias(self, params, **kwargs): """One of the fields must be filled""" if not any([params.get('alias'), params.get('category'), params.get('brand')]): raise ValidationError('No alias provided', field='alias') return params Besides it used not only for validation. Code example is just for visual understanding, do not analyze it, I have just invented it. So my question is: is there any analog for post_load in pydantic? | It is not obvious but pydantic's validator returns value of the field. Pydantic v1 There are two ways to handle post_load conversions: validator and root_validator. validator gets the field value as argument and returns its value. root_validator is the same but manipulates with the whole object. from pydantic import validator, root_validator class PaymentStatusSchema(BaseModel): order_id: str = Param(..., title="Order id in the shop") order_number: str = Param(..., title="Order number in chronological order") status: int = Param(..., title="Payment status") @validator("status") def convert_status(cls, status): return "active" if status == 1 else "inactive" @root_validator def validate_order_id(cls, values): """Check order id""" if not values.get('orderNumber') and not values.get('mdOrder'): raise HTTPException(status_code=400, detail='No order data provided') return values By default pydantic runs validators as post-processing methods. For pre-processing you should use validators with pre argument: @root_validator(pre=True) def validate_order_id(cls, values): """Check order id""" # some code here return values Pydantic v2 In Pydantic v2 validators migrated: validator to field_validator and root_validator to model_validator. @field_validator('status') @classmethod def convert_status(cls, status: int): return "active" if status == 1 else "inactive" @model_validator(mode='after') @classmethod def validate_order_id(cls, values): """Check order id""" if not values.get('orderNumber') and not values.get('mdOrder'): raise HTTPException(status_code=400, detail='No order data provided') return values For post or pre-processing use mode parameter. | 12 | 18 |
63,623,930 | 2020-8-27 | https://stackoverflow.com/questions/63623930/how-to-create-unit-test-for-a-python-telegram-bot | I've built this Telegram Bot in Python, with python-telegram-bot. It's not so complex, but I want to do some regression tests to check if everything works fine after a new feature or a change, and more generally to test specific features to find bugs/edge cases. How can I achieve this? For now, I'm doing this manually, clicking bot's keyboard and typing some text. | Have you looked to unit tests that are present in python-telegram-bot library? I think it is a good place to start. For example, in this file (historical version) you can see how to test a dialog with bot that uses ConversationHandler. | 9 | 5 |
63,609,570 | 2020-8-27 | https://stackoverflow.com/questions/63609570/mysql-values-function-is-deprecated | This is my python code which prints the sql query. def generate_insert_statement(column_names, values_format, table_name, items, insert_template=INSERT_TEMPLATE, ): return insert_template.format( column_names=",".join(column_names), values=",".join( map( lambda x: generate_raw_values(values_format, x), items ) ), table_name=table_name, updates_on=create_updates_on_columns(column_names) ) query = generate_insert_statement(table_name=property['table_name'], column_names=property['column_names'], values_format=property['values_format'], items=batch) print(query) #here execute_commit(query) When printing the Mysql query my Django project shows following error in the terminal: 'VALUES function' is deprecated and will be removed in a future release. Please use an alias (INSERT INTO ... VALUES (...) AS alias) and replace VALUES(col) in the ON DUPLICATE KEY UPDATE clause with alias.col instead Mysql doumentation does not say much about it.What does this mean and how to can i rectify it. INSERT_TEMPLATE = "INSERT INTO {table_name} ({column_names}) VALUES {values} ON DUPLICATE KEY UPDATE {updates_on};" | Basically, mysql is looking toward removing a longstanding non-standard use of the values function to clear the way for some future work where the SQL standard allows using a VALUES keyword for something very different, and because how the VALUES function works in subqueries or not in a ON DUPLICATE KEY UPDATE clause can be surprising. You need to add an alias to the VALUES clause and then use that alias instead of the non-standard VALUES function in the ON DUPLICATE KEY UPDATE clause, e.g. change INSERT INTO foo (bar, baz) VALUES (1,2) ON DUPLICATE KEY UPDATE baz=VALUES(baz) to INSERT INTO foo (bar, baz) VALUES (1,2) AS new_foo ON DUPLICATE KEY UPDATE baz=new_foo.baz (This only works on mysql 8+, not on older versions or in any version of mariadb through at least 11.0.1) Note that this is no different if you are updating multiple rows: INSERT INTO foo (bar, baz) VALUES (1,2),(3,4),(5,6) AS new_foo ON DUPLICATE KEY UPDATE baz=new_foo.baz From https://dev.mysql.com/worklog/task/?id=13325: According to the SQL standard, VALUES is a table value constructor that returns a table. In MySQL this is true for simple INSERT and REPLACE statements, but MySQL also uses VALUES to refer to values in INSERT ... ON DUPLICATE KEY UPDATE statements. E.g.: INSERT INTO t(a,b) VALUES (1, 2) ON DUPLICATE KEY UPDATE a = VALUES (b) + 1; VALUES (b) refers to the value for b in the table value constructor for the INSERT, in this case 2. To make the value available in simple arithmetic expressions, it is part of the parser rule for simple_expr. Unfortunately, this also means that VALUES can be used in this way in a lot of other statements, e.g.: SELECT a FROM t WHERE a=VALUES(a); In all such statements, VALUES returns NULL, so the above query would not have the intended effect. The only meaningful usage of VALUES as a function, rather than a table value constructor, is in INSERT ... ON DUPLICATE KEY UPDATE. Also, the non-standard use in INSERT ... ON DUPLICATE KEY UPDATE does not extend to subqueries. E.g.: INSERT INTO t1 VALUES(1,2) ON DUPLICATE KEY UPDATE a=(SELECT a FROM t2 WHERE b=VALUES(b)); This does not do what the user expects. VALUES(b) will return NULL, even if it is in an INSERT .. ON DUPLICATE KEY UPDATE statement. The non-standard syntax also makes it harder (impossible?) to implement standard behavior of VALUES as specified in feature F641 "Row and table constructors". | 17 | 42 |
63,696,833 | 2020-9-1 | https://stackoverflow.com/questions/63696833/how-to-clear-the-conda-environment-variables | While I was setting an environment variable on a conda base env, I made an error in the path that was supposed to be assigned to the variable. I was trying to set the $PYSPARK_PYTHON env variable on the conda env. The set command conda env config vars set $PYSPARK_PYTHON=errorpath executed successfully even though the path has an error, and asked me to reactivate the environment. And I am unable to activate the env. When I check the env var list by doing the following: conda env config vars list -n base It shows me the incorrect path which I have set but without the variable name as follows: = C:\\ProgramData\\Anaconda3\\envs\\some-env\\python3.7 And because of this above incorrect env variable, I am unable to activate the base env. It gives me an error as follows: Invoke-Expression : At line:6 char:1 + $Env: = "C:\\ProgramData\\Anaconda3\\envs\\some-env\\python3.7" + ~~~~~ Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. At C:\ProgramData\Anaconda3\shell\condabin\Conda.psm1:101 char:9 + Invoke-Expression -Command $activateCommand; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException + FullyQualifiedErrorId : InvalidVariableReferenceWithDrive,Microsoft.PowerShell.Commands.InvokeExpressionCommand I am not sure how to fix this error, but I want to just remove the environment variable from the base env. I tried unsetting it using the command conda env config vars unset $PYSPARK_PYTHON -n base. But it doesn't work. I think as the variable declaration is missing in the list, I am unable to access the variable. I did try it without the $PYSPARK_PYTHON hoping it removes all the orphaned env variables but it doesn't. Could anyone help me with this? Is there any way to reset the base environment without affecting the other envs, or reset the env variables list on the given env? Thanks | Try looking for a JSON file called state that resides in the conda-meta directory of your environment. Depending on your OS and install directory the conda-meta will be installed in different locations. The default install path for each OS is Windows: C:\Users\<your-username>\Anaconda3\conda-meta\state Mac:/Users/<your-username>/anaconda3/conda-meta/state or ~/opt//anaconda3/conda-meta/state for GUI install Linux:/home/<your-username>/anaconda3/conda-meta/state By editing that file you can manually change your environment variables. Further Explanation I recently messed up a conda environment too and only found this answer through inspecting the code for conda. In the code you can see that the environment variables are saved and loaded from a file def _get_environment_state_file(self): env_vars_file = join(self.prefix_path, PREFIX_STATE_FILE) if lexists(env_vars_file): with open(env_vars_file, 'r') as f: prefix_state = json.loads(f.read(), object_pairs_hook=OrderedDict) else: prefix_state = {} return prefix_state def get_environment_env_vars(self): prefix_state = self._get_environment_state_file() env_vars_all = OrderedDict(prefix_state.get('env_vars', {})) env_vars = { k: v for k, v in env_vars_all.items() if v != CONDA_ENV_VARS_UNSET_VAR } return env_vars If you print env_vars_file or look where PREFIX_STATE_FILE is defined you will find the file the environment variables are stored in for the environment. | 9 | 13 |
63,693,550 | 2020-9-1 | https://stackoverflow.com/questions/63693550/system-libraries-in-conda-environment-not-seen-by-reticulate | I'm trying to get the R package reticulate working on a CentOS 7.8 system using RStudio Server v1.2.5042 with a custom environment created with conda. When I initiate a Python job with reticulate, I get an error that some system libraries are not the correct versions, specifically, libstdc++.so.6 and libz.so.1. First off, I realize CentOS 7.8 is a bit old and some of the problem might be solved by upgrading the OS, but that's not an option in this case. The conda environment does work and I can run the target Python script in a terminal window without any errors. In RStudio using reticulate, the code is extremely simple at this point: library(reticulate) use_condaenv('test') py_run_file('test_script.py') When the script is run, I get the following error: ImportError: /lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by /home/<user>/.conda/envs/test/lib/python3.8/site-packages/scipy/_lib/_uarray/_uarray.cpython-38-x86_64-linux-gnu.so) When I look into the /usr/lib64 directory, I find libstdc++.so, but running strings libstdc++.so | grep ^GLIBC | sort shows me that it indeed does not support version GLIBCXX 3.4.21. No surprises. If I navigate to the /home/<user>/.conda/envs/test/lib directory, I find another copy of libstdc++.so.6 and this one does support version GLIBCXX 3.4.21. So, the correct version of the library is present in the correct conda environment directory, but for some reason RStudio and reticulate are not finding it. I tried changing LD_LIBRARY_PATH to have the conda environment directory listed first, but that does not work. I found a lengthy discussion here, which points out that LD_LIBRARY_PATH isn't really a good fix unless it is set prior to the RStudio process initialization. (And then goes on a tangent about which version of Python gets used.) For my situation, there may be multiple conda environments to support and it isn't possible to know which will be active for any given session, and any given user my use different/multiple environments. I would rather not try to harmonize all conda environments into one, big, uber-environment. I've also verified that the Python version and other libraries are correctly set: python: /home/<user>/.conda/envs/test/bin/python libpython: /home/<user>/.conda/envs/test/lib/libpython3.8.so pythonhome: /home/<user>/.conda/envs/test:/home/<user>/.conda/envs/test version: 3.8.5 (default, Aug 5 2020, 08:36:46) [GCC 7.3.0] numpy: /home/<user>/.conda/envs/test/lib/python3.8/site-packages/numpy numpy_version: 1.19.1 NOTE: Python version was forced by use_python function I have been able to get it running by resetting the links in /usr/lib64 to point to the copy in the conda directory. While this gets it working for this instance, I'm not sure I want to push a fix like this to production. My guess is that if I link to the most inclusive version of the library across all conda environments, and that version fully supports all versions that the system level library supports, everything will be fine, but this feels like a hack, at best. If anyone has found a good solution to this, I would appreciate to know the details. | After struggling with a similar issue for several days, and trying many of the suggested solutions on the web (mostly based on symlinks, LD_LIBRARY_PATH variable, or installing/upgrading/downgrading packages like libgcc), I finally found something that is only mentioned once here : https://github.com/rstudio/reticulate/issues/338#issuecomment-415472406 The problem possibly seems to be a conflict when R is installed on the OS (with apt-get r-base for example) rather than with (Ana/Mini)conda. In that case, it will try to load system libraries rather than conda environment ones. So here is a possible solution to people still having this kind of issue, that worked for me : (maybe optional) uninstall R on the local system : apt-get remove r-base r-base-dev Activate conda environment : conda activate my_R_env Install R within this environment : conda install r r-essentials --channel conda-forge Install R packages like reticulate inside the same env : conda install r-reticulate --channel conda-forge You can check that your Python packages installed within your conda environment are now properly loaded with reticulate : R > library(reticulate) > repl_python() >>> import pandas or any package that was causing the initial issue Note : I still had some issues due to R loading base conda environment instead of activated one, but deactivating/reactivating environments or calling use_condaenv('my_R_env') seems to solve the problem. | 7 | 2 |
63,648,752 | 2020-8-29 | https://stackoverflow.com/questions/63648752/requests-exceptions-connectionerror-connection-aborted-remotedisconnected | I'm trying to connect to https://apis.digital.gob.cl/fl/feriados/2020, but I get an requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) error on a script that works perfectly with other URLs. The code: import requests response = requests.get('https://apis.digital.gob.cl/fl/feriados/2020') print(response.status_code) | The issue is that the website filters out requests without a proper User-Agent, so just use a random one from MDN: requests.get("https://apis.digital.gob.cl/fl/feriados/2020", headers={ "User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" }) | 15 | 20 |
63,624,633 | 2020-8-27 | https://stackoverflow.com/questions/63624633/pandas-info-not-showing-all-columns-and-datatypes | I am have imported a csv file onto my Jupyter notebook and trying to obtain all the columns names and datatypes using the info() function. However, I get the following image. Any idea how to resolve it? I can't view all the columns and datatypes, only this vague information Thanks! | use verbose as argument to info, it gives option to print the full summary. see full documentation here You can also use show_counts (or null_counts for older pandas version since it was deprecated since pandas 1.2.0) argument to see null count information For pandas >= 1.2.0: df.info(verbose=True, show_counts=True) For pandas <1.2.0: df.info(verbose=True, null_counts=True) | 13 | 38 |
63,654,232 | 2020-8-30 | https://stackoverflow.com/questions/63654232/pytorch-dataloader-extremely-slow-first-epoch | When I create a PyTorch DataLoader and start iterating -- I get an extremely slow first epoch (x10--x30 slower then all next epochs). Moreover, this problem occurs only with the train dataset from the Google landmark recognition 2020 from Kaggle. I can't reproduce this on synthetic images, also, I tried to create a folder with 500k images from GLR2020, and everything worked well. Found few similar problems in the PyTorch forum without any solutions. import argparse import pandas as pd import numpy as np import os, sys import multiprocessing, ray import time import cv2 import logging import albumentations as albu from torch.utils.data import Dataset, DataLoader samples = 50000 # count of samples to speed up test bs = 64 # batch size dir = '/hdd0/datasets/ggl_landmark_recognition_2020/train' # directory with train data all_files = pd.read_csv('/hdd0/datasets/ggl_landmark_recognition_2020/train.csv') files = np.random.choice(all_files.id.values, 50000) files = [os.path.join(_[0], _[1], _[2], _+'.jpg') for _ in files] # augmentations aug = albu.Compose([albu.Resize(400, 400), albu.Rotate(limit=15), albu.ChannelDropout(p=0.1), albu.Normalize(),]) class ImgDataset: def __init__(self, path, files, augmentation = None): self.path = path self.files = {k:v for k, v in enumerate(files)} self.augmentation = augmentation def __len__(self): return len(self.files) def __getitem__(self, idx): img_name = self.files[idx] img = np.array(cv2.imread(os.path.join(self.path, img_name))) if self.augmentation is not None: return self.augmentation(image=img)['image'] dtset = ImgDataset(dir,files, aug) torchloader = DataLoader(dataset= dtset, batch_size=64, num_worker=16, shuffle=True) for _ in range(3): t1 = time.time() for idx, val in enumerate(torchloader): pass t2 = time.time() print(str(t2-t1) +' sec') Here are some examples of execution speed with different num_workers in DataLoader #num_workers=0 273.1584792137146 sec 83.15653467178345 sec 83.67923021316528 sec # num_workers = 8 165.62366938591003 sec 10.405716896057129 sec 10.495309114456177 sec # num_workers = 16 156.60744667053223 sec 8.051618099212646 sec 7.922858238220215 sec Looks like the problem is not with DataLoader, but with dataset. When I delete and reinitialise DataLoader object after first "long" iteration, everything still works fine. When I reinitialise dataset -- long first iteration appears again. Moreover, I tracked my cpu utilisation via htop during this epochs with num_workers setted to 32, and during the first epoch, utilisation is really low; only 1-2 of 32 cores are working, during other epochs ~all cores are working. | Slavka, TLDR: This is a caching effect. I did not download the whole GLR2020 dataset but I was able to observe this effect on the image dataset that I had locally (80000 jpg images of approx 400x400 size). To find the reasons for the difference in performance I tried the following: reducing the augmentation to just resizing testing just ImgDataset.__getitem__() function ImgDataset.__getitem__() without augmentation just loading the raw jpg image and passing it from the dataset without even numpy conversion. It turns out that the difference comes from the image loading timing. Python (or OS itself) implements some kind of caching which is observed when loading image multiple times in the following test. for i in range(5): t0 = time.time() data = cv2.imread(filename) print (time.time() - t0) 0.03395271301269531 0.0010004043579101562 0.0010004043579101562 0.0010008811950683594 0.001001119613647461 same is observed when just reading from file to variable for i in range(5): t0 = time.time() with open(filename, mode='rb') as file: data = file.read() print (time.time() - t0) 0.036234378814697266 0.0028831958770751953 0.0020024776458740234 0.0031833648681640625 0.0028734207153320312 One way to reduce the loading speed is to keep the data on very fast local SSD. If size allows, try loading part of the dataset into RAM and writing custom dataloader to feed from there... BTW Based on my findings this effect should be reproducible with any dataset - see if you used different drives or some caching. | 16 | 17 |
63,682,956 | 2020-9-1 | https://stackoverflow.com/questions/63682956/fastapi-retrieve-url-from-view-name-route-name | Suppose I have following views, from fastapi import FastAPI app = FastAPI() @app.get('/hello/') def hello_world(): return {"msg": "Hello World"} @app.get('/hello/{number}/') def hello_world_number(number: int): return {"msg": "Hello World Number", "number": number} I have been using these functions in Flask and Django Flask: url_for(...) Django: reverse(...) So, how can I obtain/build the URLs of hello_world and hello_world_number in a similar way? | We have got Router.url_path_for(...) method which is located inside the starlette package Method-1: Using FastAPI instance This method is useful when you are able to access the FastAPI instance in your current context. (Thanks to @Yagizcan Degirmenci) from fastapi import FastAPI app = FastAPI() @app.get('/hello/') def hello_world(): return {"msg": "Hello World"} @app.get('/hello/{number}/') def hello_world_number(number: int): return {"msg": "Hello World Number", "number": number} print(app.url_path_for('hello_world')) print(app.url_path_for('hello_world_number', number=1)) print(app.url_path_for('hello_world_number', number=2)) # Results "/hello/" "/hello/1/" "/hello/2/" Drawback If we are using APIRouter, router.url_path_for('hello_world') may not work since router isn't an instance of FastAPI class. That is, we must have the FastAPI instance to resolve the URL Method-2: Request instance This method is useful when you are able to access the Request instance (the incoming request), usually, within a view. from fastapi import FastAPI, Request app = FastAPI() @app.get('/hello/') def hello_world(): return {"msg": "Hello World"} @app.get('/hello/{number}/') def hello_world_number(number: int): return {"msg": "Hello World Number", "number": number} @app.get('/') def named_url_reveres(request: Request): return { "URL for 'hello_world'": request.url_for("hello_world"), "URL for 'hello_world_number' with number '1'": request.url_for("hello_world_number", number=1), "URL for 'hello_world_number' with number '2''": request.url_for("hello_world_number", number=2}) } # Result Response { "URL for 'hello_world'": "http://0.0.0.0:6022/hello/", "URL for 'hello_world_number' with number '1'": "http://0.0.0.0:6022/hello/1/", "URL for 'hello_world_number' with number '2''": "http://0.0.0.0:6022/hello/2/" } Drawback We must include the request parameter in every (or required) view to resolve the URL, which might raise an ugly feel to developers. | 39 | 63 |
63,678,723 | 2020-8-31 | https://stackoverflow.com/questions/63678723/is-there-a-python-equivalent-to-template-literals-in-javascript | To provide a basic example, say I wanted to write: name = str(input()) age = int(input()) print('Hi, {name}, you are {age}.') In javascript, this would look like: console.log(`Hi, ${name}, you are ${age}.`) I assume there is no direct implementation of template literals in Python, as I haven't found any mention on Google / DDG. If I am correct in thinking that there isn't a direct implementation, have any of you found workarounds? Thanks in advance. | You can go with formatted string literals ("f-strings") since Python 3.6 f"Hi {name}, you are {age}" Or string formatting "Hi {}, you are {}".format(name, age) "Hi {name}, you are {age}".format(name=name, age=age) Or format specifiers "Hi %s, you are %d" % (name, age) | 43 | 81 |
63,643,687 | 2020-8-29 | https://stackoverflow.com/questions/63643687/import-tkinter-if-this-fails-your-python-may-not-be-configured-for-tk-error-i | Currently using Ubuntu 20.04 LTS with python3.8.5. Its my first time using ubuntu with absolutely no previous knowledge of terminal.SO,would love to have a detailed answer if possible. Below is terminal output when i try importing tkinter in python3. >>> import tkinter Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.8/tkinter/__init__.py", line 36, in <module> import _tkinter # If this fails your Python may not be configured for Tk ModuleNotFoundError: No module named '_tkinter' >>> I have reinstalled python3 and tkinter using sudo apt.But still it shows same error. When i run the same command in python IDLE it works without any error. I hope this explains my problem clearly, if any other info. is required pls reply. I also tried running the command >>>from tkinter import * | Resolved the issue it occurred because the Tkinter was installed for version 3.5 and not for the 3.8 version. For that, I installed the 3.5 version and kept only one version i.e. 3.8, and installed Tkinter again, and it worked! This is just a workaround to make things work, but the more preferred way is to create a venv and then install the particular versions of python and libraries that are needed. | 11 | 1 |
63,656,333 | 2020-8-30 | https://stackoverflow.com/questions/63656333/reduction-parameter-in-tf-keras-losses | According to the docs, the Reduction parameter takes on 3 values - SUM_OVER_BATCH_SIZE, SUM and NONE. y_true = [[0., 2.], [0., 0.]] y_pred = [[3., 1.], [2., 5.]] mae = tf.keras.losses.MeanAbsoluteError(reduction=tf.keras.losses.Reduction.SUM) mae(y_true, y_pred).numpy() > 5.5 mae = tf.keras.losses.MeanAbsoluteError() mae(y_true, y_pred).numpy() > 2.75 What I could infer about the calculation after various trials, is this:- when REDUCTION = SUM, Loss = Sum over all samples {(Sum of differences between y_pred and y_target vector of each sample / No of element in y_target of the sample )} = { (abs(3-0) + abs(1-2))/2 } + { (abs(2-0) + abs(5-0))/2 } = {4/2} + {7/2} = 5.5. when REDUCTION = SUM_OVER_BATCH_SIZE, Loss = [Sum over all samples {(Sum of differences between y_pred and y_target vector of each sample / No of element in y_target of the sample )}] / Batch_size or No of Samples = [ { (abs(3-0)} + abs(1-2))/2 } + { (abs(2-0) + abs(5-0))/2 } ]/2 = [ {4/2} + {7/2} ]/2 = [5.5]/2 = 2.75. As a result, SUM_OVER_BATCH_SIZE is nothing but SUM/batch_size. Then, why is it called SUM_OVER_BATCH_SIZE when SUM actually adds up the losses over the entire batch, while SUM_OVER_BATCH_SIZE calculates the average loss of the batch. Is my assumption regarding the workings of SUM_OVER_BATCH_SIZE and SUM at all correct? | Your assumption is correct as far as I understand. If you check the github [keras/losses_utils.py][1] lines 260-269 you will see that it does performs as expected. SUM will sum up the losses in the batch dimension, and SUM_OVER_BATCH_SIZE would divide SUM by the number of total losses (batch size). def reduce_weighted_loss(weighted_losses, reduction=ReductionV2.SUM_OVER_BATCH_SIZE): if reduction == ReductionV2.NONE: loss = weighted_losses else: loss = tf.reduce_sum(weighted_losses) if reduction == ReductionV2.SUM_OVER_BATCH_SIZE: loss = _safe_mean(loss, _num_elements(weighted_losses)) return loss You can do a easy checking with your previous example just by adding one pair of outputs with 0 loss. y_true = [[0., 2.], [0., 0.],[1.,1.]] y_pred = [[3., 1.], [2., 5.],[1.,1.]] mae = tf.keras.losses.MeanAbsoluteError(reduction=tf.keras.losses.Reduction.SUM) mae(y_true, y_pred).numpy() > 5.5 mae = tf.keras.losses.MeanAbsoluteError() mae(y_true, y_pred).numpy() > 1.8333 So, your assumption is correct. [1]: https://github.com/keras-team/keras/blob/v2.7.0/keras/utils/losses_utils.py#L25-L84 | 7 | 5 |
63,630,179 | 2020-8-28 | https://stackoverflow.com/questions/63630179/avoid-division-by-zero-in-numpy-where | I have two numpy arrays a, b of the same shape, b has a few zeros. I would like to set an output array to a / b where b is not zero, and a otherwise. The following works, but yields a warning because a / b is computed everywhere first. import numpy a = numpy.random.rand(4, 5) b = numpy.random.rand(4, 5) b[b < 0.3] = 0.0 A = numpy.where(b > 0.0, a / b, a) /tmp/l.py:7: RuntimeWarning: divide by zero encountered in true_divide A = numpy.where(b > 0.0, a / b, a) Filtering the division with a mask doesn't perserve the shape, so this doesn't work: import numpy a = numpy.random.rand(4, 5) b = numpy.random.rand(4, 5) b[b < 0.3] = 0.0 mask = b > 0.0 A = numpy.where(mask, a[mask] / b[mask], a) ValueError: operands could not be broadcast together with shapes (4,5) (14,) (4,5) Any hints on how to avoid the warning? | Simply initialize output array with the fallback values (condition-not-satisfying values) or array and then mask to select the condition-satisfying values to assign - out = a.copy() out[mask] /= b[mask] If you are looking for performance, we can use a modified b for the division - out = a / np.where(mask, b, 1) Going further, super-charge it with numexpr for this specific case of positive values in b (>=0) - import numexpr as ne out = ne.evaluate('a / (1 - mask + b)') Benchmarking Code to reproduce the plot: import perfplot import numpy import numexpr numpy.random.seed(0) def setup(n): a = numpy.random.rand(n) b = numpy.random.rand(n) b[b < 0.3] = 0.0 mask = b > 0 return a, b, mask def copy_slash(data): a, b, mask = data out = a.copy() out[mask] /= b[mask] return out def copy_divide(data): a, b, mask = data out = a.copy() return numpy.divide(a, b, out=out, where=mask) def slash_where(data): a, b, mask = data return a / numpy.where(mask, b, 1.0) def numexpr_eval(data): a, b, mask = data return numexpr.evaluate('a / (1 - mask + b)') b = perfplot.bench( setup=setup, kernels=[copy_slash, copy_divide, slash_where, numexpr_eval], n_range=[2 ** k for k in range(24)], xlabel="n" ) b.save("out.png") | 7 | 7 |
63,687,314 | 2020-9-1 | https://stackoverflow.com/questions/63687314/why-does-keras-model-fit-use-so-much-memory-despite-using-allow-growth-true | I have, thanks to this question mostly been able to solve the problem of tensorflow allocating memory which I didn't want allocated. However, I have recently found that despite my using set_session with allow_growth=True, using model.fit will still mean that all the memory is allocated and I can no longer use it for the rest of my program, even when the function is exited and the model should no longer have any allocated memory due to the fact that the model is a local variable. Here is some example code demonstrating this: from numpy import array from keras import Input, Model from keras.layers import Conv2D, Dense, Flatten from keras.optimizers import SGD # stops keras/tensorflow from allocating all the GPU's memory immediately from tensorflow.compat.v1.keras.backend import set_session from tensorflow.compat.v1 import Session, ConfigProto, GPUOptions tf_config = ConfigProto(gpu_options=GPUOptions(allow_growth=True)) session = Session(config=tf_config) set_session(session) # makes the neural network def make_net(): input = Input((2, 3, 3)) conv = Conv2D(256, (1, 1))(input) flattened_input = Flatten()(conv) output = Dense(1)(flattened_input) model = Model(inputs=input, outputs=output) sgd = SGD(0.2, 0.9) model.compile(sgd, 'mean_squared_error') model.summary() return model def make_data(input_data, target_output): input_data.append([[[0 for i in range(3)] for j in range(3)] for k in range(2)]) target_output.append(0) def main(): data_amount = 4096 input_data = [] target_output = [] model = make_model() for i in range(data_amount): make_data(input_data, target_output) model.fit(array(input_data), array(target_output), batch_size=len(input_data)) return while True: main() When I run this code with the Pycharm debugger, I find that the GPU RAM used stays at around 0.1GB until I run model.fit for the first time, at which point the memory usage shoots up to 3.2GB of my 4GB of GPU RAM. I have also noted that the memory usage doesn't increase after the first time that model.fit is run and that if I remove the convolutional layer from my network, the memory increase doesn't happen at all. Could someone please shine some light on my problem? UPDATE: Setting per_process_gpu_memory_fraction in GPUOptions to 0.1 helps limit the effect in the code included, but not in my actual program. A better solution would still be helpful. | I used to face this problem. And I found a solution from someone who I can't find anymore. His solution I paste below. In fact, I found that if you set allow_growth=True, tensorflow seems to use all your memory. So you should just set your max limit. try this: gpus = tf.config.experimental.list_physical_devices("GPU") if gpus: # Restrict TensorFlow to only use the first GPU try: for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, False) tf.config.experimental.set_virtual_device_configuration( gpu, [ tf.config.experimental.VirtualDeviceConfiguration( memory_limit=12288 # set your limit ) ], ) tf.config.experimental.set_visible_devices(gpus[0], "GPU") logical_gpus = tf.config.experimental.list_logical_devices("GPU") print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU") except RuntimeError as e: # Visible devices must be set before GPUs have been initialized print(e) | 8 | 6 |
63,676,411 | 2020-8-31 | https://stackoverflow.com/questions/63676411/pydantic-how-to-use-one-fields-value-to-set-values-for-other-fields | What I Have Dictionary: user_dict = {'user': {'field1': 'value1', 'field2': 'value2'}, 'admin':{'field1': 'value3', 'field2': 'value4'}} Pydantic Model: class User(BaseModel): account_type: Optional[str] = 'user' field1: Optional[str] = '' field1: Optional[str] = '' class Config: validate_assignment = True @validator("account_type", pre=True, always=True) def _set_account_type(cls, account_type: str): return account_type or "user" Desired Outcome I would like to lookup the values of field1 and field2 from the user_dict based upon the account_type. So I should be able to do something like this: user = User() print(user.field1) # > 'value1' print(user.field2) # > 'value2' user2 = User(field1=None, field2=None) print(user2.field1) # > 'value1' print(user2.field2) # > 'value2' user3 = User(account_type="admin") print(user3.field1) # > 'value3' print(user3.field2) # > 'value4' What I have tried class User(BaseModel): account_type: Optional[str] = 'user' field1: Optional[str] = user_dict['account_type']['field1'] field1: Optional[str] = user_dict['account_type']['field2'] class Config: validate_assignment = True @validator("account_type", pre=True, always=True) def _set_account_type(cls, account_type: str): return account_type or "user" user = User() print(user.field1) # > 'value1' user = User(field1=None) print(user.field1) # > None Using Validators for field1 and field2: class User(BaseModel): account_type: Optional[str] = 'user' field1: Optional[str] field1: Optional[str] class Config: validate_assignment = True @validator("account_type", pre=True, always=True) def _set_account_type(cls, account_type: str): return account_type or "user" @validator("field1", pre=True, always=True) def _set_plan_credits(cls, value): if value is None: value = 'value1' return user_dict['account_type']['field1'] or value @validator("field2", pre=True, always=True) def _set_rollover_credits(cls, value): if value is None: value = 'value2' return user_dict['account_type']['field2'] or value user = User() # > AttributeError: type object 'Account' has no attribute 'account_type' Any ideas on what I can do to get the desired outcome? | I solved it by using the root_validator decorator as follows: Solution: @root_validator(pre=False) def _set_fields(cls, values: dict) -> dict: """This is a validator that sets the field values based on the the user's account type. Args: values (dict): Stores the attributes of the User object. Returns: dict: The attributes of the user object with the user's fields. """ values["field1"] = user_dict[values["account_type"]]["field1"] values["field2"] = user_dict[values["account_type"]]["field2"] return values | 13 | 13 |
63,687,113 | 2020-9-1 | https://stackoverflow.com/questions/63687113/no-such-option-use-feature-while-installing-tensorflow-object-detection-api | I'm trying to install Tensorflow Object Detection API, following the steps at this link, which is the official installation's documentation for Tensorflow 2. git clone https://github.com/tensorflow/models.git > everything is ok cd models/research/ > everything is ok protoc object_detection/protos/*.proto --python_out=. > everything is ok cp object_detection/packages/tf2/setup.py . > everything is ok python -m pip install --use-feature=2020-resolver . > Usage: > /opt/anaconda3/envs/ml/bin/python -m pip install [options] <requirement specifier> [package-> index-options] ... > /opt/anaconda3/envs/ml/bin/python -m pip install [options] -r <requirements file> [package-index-options] ... > /opt/anaconda3/envs/ml/bin/python -m pip install [options] [-e] <vcs project url> ... > /opt/anaconda3/envs/ml/bin/python -m pip install [options] [-e] <local project path> ... > /opt/anaconda3/envs/ml/bin/python -m pip install [options] <archive url/path> ... > no such option: --use-feature Can someone help me understand why the installation stops as it does? I'm using macOS Mojave, Python 3.6 (on a conda virtual env), and Tensorflow 2.3.0. | I had the same problem, I upgraded pip version from 20.0.2 to 20.2.2, then it worked. An issue was opened on github on this matter, check here. Use python -m pip install --upgrade pip to upgrade pip. | 6 | 15 |
63,624,533 | 2020-8-27 | https://stackoverflow.com/questions/63624533/coinbase-apierrorid-in-python | I want to transfer money between my coinbase accounts. I'm storing all of my accounts' IDs from client.get_accounts()['data']['id'] and transferring with the code, tx = client.transfer_money('2bbf394c-193b-5b2a-9155-3b4732659ede', to='58542935-67b5-56e1-a3f9-42686e07fa40', amount='1', currency= 'BTC) But, I get this error. coinbase.wallet.error.APIError: APIError(id=): | I struggled with the same problem. It seems to be on their side and not limited to the python client. The only way I managed to transfer from wallet to wallet is by using the undocumented and unimplemented API "trades" that is used by the website. First your have to find the base_id of both your currencies, then your can do: r = client._post('v2', "trades", data={ "amount":"1", "amount_asset":"BTC", "amount_from":"input", "source_asset":"<BASE_ID_OF_SOUCE>", "target_asset":"<BASE_ID_OF_TARGET" } ) result = r.json() trade_id = result['data']['id'] client._post("v2", "trades", trade_id, "commit") It's not the cleanest code since it's accessing a protected method and I'm not entirely sure that coinbase is OK with it (There might be a reason it's not documented...) but it does the job. | 6 | 0 |
63,645,357 | 2020-8-29 | https://stackoverflow.com/questions/63645357/using-pytorch-with-celery | I'm trying to run a PyTorch model in a Django app. As it is not recommended to execute the models (or any long-running task) in the views, I decided to run it in a Celery task. My model is quite big and it takes about 12 seconds to load and about 3 seconds to infer. That's why I decided that I couldn't afford to load it at every request. So I tried to load it at settings and save it there for the app to use it. So my final scheme is: When the Django app starts, in the settings the PyTorch model is loaded and it's accessible from the app. When views.py receives a request, it delays a celery task The celery task uses the settings.model to infer the result The problem here is that the celery task throws the following error when trying to use the model [2020-08-29 09:03:04,015: ERROR/ForkPoolWorker-1] Task app.tasks.task[458934d4-ea03-4bc9-8dcd-77e4c3a9caec] raised unexpected: RuntimeError("Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method") Traceback (most recent call last): File "/home/ubuntu/anaconda3/envs/tensor/lib/python3.7/site-packages/celery/app/trace.py", line 412, in trace_task R = retval = fun(*args, **kwargs) File "/home/ubuntu/anaconda3/envs/tensor/lib/python3.7/site-packages/celery/app/trace.py", line 704, in __protected_call__ return self.run(*args, **kwargs) /*...*/ File "/home/ubuntu/anaconda3/envs/tensor/lib/python3.7/site-packages/torch/cuda/__init__.py", line 191, in _lazy_init "Cannot re-initialize CUDA in forked subprocess. " + msg) RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method Here's the code in my settings.py loading the model: if sys.argv and sys.argv[0].endswith('celery') and 'worker' in sys.argv: #In order to load only for the celery worker import torch torch.cuda.init() torch.backends.cudnn.benchmark = True load_model_file() And the task code @task def getResult(name): print("Executing on GPU:", torch.cuda.is_available()) if os.path.isfile(name): try: outpath = model_inference(name) os.remove(name) return outpath except OSError as e: print("Error", name, "doesn't exist") return "" The print in the task shows "Executing on GPU: true" I've tried setting torch.multiprocessing.set_start_method('spawn') in the settings.py before and after the torch.cuda.init() but it gives the same error. | Setting this method works as long as you're also using Process from the same library. from torch.multiprocessing import Pool, Process Celery uses "regular" multiprocessing library, thus this error. If I were you I'd try either: run it single threaded to see if that helps run it with eventlet to see if that helps read this | 8 | 10 |
63,602,222 | 2020-8-26 | https://stackoverflow.com/questions/63602222/what-loss-or-reward-is-backpropagated-in-policy-gradients-for-reinforcement-lear | I have made a small script in Python to solve various Gym environments with policy gradients. import gym, os import numpy as np #create environment env = gym.make('Cartpole-v0') env.reset() s_size = len(env.reset()) a_size = 2 #import my neural network code os.chdir(r'C:\---\---\---\Python Code') import RLPolicy policy = RLPolicy.NeuralNetwork([s_size,a_size],learning_rate=0.000001,['softmax']) #a 3layer network might be ([s_size, 5, a_size],learning_rate=1,['tanh','softmax']) #it supports the sigmoid activation function also print(policy.weights) DISCOUNT = 0.95 #parameter for discounting future rewards #first step action = policy.feedforward(env.reset) state,reward,done,info = env.step(action) for t in range(3000): done = False states = [] #lists for recording episode probs2 = [] rewards = [] while not done: #env.render() #to visualize learning probs = policy.feedforward(state)[-1] #calculate probabilities of actions action = np.random.choice(a_size,p=probs) #choose action from probs #record and update state probs2.append(probs) states.append(state) state,reward,done,info = env.step(action) rewards.append(reward) #should reward be before updating state? #calculate gradients gradients_w = [] gradients_b = [] for i in range(len((rewards))): totalReward = sum([rewards[t]*DISCOUNT**t for t in range(len(rewards[i:]))]) #discounted reward ## !! this is the line that I need help with gradient = policy.backpropagation(states[i],totalReward*(probs2[i])) #what should be backpropagated through the network ## !! ##record gradients gradients_w.append(gradient[0]) gradients_b.append(gradient[1]) #combine gradients and update the weights and biases gradients_w = np.array(gradients_w,object) gradients_b = np.array(gradients_b,object) policy.weights += policy.learning_rate * np.flip(np.sum(gradients_w,0),0) #np.flip because the gradients are calculated backwards policy.biases += policy.learning_rate * np.flip(np.sum(gradients_b,0),0) #reset and record env.reset() if t%100==0: print('t'+str(t),'r',sum(rewards)) What should be passed backwards to calculate the gradients? I am using gradient ascent but I could switch it to descent. Some people have defined the reward function as totalReward*log(probabilities). Would that make the score derivative totalReward*(1/probs) or log(probs) or something else? Do you use a cost function like cross entropy? I have tried totalReward*np.log(probs) totalReward*(1/probs) totalReward*(probs**2) totalReward*probs probs = np.zeros(a_size) probs[action] = 1 totalRewards*probs and a couple others. The last one is the only one that was able to solve any of them and it only worked on Cartpole. I have tested the various loss or score functions for thousands of episodes with gradient ascent and descent on Cartpole, Pendulum, and MountainCar. Sometimes it will improve a small amount but it will never solve it. What am I doing wrong? And here is the RLPolicy code. It is not well written or pseudo coded but I don't think it is the problem because I checked it with gradient checking several times. But it would be helpful even if I could narrow it down to a problem with the neural network or somewhere else in my code. #Neural Network import numpy as np import random, math, time, os from matplotlib import pyplot as plt def activation(x,function): if function=='sigmoid': return(1/(1+math.e**(-x))) #Sigmoid if function=='relu': x[x<0]=0 return(x) if function=='tanh': return(np.tanh(x.astype(float))) #tanh if function=='softmax': z = np.exp(np.array((x-max(x)),float)) y = np.sum(z) return(z/y) def activationDerivative(x,function): if function=='sigmoid': return(x*(1-x)) if function=='relu': x[x<0]==0 x[x>0]==1 return(x) if function=='tanh': return(1-x**2) if function=='softmax': s = x.reshape(-1,1) return(np.diagflat(s) - np.dot(s, s.T)) class NeuralNetwork(): def __init__ (self,layers,learning_rate,momentum,regularization,activations): self.learning_rate = learning_rate if (isinstance(layers[1],list)): h = layers[1][:] del layers[1] for i in h: layers.insert(-1,i) self.layers = layers self.weights = [2*np.random.rand(self.layers[i]*self.layers[i+1])-1 for i in range(len(self.layers)-1)] self.biases = [2*np.random.rand(self.layers[i+1])-1 for i in range(len(self.layers)-1)] self.weights = np.array(self.weights,object) self.biases = np.array(self.biases,object) self.activations = activations def feedforward(self, input_array): layer = input_array neuron_outputs = [layer] for i in range(len(self.layers)-1): layer = np.tile(layer,self.layers[i+1]) layer = np.reshape(layer,[self.layers[i+1],self.layers[i]]) weights = np.reshape(self.weights[i],[self.layers[i+1],self.layers[i]]) layer = weights*layer layer = np.sum(layer,1)#,self.layers[i+1]-1) layer = layer+self.biases[i] layer = activation(layer,self.activations[i]) neuron_outputs.append(np.array(layer,float)) return(neuron_outputs) def neuronErrors(self,l,neurons,layerError,n_os): if (l==len(self.layers)-2): return(layerError) totalErr = [] #total error for e in range(len(layerError)): #-layers e = e*self.layers[l+2] a_ws = self.weights[l+1][e:e+self.layers[l+1]] e = int(e/self.layers[l+2]) err = layerError[e]*a_ws #error totalErr.append(err) return(sum(totalErr)) def backpropagation(self,state,loss): weights_gradient = [np.zeros(self.layers[i]*self.layers[i+1]) for i in range(len(self.layers)-1)] biases_gradient = [np.zeros(self.layers[i+1]) for i in range(len(self.layers)-1)] neuron_outputs = self.feedforward(state) grad = self.individualBackpropagation(loss, neuron_outputs) return(grad) def individualBackpropagation(self, difference, neuron_outputs): #number of output lr = self.learning_rate n_os = neuron_outputs[:] w_o = self.weights[:] b_o = self.biases[:] w_n = self.weights[:] b_n = self.biases[:] gradient_w = [] gradient_b = [] error = difference[:] #error for neurons for l in range(len(self.layers)-2,-1,-1): p_n = np.tile(n_os[l],self.layers[l+1]) #previous neuron neurons = np.arange(self.layers[l+1]) error = (self.neuronErrors(l,neurons,error,n_os)) if not self.activations[l]=='softmax': error = error*activationDerivative(neuron_outputs[l+1],self.activations[l]) else: error = error @ activationDerivative(neuron_outputs[l+1],self.activations[l]) #because softmax derivative returns different dimensions w_grad = np.repeat(error,self.layers[l]) #weights gradient b_grad = np.ravel(error) #biases gradient w_grad = w_grad*p_n b_grad = b_grad gradient_w.append(w_grad) gradient_b.append(b_grad) return(gradient_w,gradient_b) Thanks for any answers, this is my first question here. | mprouveur's answer was half correct but I felt that I needed to explain the right thing to backpropagate. The answer to my question on ai.stackexchange.com was how I came to understand this. The correct error to backpropagate is the log probability of taking the action multiplied by the goal reward. This can also be calculated as the cross entropy loss between the outputted probabilities and an array of zeros with the action that was taken being one 1. Because of the derivative of cross entropy loss, this will have the effect of pushing only the probability of the action that was taken closer to one. Then, the multiplication of the total reward makes better actions get pushed more to a higher probability. So, with the label being a one-hot encoded vector, the correct equation is label/probs * totalReward because that is the derivative of cross entropy loss and the derivative of the log of probs. I got this working in other code, but even with this equation I think something else in my code is wrong. It probably has something to do with how I made the softmax derivative too complicated instead of calculating the usual way, by combing the cross entropy derivative and softmax derivative. I will update this answer soon with correct code and more information. | 11 | 0 |
63,620,981 | 2020-8-27 | https://stackoverflow.com/questions/63620981/dropbox-cant-generate-access-token-missing-scope | I just got started with using the DropBox API for Python - i want to use it to store files that my Discord Bot previously downloaded, but even following the official tutorial 1:1 i cant get it to just read and write files. I registered the app and generated an access token, and it always tells me dropbox.exceptions.AuthError: AuthError('09d729accff6a6d8fa601154df010b0b', AuthError('missing_scope', TokenScopeError(required_scope='files.metadata.read'))) when i try to read dbx.files_list_folder('').entries for example. I checked the permissions and saw that apparently, the access token has no permissions yet, so i checked the right permissions. However, i cannot generate a new access token with the new permissions now, because it says `You must be a team administrator to perform this operation.Β΄ I think i am missunderstanding something here, but i dont know why this basic example that i got from the offical site wont work. | Regarding the 'missing_scope' error: You're correct, the app and access token need the particular scope required by the route in order to access the route. Note that just enabling a particular scope for an app, via the App Console, does not retroactively add authorization for that scope to existing access tokens though. So, you'd need to process the authorization flow (either the OAuth flow or using the "Generate" button) again to authorize an access token with any newly enabled scopes, as you attempted. Regarding the "You must be a team administrator to perform this operation" error: That indicates that you selected one or more "team" scopes, which can only be authorized by a team admin, but you're not an admin on a Business team. In that case, you'd need to remove any team scopes to connect the app. Also, note that the 'files.permanent_delete' scope automatically requires the 'team_data.member' scope, so you can't use 'files.permanent_delete' from a non-team account, and so enabling the the 'files.permanent_delete' scope will also cause that. (Edit: Fixed: There's also a current issue that can prevent you from deselecting the 'team_data.member' scope if your app uses the "app folder" access type. We're working on fixing that, but you may need to re-create the app if you're in that state and want to use it before the fix is out.) | 9 | 30 |
63,650,010 | 2020-8-29 | https://stackoverflow.com/questions/63650010/could-not-find-a-version-that-satisfies-the-requirement-pyyaml-5-3-but-pyyaml | I am using SetupTools to build a package of my own. In INSTALL_REQUIRES in setup.py I have the following dependencies: ... INSTALL_REQUIRES = [ 'ray>=0.8.7', 'pyyaml>=5.3', ] setup(name=PACKAGE_NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type=LONG_DESC_TYPE, author=AUTHOR, license=LICENSE, author_email=AUTHOR_EMAIL, url=URL, install_requires=INSTALL_REQUIRES, packages=find_packages() ) When I run pip3 install -i https://test.pypi.org/simple/ r3po==0.0.6, I get the following error: ERROR: Could not find a version that satisfies the requirement pyyaml>=5.3 (from r3po==0.0.6) (from versions: 3.11) ERROR: No matching distribution found for pyyaml>=5.3 (from r3po==0.0.6) However, pip3 search pyyaml shows me that PyYAML is definitely there: PyYAML (5.3.1) - YAML parser and emitter for Python and pip3 install pyyaml (in a .venv that has pyyaml installed) gives Requirement already satisfied: pyyaml in /home/lieu/dev/inzura-clustering-project/.venv/lib/python3.8/site-packages (5.3.1) And before you ask --- yes, I've tried all combinations of PyYAML, pyyaml, 5.3.1, 5.3, and so on, but nothing has worked. I even tried to remove the version requirement (so INSTALL_REQUIRES=['ray>=0.87','pyyaml']) but this leads to another error: ERROR: Command errored out with exit status 1: command: /home/lieu/dev/r3po/sample/.venv/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-w32z04mo/pyyaml/setup.py'"'"'; __file__='"'"'/tmp/pip-install-w32z04mo/pyyaml/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-w32z04mo/pyyaml/pip-egg-info cwd: /tmp/pip-install-w32z04mo/pyyaml/ Complete output (7 lines): running egg_info creating /tmp/pip-install-w32z04mo/pyyaml/pip-egg-info/PyYAML.egg-info writing /tmp/pip-install-w32z04mo/pyyaml/pip-egg-info/PyYAML.egg-info/PKG-INFO writing dependency_links to /tmp/pip-install-w32z04mo/pyyaml/pip-egg-info/PyYAML.egg-info/dependency_links.txt writing top-level names to /tmp/pip-install-w32z04mo/pyyaml/pip-egg-info/PyYAML.egg-info/top_level.txt writing manifest file '/tmp/pip-install-w32z04mo/pyyaml/pip-egg-info/PyYAML.egg-info/SOURCES.txt' error: package directory 'lib3/yaml' does not exist | Anthony Sottile's suggestion to use --extra-index-url worked for me. | 6 | 6 |
63,686,877 | 2020-9-1 | https://stackoverflow.com/questions/63686877/how-to-install-python-on-windows-without-an-msi-installer | Take python 3.6.x for example. The last windows installer for python 3.6.x is 3.6.8: no more installers for 3.6x version that comes later (see https://www.python.org/downloads/windows/) 3.6.8 happens to be the last maintenance release of python3.6, I don't know if it is somehow related to not propose a package installer for windows but only sources. Practical problem here: How should I proceed to install 3.6.12 on Windows? Please donβt simply advice Β« Install 3.7 or 3.8, it is more recent Β». I know that 3.6 is not the latest, but sometimes you have to stick with a particular version for support or compatibility. Since I have to use 3.6.x, I am looking for the latest version available in this branch (currently 3.6.12) to still benefit from security patches. This gives two path: install 3.6.8 with MSI installer then upgrade to 3.6.12 from source, install 3.6.12 from source. What are the steps involved for option 1 or 2? | It is possible to create your own MSI installer from the source distributions at https://www.python.org/downloads/source/. This is what I did to install Python 3.6.12 on my Windows machine. In each source distribution, the files at PCBuild/readme.txt and Tools/msi/README.txt provide guidance for how to build your own Python installer. If you have not built Python from source before on Windows, this may be a challenge to set up. If you do not want to build the installer yourself, you can download unofficial installers from https://github.com/adang1345/PythonWindows. These are the installers that I built recently as part of a personal project. | 8 | 19 |
63,646,854 | 2020-8-29 | https://stackoverflow.com/questions/63646854/how-to-get-list-of-channels-that-i-joined-in-telethon | I want to make a script that shows the channels that i joined and then leave all of it with this example: from telethon.tl.functions.channels import LeaveChannelRequest await client(LeaveChannelRequest(input_channel)) | In order to leave all the channels you're in, you have to fetch all the channels from the dialogs list and then just delete them. Here is a snippet. async for dialog in client.iter_dialogs(): if not dialog.is_group and dialog.is_channel: await dialog.delete() | 11 | 17 |
63,660,037 | 2020-8-30 | https://stackoverflow.com/questions/63660037/django-contrib-auth-login-function-not-returning-any-user-as-logged-in | I have created a basic app using Django's built in authentication system. I successfully created a User object in the shell using >>python manage.py createsuperuser. I then created a basic view, 'UserLogin' along with corresponding serializers/urls, to log an existing user in using the django.contrib.auth authenticate(), and login() functions. Upon testing with the credentials of my created user, the login function seemed to have worked successfully. To test this, I created another view function, 'CurrentUser' which returns the username of the currently logged in user. However, this view returns the user as empty. Why would the 'CurrentUser' view be returning no user as logged in? I have attached my code (minus imports) below. views.py: class UserLogin(APIView): def post(self, request, format = None): serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(): user = authenticate(username=serializer.validated_data["username"], password=serializer.validated_data["password"]) if user is not None: login(request, user) return Response(UserSerializer(user).data, status=status.HTTP_201_CREATED) return Response("Invalid username/password", status=status.HTTP_401_UNAUTHORIZED) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) class CurrentUser(APIView): def get(self, request, format = None): return Response(self.request.user.username) serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username'] class UserLoginSerializer(serializers.Serializer): username = serializers.CharField(max_length=300, required=True) password = serializers.CharField(required=True, write_only=True) urls.py: urlpatterns = [ path('login/', views.UserLogin.as_view()), path('current/', views.CurrentUser.as_view()) ] Any guidance would be much appreciated. Thanks | You have to set the default auth class as session authenticate class in DRF settings. Read more about it here [1]. Session auth uses session id to identify the user. So you have to send the cookie based session id in the request. Read about session auth here [2]. for example: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', # <-- set this class ] } Use this code: def post(self, request, format = None): serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(): user = authenticate(username=serializer.validated_data["username"], password=serializer.validated_data["password"]) if user: return Response(UserSerializer(user).data, status=status.HTTP_201_CREATED) return Response("Invalid username/password", status=status.HTTP_401_UNAUTHORIZED) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) But my recommendation is to use Token auth [3]. To use token auth 2 things will change: The default auth class in DRF settings When sending a request to any DRF API view you to send the Auth header as Token <token-value> Your post method and API views code will remain same. [1] https://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme [2] https://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication [3] https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication | 6 | 5 |
63,652,016 | 2020-8-29 | https://stackoverflow.com/questions/63652016/python-serverless-function-vercel-next-js | I found out that I could use Python to create a serverless function inside a Next.js project. Once deployed to Vercel, it will get converted into a serverless function. I went through the docs and found a simple example that outputs the date: from http.server import BaseHTTPRequestHandler from datetime import datetime class handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')).encode()) return They offer a live working example here. Apparently all that is needed is to place the file date.py inside the api folder of a bootstrapped Next.js project and you're off to the races. When deployed, Vercel will detect the Python file and serve it as a serverless function. The deploy succeeded and I placed the file inside the pages/api folder as required. However, the function is never picked up (image below): Older versions apparently required the configuration of serverless functions by adding a vercel.json file. But this doesn't seem necessary now. What am I missing? | After going over the FAQs. I found an entry named Unmatched Function Pattern, it states: the functions property uses a glob pattern for each key. This pattern must match Serverless Function source files within the api directory. It also mentions: if you'd like to use a Serverless Function that isn't written with Node.js in combination with Next.js, you can place it in the api directory (provided by the platform), since pages/api (provided by Next.js) only supports JavaScript. I think that this needs to be clarified a bit. There is indeed an default api folder when you bootstrap a Next.js project with create-next-app, but it's created inside the pages directory. If you follow the example they give, you might just go ahead and create a serverless function in a supported language (other than JavaScript) inside the pages/api directory and wonder why Vercel doesn't pick it up when you deploy. In short, if you're using another language to write a serverless function inside a Next.js project. Be sure to place it inside an api folder that sits in the root directory of the project (if there's none, create one). Thanks to @evgenifotia for the suggestion, it pointed me in the right direction and helped me solve this issue. Note: You can only have a single api directory that houses serverless functions. Either you have a pages/api directory or a api directory in the root folder, having both in a single project is not supported. | 10 | 15 |
63,589,249 | 2020-8-26 | https://stackoverflow.com/questions/63589249/plotly-dash-display-real-time-data-in-smooth-animation | We are trying to produce a real-time dashboard in plotly-dash that displays live data as it is produced. We are generally following the guidance here (https://dash.plotly.com/live-updates). We have a callback that gathers a chunk of new data points from the source approximately every second and then appends the data to the graph. When we do this the update to the graph is choppy because we are generating a new graph object on the callback every second. We want the graph to flow smoothly, even if that means we're a second or two behind the live data. We are looking at animations (https://plotly.com/python/animations/) but it's not clear how we might apply an animation to a live stream of data being appended to a graph. | Updating traces of a Graph component without generating a new graph object can be achieved via the extendData property. Here is a small example that appends data each second, import dash import dash_html_components as html import dash_core_components as dcc import numpy as np from dash.dependencies import Input, Output # Example data (a circle). resolution = 20 t = np.linspace(0, np.pi * 2, resolution) x, y = np.cos(t), np.sin(t) # Example app. figure = dict(data=[{'x': [], 'y': []}], layout=dict(xaxis=dict(range=[-1, 1]), yaxis=dict(range=[-1, 1]))) app = dash.Dash(__name__, update_title=None) # remove "Updating..." from title app.layout = html.Div([dcc.Graph(id='graph', figure=figure), dcc.Interval(id="interval")]) @app.callback(Output('graph', 'extendData'), [Input('interval', 'n_intervals')]) def update_data(n_intervals): index = n_intervals % resolution # tuple is (dict of new data, target trace index, number of points to keep) return dict(x=[[x[index]]], y=[[y[index]]]), [0], 10 if __name__ == '__main__': app.run_server() Depending of the network connection between client and server (at each update, a request is exchanged between client and server), this approach works up to a refresh rate of around 1s. If you need a higher refresh rate, i would suggest doing the graph update using a client side callback. Adopting the previous example, the code would be along the lines of import dash import dash_html_components as html import dash_core_components as dcc import numpy as np from dash.dependencies import Input, Output, State # Example data (a circle). resolution = 1000 t = np.linspace(0, np.pi * 2, resolution) x, y = np.cos(t), np.sin(t) # Example app. figure = dict(data=[{'x': [], 'y': []}], layout=dict(xaxis=dict(range=[-1, 1]), yaxis=dict(range=[-1, 1]))) app = dash.Dash(__name__, update_title=None) # remove "Updating..." from title app.layout = html.Div([ dcc.Graph(id='graph', figure=dict(figure)), dcc.Interval(id="interval", interval=25), dcc.Store(id='offset', data=0), dcc.Store(id='store', data=dict(x=x, y=y, resolution=resolution)), ]) app.clientside_callback( """ function (n_intervals, data, offset) { offset = offset % data.x.length; const end = Math.min((offset + 10), data.x.length); return [[{x: [data.x.slice(offset, end)], y: [data.y.slice(offset, end)]}, [0], 500], end] } """, [Output('graph', 'extendData'), Output('offset', 'data')], [Input('interval', 'n_intervals')], [State('store', 'data'), State('offset', 'data')] ) if __name__ == '__main__': app.run_server() Client side updates should be fast enough to achieve a smooth update. The gif below shows the above example running with 25 ms refresh rate, Keep in mind that a client side update is only possible if the data is already present client side, i.e. another mechanism is needed to fetch the data from the server. A possible data flow could be Use a slow Interval component (e.g. 2 s) to trigger a (normal) callback that fetches a chunk of data from the source and places it in a Store component Use a fast Interval component (e.g. 25 ms) to trigger a client side callback that streams data from the Store component to the Graph component | 45 | 68 |
63,679,315 | 2020-8-31 | https://stackoverflow.com/questions/63679315/how-to-use-cython-with-poetry | I have a file in my project which I would like to compile for performance reasons: mylibrary/myfile.py How to achieve this with Poetry? | There is an undocumented feature in Poetry. Add this to your pyproject.toml: [tool.poetry] ... build = 'build.py' [build-system] requires = ["poetry>=0.12", "cython"] build-backend = "poetry.masonry.api" What this does is runs the build.py:build() function inside the implicitly generated setup.py. This is where we build. So, create a build.py that provides the build() function: import os # See if Cython is installed try: from Cython.Build import cythonize # Do nothing if Cython is not available except ImportError: # Got to provide this function. Otherwise, poetry will fail def build(setup_kwargs): pass # Cython is installed. Compile else: from setuptools import Extension from setuptools.dist import Distribution from distutils.command.build_ext import build_ext # This function will be executed in setup.py: def build(setup_kwargs): # The file you want to compile extensions = [ "mylibrary/myfile.py" ] # gcc arguments hack: enable optimizations os.environ['CFLAGS'] = '-O3' # Build setup_kwargs.update({ 'ext_modules': cythonize( extensions, language_level=3, compiler_directives={'linetrace': True}, ), 'cmdclass': {'build_ext': build_ext} }) Now, when you do poetry build, nothing happens. But if you install this package elsewhere, it gets compiled. You can also build it manually with: $ cythonize -X language_level=3 -a -i mylibrary/myfile.py Finally, it seems that you can't publish binary packages to PyPi. The solution is to limit your build to "sdist": $ poetry build -f sdist $ poetry publish | 19 | 26 |
63,690,068 | 2020-9-1 | https://stackoverflow.com/questions/63690068/how-to-find-cosine-similarity-of-one-vector-vs-matrix | I have a TF-IDF matrix of shape (149,1001). What is want is to compute the cosine similarity of last columns, with all columns Here is what I did from numpy import dot from numpy.linalg import norm for i in range(mat.shape[1]-1): cos_sim = dot(mat[:,i], mat[:,-1])/(norm(mat[:,i])*norm(mat[:,-1])) cos_sim But this loop is making it slow. So, is there any efficient way? I want to do with numpy only | Leverage 2D vectorized matrix-multiplication Here's one with NumPy using matrix-multiplication on 2D data - p1 = mat[:,-1].dot(mat[:,:-1]) p2 = norm(mat[:,:-1],axis=0)*norm(mat[:,-1]) out1 = p1/p2 Explanation : p1 is the vectorized equivalent of looping of dot(mat[:,i], mat[:,-1]). p2 is of (norm(mat[:,i])*norm(mat[:,-1])). Sample run for verification - In [57]: np.random.seed(0) ...: mat = np.random.rand(149,1001) In [58]: out = np.empty(mat.shape[1]-1) ...: for i in range(mat.shape[1]-1): ...: out[i] = dot(mat[:,i], mat[:,-1])/(norm(mat[:,i])*norm(mat[:,-1])) In [59]: p1 = mat[:,-1].dot(mat[:,:-1]) ...: p2 = norm(mat[:,:-1],axis=0)*norm(mat[:,-1]) ...: out1 = p1/p2 In [60]: np.allclose(out, out1) Out[60]: True Timings - In [61]: %%timeit ...: out = np.empty(mat.shape[1]-1) ...: for i in range(mat.shape[1]-1): ...: out[i] = dot(mat[:,i], mat[:,-1])/(norm(mat[:,i])*norm(mat[:,-1])) 18.5 ms Β± 977 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each) In [62]: %%timeit ...: p1 = mat[:,-1].dot(mat[:,:-1]) ...: p2 = norm(mat[:,:-1],axis=0)*norm(mat[:,-1]) ...: out1 = p1/p2 939 Β΅s Β± 29.2 Β΅s per loop (mean Β± std. dev. of 7 runs, 1000 loops each) # @yatu's soln In [89]: a = mat In [90]: %timeit cosine_similarity(a[None,:,-1] , a.T[:-1]) 2.47 ms Β± 461 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each) Further optimize on norm with einsum Alternatively, we could compute p2 with np.einsum. So, norm(mat[:,:-1],axis=0) could be replaced by : np.sqrt(np.einsum('ij,ij->j',mat[:,:-1],mat[:,:-1])) Hence, giving us a modified p2 : p2 = np.sqrt(np.einsum('ij,ij->j',mat[:,:-1],mat[:,:-1]))*norm(mat[:,-1]) Timings on same setup as earlier - In [82]: %%timeit ...: p1 = mat[:,-1].dot(mat[:,:-1]) ...: p2 = np.sqrt(np.einsum('ij,ij->j',mat[:,:-1],mat[:,:-1]))*norm(mat[:,-1]) ...: out1 = p1/p2 607 Β΅s Β± 132 Β΅s per loop (mean Β± std. dev. of 7 runs, 1000 loops each) 30x+ speedup over loopy one! | 6 | 6 |
63,672,218 | 2020-8-31 | https://stackoverflow.com/questions/63672218/efficiently-finding-consecutive-streaks-in-a-pandas-dataframe-column | I have a DataFrame similar to the below:, and I want to add a Streak column to it (see example below): Date Home_Team Away_Team Winner Streak 2005-08-06 A G A 0 2005-08-06 B H H 0 2005-08-06 C I C 0 2005-08-06 D J J 0 2005-08-06 E K K 0 2005-08-06 F L F 0 2005-08-13 A B A 1 2005-08-13 C D D 1 2005-08-13 E F F 0 2005-08-13 G H H 0 2005-08-13 I J J 0 2005-08-13 K L K 1 2005-08-20 B C B 0 2005-08-20 A D A 2 2005-08-20 G K K 0 2005-08-20 I E E 0 2005-08-20 F H F 2 2005-08-20 J L J 2 2005-08-27 A H A 3 2005-08-27 B F B 1 2005-08-27 J C C 3 2005-08-27 D E D 0 2005-08-27 I K K 0 2005-08-27 L G G 0 2005-09-05 B A A 2 2005-09-05 D C D 1 2005-09-05 F E F 0 2005-09-05 H G H 0 2005-09-05 J I I 0 2005-09-05 K L K 4 The DataFrame is approximately 200k rows going from 2005 to 2020. Now, what I am trying to do is find the number of consecutive games the Home Team has won PRIOR to the date in in the Date column in the DataFrame. I have a solution, but it is too slow, see below: df["Streak"] = 0 def home_streak(x): # x is a row of the DataFrame """Keep track of a team's winstreak""" home_team = x["Home_Team"] date = x["Date"] # all previous matches for the home team home_df = df[(df["Home_Team"] == home_team) | (df["Away_Team"] == home_team)] home_df = home_df[home_df["Date"] < date].sort_values(by="Date", ascending=False).reset_index() if len(home_df.index) == 0: # no previous matches for that team, so start streak at 0 return 0 elif home_df.iloc[0]["Winner"] != home_team: # lost the last match return 0 else: # they won the last game winners = home_df["Winner"] streak = 0 for i in winners.index: if home_df.iloc[i]["Winner"] == home_team: streak += 1 else: # they lost, return the streak return streak df["Streak"] = df.apply(lambda x: home_streak(x), axis = 1) How can I speed this up? | I will present a numpy-based solution here. Firstly because I am not very familiar with pandas and don't feel like doing the research, and secondly because a numpy solution should work just fine regardless. Let's take a look at what happens to one given team first. Your goal is to find the number of consecutive wins for a team based on the sequence of games it participated in. I will drop the date column and turn your data into a numpy array for starters: x = np.array([ ['A', 'G', 'A'], ['B', 'H', 'H'], ['C', 'I', 'C'], ['D', 'J', 'J'], ['E', 'K', 'K'], ['F', 'L', 'F'], ['A', 'B', 'A'], ['C', 'D', 'D'], ['E', 'F', 'F'], ['G', 'H', 'H'], ['I', 'J', 'J'], ['K', 'L', 'K'], ['B', 'C', 'B'], ['A', 'D', 'A'], ['G', 'K', 'K'], ['I', 'E', 'E'], ['F', 'H', 'F'], ['J', 'L', 'J']]) You don't need the date because all you care about is who played, even if they did it multiple times in one day. So let's take a look at just team A: A_played = np.flatnonzero((x[:, :2] == 'A').any(axis=1)) A_won = x[A_played, -1] == 'A' A_played is an index array with the same number of elements as there are rows in x. A_won is a mask that has as many elements as np.count_nonzero(A_played); i.e., the number of games A participated in. Finding the sizes of the streaks is a fairly well hashed out problem: streaks = np.diff(np.flatnonzero(np.diff(np.r_[False, A_won, False])))[::2] You compute the differences between each pair of indices where the value of the mask switches. The extra padding with False ensures that you know which way the mask is switching. What you are looking for is based on this computation but requires a bit more detail, since you want the cumulative sum, but reset after each run. You can do that by setting the value of the data to the negated run length immediately after the run: wins = np.r_[0, A_won, 0] # Notice the int dtype here switch_indices = np.flatnonzero(np.diff(wins)) + 1 streaks = np.diff(switch_indices)[::2] wins[switch_indices[1::2]] = -streaks Now you have a trimmable array whose cumulative sum can be assigned directly to the output columns: streak_counts = np.cumsum(wins[:-2]) output = np.zeros((x.shape[0], 2), dtype=int) # Home streak home_mask = x[A_played, 0] == 'A' output[A_played[home_mask], 0] = streak_counts[home_mask] # Away streak away_mask = ~home_mask output[A_played[away_mask], 1] = streak_counts[away_mask] Now you can loop over all teams (which should be a fairly small number compared to the total number of games): def process_team(data, team, output): played = np.flatnonzero((data[:, :2] == team).any(axis=1)) won = data[played, -1] == team wins = np.r_[0, won, 0] switch_indices = np.flatnonzero(np.diff(wins)) + 1 streaks = np.diff(switch_indices)[::2] wins[switch_indices[1::2]] = -streaks streak_counts = np.cumsum(wins[:-2]) home_mask = data[played, 0] == team away_mask = ~home_mask output[played[home_mask], 0] = streak_counts[home_mask] output[played[away_mask], 1] = streak_counts[away_mask] output = np.empty((x.shape[0], 2), dtype=int) # Assume every team has been home team at least once. # If not, x[:, :2].ravel() copies the data and np.unique(x[:, :2]) does too for team in set(x[:, 0]): process_team(x, team, output) | 9 | 4 |
63,687,789 | 2020-9-1 | https://stackoverflow.com/questions/63687789/how-do-i-create-a-pie-chart-using-categorical-data-in-matplotlib | I have data as follows: ID Gender Country ... 1 Male UK 2 Female US 3 Male NZ 4 Female UK ... There are only 2 options for gender and 3 for country. I would like to create a seperate pie chart for both "Gender" and "Country" to show how many times each option shows up in the data but I'm quite confused about how to do so. The data is stored in a pandas dataframe. Any and all help is much appreciated! | Here is an approach using pandas: import pandas as pd import numpy as np from matplotlib import pyplot as plt def label_function(val): return f'{val / 100 * len(df):.0f}\n{val:.0f}%' N = 50 df = pd.DataFrame({'country': np.random.choice(['UK', 'US', 'NZ'], N), 'gender': np.random.choice(['Male', 'Female'], N)}) fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5)) df.groupby('country').size().plot(kind='pie', autopct=label_function, textprops={'fontsize': 20}, colors=['tomato', 'gold', 'skyblue'], ax=ax1) df.groupby('gender').size().plot(kind='pie', autopct=label_function, textprops={'fontsize': 20}, colors=['violet', 'lime'], ax=ax2) ax1.set_ylabel('Per country', size=22) ax2.set_ylabel('Per gender', size=22)plt.tight_layout() plt.show() PS: To just show the percentage, use autopct='%1.0f%%'. | 9 | 13 |
63,687,319 | 2020-9-1 | https://stackoverflow.com/questions/63687319/how-to-convert-a-sklearn-pipeline-into-a-pyspark-pipeline | We have a machine learning classifier model that we have trained with a pandas dataframe and a standard sklearn pipeline (StandardScaler, RandomForestClassifier, GridSearchCV etc). We are working on Databricks and would like to scale up this pipeline to a large dataset using the parallel computation spark offers. What is the quickest way to convert our sklearn pipeline into something that computes in parallel? (We can easily switch between pandas and spark DFs as required.) For context, our options seem to be: Rewrite the pipeline using MLLib (time-consuming) Use a sklearn-spark bridging library On option 2, Spark-Sklearn seems to be deprecated, but Databricks instead recommends that we use joblibspark. However, this raises an exception on Databricks: from sklearn import svm, datasets from sklearn.model_selection import GridSearchCV from joblibspark import register_spark from sklearn.utils import parallel_backend register_spark() # register spark backend iris = datasets.load_iris() parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]} svr = svm.SVC(gamma='auto') clf = GridSearchCV(svr, parameters, cv=5) with parallel_backend('spark', n_jobs=3): clf.fit(iris.data, iris.target) raises py4j.security.Py4JSecurityException: Method public int org.apache.spark.SparkContext.maxNumConcurrentTasks() is not whitelisted on class class org.apache.spark.SparkContext | According to the Databricks instructions (here and here), the necessary requirements are: Python 3.6+ pyspark>=2.4 scikit-learn>=0.21 joblib>=0.14 I cannot reproduce your issue in a community Databricks cluster running Python 3.7.5, Spark 3.0.0, scikit-learn 0.22.1, and joblib 0.14.1: import sys import sklearn import joblib spark.version # '3.0.0' sys.version # '3.7.5 (default, Nov 7 2019, 10:50:52) \n[GCC 8.3.0]' sklearn.__version__ # '0.22.1' joblib.__version__ # '0.14.1' With the above settings, your code snippet runs smoothly, and produces indeed a classifier clf as: GridSearchCV(cv=5, error_score=nan, estimator=SVC(C=1.0, break_ties=False, cache_size=200, class_weight=None, coef0=0.0, decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf', max_iter=-1, probability=False, random_state=None, shrinking=True, tol=0.001, verbose=False), iid='deprecated', n_jobs=None, param_grid={'C': [1, 10], 'kernel': ('linear', 'rbf')}, pre_dispatch='2*n_jobs', refit=True, return_train_score=False, scoring=None, verbose=0) as does the alternative example from here: from sklearn.utils import parallel_backend from sklearn.model_selection import cross_val_score from sklearn import datasets from sklearn import svm from joblibspark import register_spark register_spark() # register spark backend iris = datasets.load_iris() clf = svm.SVC(kernel='linear', C=1) with parallel_backend('spark', n_jobs=3): scores = cross_val_score(clf, iris.data, iris.target, cv=5) print(scores) giving [0.96666667 1. 0.96666667 0.96666667 1. ] | 8 | 5 |
63,673,724 | 2020-8-31 | https://stackoverflow.com/questions/63673724/python-subtest-parameters | When using python's unittest subtest, I am confused regarding how parameters are named and scoped within the sub-test. The canonical example given in the link above seems to imply that the parameters used within the with self.subtest() clause can be passed as keyword arguments to subTest(). For reference, the example shown is this: class NumbersTest(unittest.TestCase): def test_even(self): """ Test that numbers between 0 and 5 are all even. """ for i in range(0, 6): with self.subTest(i=i): self.assertEqual(i % 2, 0) It is using an ambiguous convention of naming the inner-scoped variable the same as the parameter (i=i). I took this to mean that keyword argument name is taken as the inner scoped variable name. However, when I tried to create my own test, I found that both PyCharm and the python interpreter complained of unresolved references if the keyword argument was not named precisely the same as the outer-scoped variable used as the parameter input. i.e.: class NumbersTest(unittest.TestCase): def test_even(self): """ Test that numbers between 0 and 5 are all even. """ for i in range(0, 6): with self.subTest(num=i): # <-- Renamed keyword argument parameter self.assertEqual(num % 2, 0) # < -- Results in unresolved reference error "num" How does one pass parameters into the subtest? How are they named and referenced within the subtest code block? | It seems to me that it would be nice if this was expounded on a little bit more in the docs, but the API for subTest(msg=None, **params) states: ...msg and params are optional, arbitrary values which are displayed whenever a subtest fails, allowing you to identify them clearly. So it seems that the keyword arguments passed in **params are used only for test identification when printing test status to the console. They don't get passed in as parameters to the code block in any fashion. | 7 | 11 |
63,668,501 | 2020-8-31 | https://stackoverflow.com/questions/63668501/windows-notification-with-button-using-python | I need to make a program that alerts me with a windows notification, and I found out that this can be simply done with the following code. I don't care what library I use from win10toast import ToastNotifier toast = ToastNotifier() toast.show_toast("alert","text") This code gives that following alert However, I want there to be a button on the notification so I can click it and it will lead me to a url. Like this example. Is this possible? I just found this website about toast contents can anyone help me use this with python? | This type of behavior is not supported in the currently released version of Windows-10-Toast-Notifications. However, a contributor created a pull request that adds functionality for a callback_on_click parameter that will call a function when the notification is clicked. This has yet to be merged into the master branch, and given how long it's been since the library has been updated, I wouldn't count on it happening anytime soon. However, you can still install this modified version of the library to make use of this feature: First, you'll need to uninstall the current version of win10toast from your environment (e.g., pip uninstall win10toast). Next, you'll need to install the modified version (e.g., pip install git+https://github.com/Charnelx/Windows-10-Toast-Notifications.git#egg=win10toast). Then, you can create a toast like this: toast.show_toast(title="Notification", msg="Hello, there!", callback_on_click=your_callback_function) A complete working example: from win10toast import Toast toast = ToastNotifier() toast.show_toast(title="Notification", msg="Hello, there!", callback_on_click=lambda: print("Clicked!")) When you click on the notification, you should see "Clicked!" appear in the Python console. Important: This will only work if you're using the modified version of the library I mentioned above. Otherwise you will get the error: TypeError: show_toast() got an unexpected keyword argument 'callback_on_click'. | 7 | 10 |
63,663,362 | 2020-8-31 | https://stackoverflow.com/questions/63663362/django-python3-on-install-i-get-parent-module-setuptools-not-loaded | I see lots of errors and suggestions about Parent module '' not loaded, ... I don't see any about specifically "out of the box" django 3.5. $ mkvirtualenv foobar -p /usr/bin/python3 Already using interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in /home/isaac/.virtualenvs/foobar/bin/python3 Also creating executable in /home/isaac/.virtualenvs/foobar/bin/python Installing setuptools, pkg_resources, pip, wheel...done. [foobar] $ pip install django Collecting django Using cached Django-2.2.15-py3-none-any.whl (7.5 MB) Collecting pytz Using cached pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Installing collected packages: pytz, sqlparse, django Successfully installed django-2.2.15 pytz-2020.1 sqlparse-0.3.1 [foobar] $ python Python 3.5.3 (default, Jul 9 2020, 13:00:10) [GCC 6.3.0 20170516] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/django/utils/version.py", line 6, in <module> from distutils.version import LooseVersion File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 666, in _load_unlocked File "<frozen importlib._bootstrap>", line 577, in module_from_spec File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/_distutils_hack/__init__.py", line 82, in create_module return importlib.import_module('._distutils', 'setuptools') File "/home/isaac/.virtualenvs/foobar/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 981, in _gcd_import File "<frozen importlib._bootstrap>", line 931, in _sanity_check SystemError: Parent module 'setuptools' not loaded, cannot perform relative import As you can see, I installed django using python3.5. It seems to work fine with python2.7... Is anyone else aware of a way around this bug, or something silly I did in my environment? I am using debian stretch instead of buster, but I'm not sure if I'm ready to upgrade yet. | Something happened in version 50 of setuptools. We could "solve" this problem by downgrading setuptools to 49.3.0 (and maybe pip to 20.2.1) pip install setuptools==49.3.0 and pip install pip==20.2.1 Be aware though that this should only be a temporary solution! | 15 | 18 |
63,668,103 | 2020-8-31 | https://stackoverflow.com/questions/63668103/how-can-i-get-or-print-current-datetime-of-gmt-time-zone-in-python | Here I print UTC time zone's current datetime. I want current GMT time zone's datetime by this method. How can I? import datetime dt_utcnow = datetime.datetime.utcnow() print(dt_utcnow) Output 2020-08-31 09:06:26.661323 | You can use the gmtime() of time module to achieve this: from datetime import datetime from time import gmtime, strftime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time =", current_time) print("Your Time Zone is GMT", strftime("%z", gmtime())) | 6 | 8 |
63,651,619 | 2020-8-29 | https://stackoverflow.com/questions/63651619/why-is-fast-orb-bad-at-finding-keypoints-near-the-edge-of-an-image | ORB doesn't find keypoints near the edge of an image and I don't understand why. It seems worse that SIFT and SURF and I would expect the opposite. If I understand correctly then SIFT/SURF use a 16x16 and 20x20 square block respectedly around the test-point so I would expect them not to find keypoints 8 and 10 pixels from an edge. FAST/ORB uses a circle of diameter 7 around the test-point so I expected it to find keypoints even closer to the edge, perhaps as close as 4 pixels (though I think the associated algorithm, BRIEF, to describe keypoints uses a larger window so this would remove some keypoints). An experiment makes nonsense of my prediction. The minimum distance from the edge in my experiments vary with the size and spacing of the squares but examples are SIFT .. 5 pixels SURF .. 15 pixels ORB .. 39 pixels Can anyone explain why? The code I used is below. I drew a grid of squares and applied a Gaussian blur. I expected the algorithms to latch onto the corners but they found the centres of the squares and some artifacts. import numpy as np import cv2 size = 501; border = 51; step = 10 image = np.zeros( (size,size), np.uint8 ) # fill with disjoint squares def drawsquare(img,i,j): restsize = step//5 cv2.rectangle(img,(i-restsize,j-restsize),(i+restsize,j+restsize),255,-1) for i in range(0,size,step): for j in range(0,size,step): drawsquare(image,i,j) # blank out the middle image[border:size-border,border:size-border] = 0 # and blur image = cv2.GaussianBlur(image,(5,5),0) imgcopy = image.copy() descriptor = cv2.xfeatures2d.SIFT_create(nfeatures=2000) kps = descriptor.detect(image) minpt = min([p for k in kps for p in k.pt ]) print("#{} SIFT keypoints, min coord is {} ".format(len(kps),minpt)) imgcopy = cv2.drawKeypoints(imgcopy,kps,imgcopy,(0,0,255)) cv2.imshow( "SIFT(red)", imgcopy ) cv2.waitKey() descriptor = cv2.xfeatures2d.SURF_create() kps, descs = descriptor.detectAndCompute(image,None) minpt = min([p for k in kps for p in k.pt ]) print("#{} SURF keypoints , min coord is {}".format(len(kps),minpt)) imgcopy = cv2.drawKeypoints(imgcopy,kps,imgcopy,(0,255,255)) cv2.imshow( "SIFT(red)+SURF(yellow)", imgcopy ) cv2.waitKey() descriptor = cv2.ORB_create(nfeatures=800) kps = descriptor.detect(image) minpt = min([p for k in kps for p in k.pt ]) print("#{} ORB keypoints, min coord is {} ".format(len(kps),minpt)) imgcopy = cv2.drawKeypoints(imgcopy,kps,imgcopy,(0,255,0)) cv2.imshow( "SIFT(red)+SURF(yellow)+ORB-detect(green)", imgcopy ) cv2.waitKey() kps, descs = descriptor.compute(image,kps) minpt = min([k.pt[0] for k in kps]+[k.pt[1] for k in kps]) print("#{} ORB described keypoints, min coord is {} ".format(len(kps),minpt)) imgcopy = cv2.drawKeypoints(imgcopy,kps,imgcopy,(255,0,0)) cv2.imshow( "SIFT(red)+SURF(yelow)+ORB-compute(blue)", imgcopy ) cv2.waitKey() cv2.imwrite("/tmp/grid-with-keypoints.png",imgcopy) Output of program is #2000 SIFT keypoints, min coord is 5.140756607055664 #1780 SURF keypoints , min coord is 15.0 #592 ORB keypoints, min coord is 39.60000228881836 #592 ORB described keypoints, min coord is 39.60000228881836 and the image is Addendum Grillteller answered my question and gave me an extra parameter in the creation-code for an ORB detector. If I write descriptor = cv2.ORB_create(nfeatures=800,edgeThreshold=0) then I get output #950 ORB keypoints, min coord is 9.953282356262207 | Usually, keypoints at the edge of the image are not useful for most applications. Consider e.g. a moving car or a plane for aerial images. Points at the image border are often not visible in the following frame. When calculating 3D reconstructions of objects most of the time the object of interest lies in the center of the image. Also the fact you mentioned, that most feature detectors work with areas of interest around pixels is important since these regions could give unwanted effects at the image border. Going into the source code of OpenCV ORB (848-849) uses a function with an edgeThreshold that can be defined using cv::ORB::create() and is set to a default value of 31 pixels. "This is size of the border where the features are not detected. It should roughly match the patchSize parameter." // Remove keypoints very close to the border KeyPointsFilter::runByImageBorder(keypoints, img.size(), edgeThreshold); The function is defined as: void KeyPointsFilter::runByImageBorder( std::vector<KeyPoint>& keypoints, Size imageSize, int borderSize ) { if( borderSize > 0) { if (imageSize.height <= borderSize * 2 || imageSize.width <= borderSize * 2) keypoints.clear(); else keypoints.erase( std::remove_if(keypoints.begin(), keypoints.end(), RoiPredicate(Rect(Point(borderSize, borderSize), Point(imageSize.width - borderSize, imageSize.height - borderSize)))), keypoints.end() ); } } and removes keypoints close to the edge using keypoints.erase(). For SIFT the relevant line (92-93) can be found here: // width of border in which to ignore keypoints static const int SIFT_IMG_BORDER = 5; I assume that SURF uses a similar parameter (=15?) but as far as I know these parameters in SIFT and SURF can not simply be changed in a function call like for ORB. | 6 | 6 |
63,667,255 | 2020-8-31 | https://stackoverflow.com/questions/63667255/plotting-graphs-in-c | I have made the following graph using matplotlib in python.I have also attached the code I used to make this. The code for the arena import matplotlib.pyplot as plt import matplotlib.patches as patches obs_boundary = [ [0, 0, 10, 600], [0, 600, 900, 10], [10, 0, 900, 10], [900, 10, 10, 600] ] obs_cir_own = [ [50,500,10], [100,300,10], [240,240,10], [300,400,10], [190,50,10] ] obs_cir_opp = [ [700, 420, 10], [460, 200, 10], [550, 500, 10], [670, 70, 10], [800, 230, 10], [600,300,10] ] fig, ax = plt.subplots() for (ox, oy, w, h) in obs_boundary: print(ox, oy, w, h) ax.add_patch( patches.Rectangle( (ox, oy), w, h, edgecolor='black', facecolor='black', fill=True ) ) for (ox, oy,r) in obs_cir_own: ax.add_patch( patches.Circle( (ox, oy), r, edgecolor='black', facecolor='green', fill=True ) ) for (ox, oy, r) in obs_cir_opp: ax.add_patch( patches.Circle( (ox, oy), r, edgecolor='black', facecolor='red', fill=True ) ) plt.plot(50,50, "bs", linewidth=30) plt.plot(870, 550, "ys", linewidth=30) name='arena' plt.title(name) plt.axis("equal") So, I want to implement a similar arena using C++ and I have no idea how to do it? I researched I got to know something about qtplot again I dont know much about qt. So, is qtplot the only way or there are some easier way. Please tell me how to implement this in C++. | You could try https://github.com/lava/matplotlib-cpp, which looks like it is just a wrapper around matplotlib anyway, so you are still calling/using Python and matplotlib in the end. With this you probably can copy your code nearly verbatim to "C++". | 7 | 13 |
63,665,702 | 2020-8-31 | https://stackoverflow.com/questions/63665702/why-is-binding-a-class-instance-method-different-from-binding-a-class-method | I was reading the python docs and stumbled upon the following lines: It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class. Please, someone explain what does that mean in plain english. I'm going to introduce some shorthand notation: let 'user-defined functions' be denoted by f, let 'class instance' be denoted by ci while class denoted simply by c. Obviously(?), ci = c(), with some abuse of notation. Also, allow membership statements to be recast in simple set notation eg 'user-defined functions which are attributes of a class instance' in shorthand is 'vf: fΞ΅a(ci)', where v: 'for all' and where 'a' is the shorthand for (set of) attributes (eg of a class or class instance) and 'Ξ΅' denotes the set membership function. Also, the process of binding a function is described in shorthand by ci.f(*args) or c.f(*args) => f(ci, *args) or f(c, *args) (the former referring to an instance method call while the later referring to a class method call) Using the newly introduced shorthand notation, does the quote from the docs imply that vf: fΞ΅a(c), c.f(*args) => f(c, *args) is a true statement while vf: fΞ΅a(ci), ci.f(*args) => f(ci, *args) is false? | Setting a User Defined Method to be an Attribute of Class, The Wrong Way Consider the following example class A and function f: class A: pass def f(self): print("I\'m in user-defined function") a = A() The function f is defined separately and not inside the class. Let's say you want to add function f to be an instance method for a object. Adding it, by setting f as a attribute, won't work: import types class A: pass def f(self): print("I\'m in user-defined function") a = A() a.f = f # <function f at 0x000002D81F0DED30> print(a.f) # TypeError: f() missing 1 required positional argument: 'self' # a.f() Because function f is not bound to the object a. That is why when calling a.f() it shall raise an error regarding the missing argument (if f has been bounded to a, that object a was the missing argument self). This part is what the docs referred at: It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods. Of course, all this has not to happen if function f has been defined inside class A, that's what the following part from the docs states: ...this only happens when the function is an attribute of the class. Setting a User Defined Method to be an Attribute of Class, The Right Way To add function f to object a you should use: import types class A: pass def f(self): print("I\'m in user-defined function") a = A() a.f = types.MethodType( f, a ) # <bound method f of <__main__.A object at 0x000001EDE4768E20>> print(a.f) # Works! I'm in user-defined function a.f() Which bounds the user-defined method f to instance a. | 14 | 13 |
63,614,899 | 2020-8-27 | https://stackoverflow.com/questions/63614899/stay-solid-and-dry-with-coroutines-and-functions-as-methods-in-python | I have that Code example: from time import sleep import asyncio class bird: def __init__(self, sleeptime=1): self.var = sleeptime def wait_meep(self): sleep(self.var) print("Meep") def do_sth(self): print("Dop Dop Do do ...") class bird_async: def __init__(self, sleeptime=1): self.var = sleeptime async def wait_meep(self): await asyncio.sleep(self.var) print("Meep") def do_sth(self): print("Dop Dop Do do ...") As you can see, both clients are mostly identical and shall contain the same name (so that everyone knows what to expect). Now I want to be DRY and write bird_async(bird). Because every extension in bird shall be used in bird_async as well. This is possible, but my coworker says, it is not SOLID, because I have overwritten wait_meep. Now I am looking for different soultions and found abstract classes. What I don't know is, if creating an abstract class birdBase(ABC) would be SOLID as well. I would overwrite there as well, because first it was a function and then a couroutine, or am I wrong here? What could be a SOLID and DRY solution to get those both classes together, without renaming the methods? | The DRY solution is some kind of subclassing as you already did. I think a "SOLID" solution is very hard to achieve under your condition. Fact is, you have two functions wait_meep, which have actually different signature and semantics. Namely, the first one blocks for the sleep interval, which can be arbitrary long. The second one OTOH is async, i.e. needs special calling semantics and runs concurrently. A somewhat comparable case is the Queue class from the standard library. There you have get and get_nowait methods which do the same, in different ways. Second example could be __iter__ and __aiter__ methods. So I think the only "correct" solution would be renaming one of the methods. Which would have the side effect that you could write it all as one class, i.e. reduce number of moving parts. | 8 | 6 |
63,661,711 | 2020-8-30 | https://stackoverflow.com/questions/63661711/when-where-does-pypy-produce-machine-code | I have skimmed through the PyPy implementation details and went through the source code as well, but PyPy's execution path is still not totally clear to me. Sometimes Bytecode is produced, sometimes it is skipped for immediate machine-code compiling (interpreter level/app level code), But I can't figure out when and where exactly is the machine code produced, to be handed to the OS for binary execution through low-level instructions (RAM/CPU). I managed to get that straight in the case of CPython, as there is a giant switch in ceval.c - that is already compiled - which interprets bytecode and runs the corresponding code (in actual C actually). Makes sense.But as far as PyPy is concerned, I did not manage to get a clear view on how this is done, specifically (I do not want to get into the various optimization details of PyPy, that's not what I am after here). I would be satisfied with an answer that points to the PYPY source code, so to avoid "hearsay" and be able to see it "with my eyes" (I spotted the JIT backends part, under /rpython, with the various CPU architectures assemblers) | Your best guide is the pypy architecture documentation, and the actual JIT documentation. What jumped out the most for me is this: we have a tracing JIT that traces the interpreter written in RPython, rather than the user program that it interprets. This is covered in more detail in the JIT overview. It seems to be that the "core" is this (from here): Once the meta-interpreter has verified that it has traced a loop, it decides how to compile what it has. There is an optional optimization phase between these actions which is covered future down this page. The backend converts the trace operations into assembly for the particular machine. It then hands the compiled loop back to the frontend. The next time the loop is seen in application code, the optimized assembly can be run instead of the normal interpreter. This paper (PDF) might also be helpful. Edit: Looking at the x86 backend rpython/jit/backend/x86/rx86.py, the backend doesn't so much as compile but spit out machine code directly. Look at the X86_64_CodeBuilder and AbstractX86CodeBuilder classes. One level higher is the Assembler386 class in rpython/jit/backend/x86/assembler.py. This assembler uses the MachineCodeBlockWrapper from rpython/jit/backend/x86/codebuf.py which is based on the X86_64_CodeBuilder for x86-64. | 8 | 3 |
63,661,866 | 2020-8-30 | https://stackoverflow.com/questions/63661866/ordinal-encoder-issues-with-nan-values | I have a dataframe with blank spaces as missing values, so I have replaced them with NaN values by using a regex. The problem that I have is when I want to use ordinal encoding for replacing categorical values. My code so far is the following: x=pd.DataFrame(np.array([30,"lawyer","France", 25,"clerk","Italy", 22," ","Germany", 40,"salesman","EEUU", 34,"lawyer"," ", 50,"salesman","France"] ).reshape(6,3)) x.columns=["age","job","country"] x = x.replace(r'^\s*$', np.nan, regex=True) oe=preprocessing.OrdinalEncoder() df.job=oe.fit_transform(df["job"].values.reshape(-1,1)) I got the following error: Input contains NaN I would like that the job column gets replaced with numbers such as: [1,2,-1,3,1,3]. | You can try with factorize, notice here is category start with 0 x.job.mask(x.job==' ').factorize()[0] Out[210]: array([ 0, 1, -1, 2, 0, 2], dtype=int32) | 6 | 4 |
63,658,086 | 2020-8-30 | https://stackoverflow.com/questions/63658086/tensorflow-2-0-valueerror-while-loading-weights-from-h5-file | I have a VAE architecture script as follows: import numpy as np import tensorflow as tf from tensorflow.keras.layers import Input, Conv2D, Flatten, Dense, Conv2DTranspose, Lambda, Reshape, Layer from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam from tensorflow.keras import backend as K INPUT_DIM = (64,64,3) CONV_FILTERS = [32,64,64, 128] CONV_KERNEL_SIZES = [4,4,4,4] CONV_STRIDES = [2,2,2,2] CONV_ACTIVATIONS = ['relu','relu','relu','relu'] DENSE_SIZE = 1024 CONV_T_FILTERS = [64,64,32,3] CONV_T_KERNEL_SIZES = [5,5,6,6] CONV_T_STRIDES = [2,2,2,2] CONV_T_ACTIVATIONS = ['relu','relu','relu','sigmoid'] Z_DIM = 32 BATCH_SIZE = 100 LEARNING_RATE = 0.0001 KL_TOLERANCE = 0.5 class Sampling(Layer): def call(self, inputs): mu, log_var = inputs epsilon = K.random_normal(shape=K.shape(mu), mean=0., stddev=1.) return mu + K.exp(log_var / 2) * epsilon class VAEModel(Model): def __init__(self, encoder, decoder, r_loss_factor, **kwargs): super(VAEModel, self).__init__(**kwargs) self.encoder = encoder self.decoder = decoder self.r_loss_factor = r_loss_factor def train_step(self, data): if isinstance(data, tuple): data = data[0] def compute_kernel(x, y): x_size = tf.shape(x)[0] y_size = tf.shape(y)[0] dim = tf.shape(x)[1] tiled_x = tf.tile(tf.reshape(x, tf.stack([x_size, 1, dim])), tf.stack([1, y_size, 1])) tiled_y = tf.tile(tf.reshape(y, tf.stack([1, y_size, dim])), tf.stack([x_size, 1, 1])) return tf.exp(-tf.reduce_mean(tf.square(tiled_x - tiled_y), axis=2) / tf.cast(dim, tf.float32)) def compute_mmd(x, y): x_kernel = compute_kernel(x, x) y_kernel = compute_kernel(y, y) xy_kernel = compute_kernel(x, y) return tf.reduce_mean(x_kernel) + tf.reduce_mean(y_kernel) - 2 * tf.reduce_mean(xy_kernel) with tf.GradientTape() as tape: z_mean, z_log_var, z = self.encoder(data) reconstruction = self.decoder(z) reconstruction_loss = tf.reduce_mean( tf.square(data - reconstruction), axis = [1,2,3] ) reconstruction_loss *= self.r_loss_factor kl_loss = 1 + z_log_var - tf.square(z_mean) - tf.exp(z_log_var) kl_loss = tf.reduce_sum(kl_loss, axis = 1) kl_loss *= -0.5 true_samples = tf.random.normal(tf.stack([BATCH_SIZE, Z_DIM])) loss_mmd = compute_mmd(true_samples, z) total_loss = reconstruction_loss + loss_mmd grads = tape.gradient(total_loss, self.trainable_weights) self.optimizer.apply_gradients(zip(grads, self.trainable_weights)) return { "loss": total_loss, "reconstruction_loss": reconstruction_loss, "kl_loss": kl_loss, "mmd_loss": loss_mmd } def call(self,inputs): latent = self.encoder(inputs) return self.decoder(latent) class VAE(): def __init__(self): self.models = self._build() self.full_model = self.models[0] self.encoder = self.models[1] self.decoder = self.models[2] self.input_dim = INPUT_DIM self.z_dim = Z_DIM self.learning_rate = LEARNING_RATE self.kl_tolerance = KL_TOLERANCE def _build(self): vae_x = Input(shape=INPUT_DIM, name='observation_input') vae_c1 = Conv2D(filters = CONV_FILTERS[0], kernel_size = CONV_KERNEL_SIZES[0], strides = CONV_STRIDES[0], activation=CONV_ACTIVATIONS[0], name='conv_layer_1')(vae_x) vae_c2 = Conv2D(filters = CONV_FILTERS[1], kernel_size = CONV_KERNEL_SIZES[1], strides = CONV_STRIDES[1], activation=CONV_ACTIVATIONS[0], name='conv_layer_2')(vae_c1) vae_c3= Conv2D(filters = CONV_FILTERS[2], kernel_size = CONV_KERNEL_SIZES[2], strides = CONV_STRIDES[2], activation=CONV_ACTIVATIONS[0], name='conv_layer_3')(vae_c2) vae_c4= Conv2D(filters = CONV_FILTERS[3], kernel_size = CONV_KERNEL_SIZES[3], strides = CONV_STRIDES[3], activation=CONV_ACTIVATIONS[0], name='conv_layer_4')(vae_c3) vae_z_in = Flatten()(vae_c4) vae_z_mean = Dense(Z_DIM, name='mu')(vae_z_in) vae_z_log_var = Dense(Z_DIM, name='log_var')(vae_z_in) vae_z = Sampling(name='z')([vae_z_mean, vae_z_log_var]) #### DECODER: vae_z_input = Input(shape=(Z_DIM,), name='z_input') vae_dense = Dense(1024, name='dense_layer')(vae_z_input) vae_unflatten = Reshape((1,1,DENSE_SIZE), name='unflatten')(vae_dense) vae_d1 = Conv2DTranspose(filters = CONV_T_FILTERS[0], kernel_size = CONV_T_KERNEL_SIZES[0] , strides = CONV_T_STRIDES[0], activation=CONV_T_ACTIVATIONS[0], name='deconv_layer_1')(vae_unflatten) vae_d2 = Conv2DTranspose(filters = CONV_T_FILTERS[1], kernel_size = CONV_T_KERNEL_SIZES[1] , strides = CONV_T_STRIDES[1], activation=CONV_T_ACTIVATIONS[1], name='deconv_layer_2')(vae_d1) vae_d3 = Conv2DTranspose(filters = CONV_T_FILTERS[2], kernel_size = CONV_T_KERNEL_SIZES[2] , strides = CONV_T_STRIDES[2], activation=CONV_T_ACTIVATIONS[2], name='deconv_layer_3')(vae_d2) vae_d4 = Conv2DTranspose(filters = CONV_T_FILTERS[3], kernel_size = CONV_T_KERNEL_SIZES[3] , strides = CONV_T_STRIDES[3], activation=CONV_T_ACTIVATIONS[3], name='deconv_layer_4')(vae_d3) #### MODELS vae_encoder = Model(vae_x, [vae_z_mean, vae_z_log_var, vae_z], name = 'encoder') vae_decoder = Model(vae_z_input, vae_d4, name = 'decoder') vae_full = VAEModel(vae_encoder, vae_decoder, 10000) opti = Adam(lr=LEARNING_RATE) vae_full.compile(optimizer=opti) return (vae_full,vae_encoder, vae_decoder) def set_weights(self, filepath): self.full_model.load_weights(filepath) def train(self, data): self.full_model.fit(data, data, shuffle=True, epochs=1, batch_size=BATCH_SIZE) def save_weights(self, filepath): self.full_model.save_weights(filepath) Problem: vae = VAE() vae.set_weights(filepath) throws: File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py", line 2200, in load_weights 'Unable to load weights saved in HDF5 format into a subclassed ' ValueError: Unable to load weights saved in HDF5 format into a subclassed Model which has not created its variables yet. Call the Model first, then load the weights. I am not sure what this means since I am not that proficient in OOP. The surprising bit is that the above code was working until it stopped working. The model is training from scratch and it saves the weights in filepath. But when I am loading the same weights now it is throwing the above error! | What version of TF are you running? For a while the default saving format was hdf5, but this format cannot support subclassed models as easily, so you get this error. It may be solvable by first training it on a single batch and then loading the weights (to determine how the parts are connected, which is not saved in hdf5). In the future I would recommend making sure that all saves are done with the TF file format though, it will save you from extra work. | 10 | 3 |
63,656,891 | 2020-8-30 | https://stackoverflow.com/questions/63656891/importerror-plotly-express-requires-pandas-to-be-installed | When I try to import plotly.express I get the error: ImportError: Plotly express requires pandas to be installed. The installation notes did not mention having to install anything additional. I can import plotly on its own, I only get the error when importing plotly.express. Any ideas on how to fix this? | Pandas is a dependency that is only used in plotly.express not in plotly. For more you can visit this issue.So you need to install pandas using pip install pandas or conda install -c anaconda pandas | 11 | 5 |
63,655,115 | 2020-8-30 | https://stackoverflow.com/questions/63655115/indexerror-replacement-index-1-out-of-range-for-positional-args-tuple | I am following a tutorial and I don't know why I got this error: <ipython-input-61-d59f7a5a07ab> in extract_featuresets(ticker) 2 tickers, df = process_data_for_labels(ticker) 3 df['{}_target'.format(ticker)] = list(map(buy_sell_hold, ----> 4 df['{}_{}1d'.format(ticker)], 5 df['{}_{}2d'.format(ticker)], 6 df['{}_{}3d'.format(ticker)], IndexError: Replacement index 1 out of range for positional args tuple Here is my code: tickers, df = process_data_for_labels(ticker) df['{}_target'.format(ticker)] = list(map(buy_sell_hold, df['{}_{}1d'.format(ticker)], df['{}_{}2d'.format(ticker)], df['{}_{}3d'.format(ticker)], df['{}_{}4d'.format(ticker)], df['{}_{}5d'.format(ticker)], df['{}_{}6d'.format(ticker)], df['{}_{}7d'.format(ticker)],)) Here is the link to the tutorial: https://www.youtube.com/watch?v=zPp80YM2v7k | Your format string need two arguments in format while you are only passing in one ticker as argument. If ticker is a two element list or tuple, you can do this: df['{}_{}1d'.format(*ticker)] Otherwise remove one curly brackets: df['{}_1d'.format(ticker)] | 18 | 31 |
63,650,646 | 2020-8-29 | https://stackoverflow.com/questions/63650646/add-labels-and-title-to-a-plot-made-using-pandas | I made a simple histogram using the following code: a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e'] pd.Series(a).value_counts().plot('bar') Although this is a concise way to plot frequency histogram, I am not sure how to customize the plot i.e. : Add Title Add Axis Labels Sort values on x-axis | Series.plot (or DataFrame.plot) returns a matplotlib axis object which exposes several methods. For example: a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e'] ax = pd.Series(a).value_counts().sort_index().plot('bar') ax.set_title("my title") ax.set_xlabel("my x-label") ax.set_ylabel("my y-label") n.b.: pandas uses matplotlib as a dependency here, and is exposing matplotlib objects and api. You can get the same result via import matplotlib.pyplot as plt; ax = plt.subplots(1,1,1). If you ever create more than one plot at a time, you will find the ax.<method> far more convenient than the module level plt.title('my title'), because it defines which plot title you'd like to change and you can take advantage of autocomplete on the ax object. | 7 | 7 |
63,648,184 | 2020-8-29 | https://stackoverflow.com/questions/63648184/error-installing-packages-using-pip-you-must-use-visual-studio-to-build-a-pyth | I am using VS Code on Windows 10. When I try to install the face_recognition package using pip I get the following error: ERROR: Command errored out with exit status 1: command: 'c:\users\admin\appdata\local\programs\python\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-fi__6w9v\\dlib\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-fi__6w9v\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-f5b3pskr\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\admin\appdata\local\programs\python\python38\Include\dlib' cwd: C:\Users\Admin\AppData\Local\Temp\pip-install-fi__6w9v\dlib\ Complete output (60 lines): running install running build running build_py package init file 'tools\python\dlib\__init__.py' not found (or not a regular file) running build_ext Building extension for Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] Invoking CMake setup: 'cmake C:\Users\Admin\AppData\Local\Temp\pip-install-fi__6w9v\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\Admin\AppData\Local\Temp\pip-install-fi__6w9v\dlib\build\lib.win-amd64-3.8 -DPYTHON_EXECUTABLE=c:\users\admin\appdata\local\programs\python\python38\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\Admin\AppData\Local\Temp\pip-install-fi__6w9v\dlib\build\lib.win-amd64-3.8 -A x64' -- Building for: NMake Makefiles CMake Error at CMakeLists.txt:5 (message): !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! You must use Visual Studio to build a python extension on windows. If you are getting this error it means you have not installed Visual C++. Note that there are many flavors of Visual Studio, like Visual Studio for C# development. You need to install Visual Studio for C++. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -- Configuring incomplete, errors occurred! Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Admin\AppData\Local\Temp\pip-install-fi__6w9v\dlib\setup.py", line 223, in <module> setup( File "c:\users\admin\appdata\local\programs\python\python38\lib\site-packages\setuptools\__init__.py", line 144, in setup return distutils.core.setup(**attrs) File "c:\users\admin\appdata\local\programs\python\python38\lib\distutils\core.py", line 148, in setup dist.run_commands() File "c:\users\admin\appdata\local\programs\python\python38\lib\distutils\dist.py", line 966, in run_commands self.run_command(cmd) File "c:\users\admin\appdata\local\programs\python\python38\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "c:\users\admin\appdata\local\programs\python\python38\lib\site-packages\setuptools\command\install.py", line 61, in run return orig.install.run(self) File "c:\users\admin\appdata\local\programs\python\python38\lib\distutils\command\install.py", line 545, in run self.run_command('build') File "c:\users\admin\appdata\local\programs\python\python38\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\users\admin\appdata\local\programs\python\python38\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "c:\users\admin\appdata\local\programs\python\python38\lib\distutils\command\build.py", line 135, in run self.run_command(cmd_name) File "c:\users\admin\appdata\local\programs\python\python38\lib\distutils\cmd.py", line 313, in run_command self.distribution.run_command(command) File "c:\users\admin\appdata\local\programs\python\python38\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "C:\Users\Admin\AppData\Local\Temp\pip-install-fi__6w9v\dlib\setup.py", line 135, in run self.build_extension(ext) File "C:\Users\Admin\AppData\Local\Temp\pip-install-fi__6w9v\dlib\setup.py", line 172, in build_extension subprocess.check_call(cmake_setup, cwd=build_folder) File "c:\users\admin\appdata\local\programs\python\python38\lib\subprocess.py", line 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-fi__6w9v\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-fi__6w9v\\dlib\\build\\lib.win-amd64-3.8', '-DPYTHON_EXECUTABLE=c:\\users\\admin\\appdata\\local\\programs\\python\\python38\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-fi__6w9v\\dlib\\build\\lib.win-amd64-3.8', '-A', 'x64']' returned non-zero exit status 1. ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\admin\appdata\local\programs\python\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-fi__6w9v\\dlib\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-fi__6w9v\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-f5b3pskr\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\admin\appdata\local\programs\python\python38\Include\dlib' Check the logs for full command output. I tried to install dlib before installing face_recognition. | The answer is really simple. You have to do what it says. Go to the VS installer and install VS for C++ and C#. The reason is that these modules use C code and while using Visual Studio, you have to make it so that it can compile the C++ code | 8 | 8 |
63,647,103 | 2020-8-29 | https://stackoverflow.com/questions/63647103/merging-pandas-dataframes-with-respect-to-a-function-output | Is there a convenient way to merge two dataframes with respect to the distance between rows? For the following example, I want to get the color for df1 rows from the closest df2 rows. The distance should be computed as ((x1-x2)**0.5+(y1-y2)**0.5)**0.5. import pandas as pd df1 = pd.DataFrame({'x': [50,16,72,61,95,47],'y': [14,22,11,45,58,56],'size':[1,4,3,7,6,5]}) df2 = pd.DataFrame({'x': [10,21,64,31,25,55],'y': [54,76,68,24,34,19],'color':['red','green','blue','white','brown','black']}) | Something from numpy broadcast df1['color']=df2.color.iloc[np.argmin(np.sum(np.abs(df1[['x','y']].values-df2[['x','y']].values[:,None])**0.5,2),0)].values df1 Out[79]: x y size color 0 50 14 1 black 1 16 22 4 white 2 72 11 3 black 3 61 45 7 blue 4 95 58 6 blue 5 47 56 5 red | 8 | 6 |
63,642,961 | 2020-8-29 | https://stackoverflow.com/questions/63642961/split-list-recursively-until-flat | I'm writing a passion program that will determine the best poker hand given hole cards and community cards. As an ace can go both ways in a straight, I've coded this as [1, 14] for a given 5 card combination. I understand recursion but implementing it is a different story for me. I'm looking for a function that will split all aces recursively, into all possible hand combinations until all nested lists are exhausted. This should obviously work with up to 4 aces, overlooking the fact that you wouldn't care about a straight at that point in all likelihood. hand = [[1, 14], 2, 3, [1, 14], 7] desired_output = [ [1, 2, 3, 1, 7], [1, 2, 3, 14, 7], [14, 2, 3, 1, 7], [14, 2, 3, 14, 7] ] I'm not proud of what I have so far, especially because it returns a list instead of something like a yield which would build the list I'm looking for: def split_first_ace(hand): aces = [True if isinstance(x, list) else False for x in hand] for i, x in enumerate(aces): if x: ranks_temp = hand.copy() ace = ranks_temp.pop(i) return [[ace[0]] + ranks_temp, [ace[1]] + ranks_temp] Any help on a solution would be appreciated, mostly because it'll help me understand how to implement recursion. But I'm open to other solutions as well. | Well, there is an easier way to do this: from itertools import product product(*[i if isinstance(i, list) else [i] for i in hand]) I challenge everybody to come up with a simpler solution | 20 | 20 |
63,635,104 | 2020-8-28 | https://stackoverflow.com/questions/63635104/plotly-how-to-set-choropleth-map-color-for-a-discrete-categorical-variable | I am trying to plot a world map with all the countries having different risk levels (low, moderate and high). I would like to make each risk level a different color but am not sure how to change the color scheme so that each risk category has a color of my choice. The df.risk variable currently has low as 1, moderate as 2 and high as 3 so that it is a continuous variable, however I would like to use discrete, fig = go.Figure(data=go.Choropleth( locations = df['code'], z = df['risk'], text = df['COUNTRY'], colorscale = 'Rainbow', autocolorscale=False, reversescale=True, marker_line_color='darkgray', marker_line_width=0.5, colorbar_tickprefix = '', colorbar_title = 'Risk level', )) fig.update_layout( title_text='Risk map', geo=dict( showframe=False, showcoastlines=False, projection_type='equirectangular' ), annotations = [dict( x=0.55, y=0.15, xref='paper', yref='paper', text='Source: <a href="www.google.com">\ Google</a>', showarrow = False )] ) fig.show() My sample df is: {'Country': {0: 'Afghanistan', 1: 'Albania', 2: 'Algeria', 3: 'American Samoa', 4: 'Andorra'}, 'code': {0: 'AFG', 1: 'ALB', 2: 'DZA', 3: 'ASM', 4: 'AND'}, 'risk': {0: 'High', 1: 'Moderate', 2: 'High', 3: 'Low', 4: 'High'}} | In this case I would rather use plotly.express with color=df['risk'] and then set color_discrete_map={'High':'red', 'Moderate':'Yellow','Low':'Green'}: Plot: Complete code: import plotly.express as px import pandas as pd fig = px.choropleth(locations=df['Country'], locationmode="country names", color=df['risk'], color_discrete_map={'High':'red', 'Moderate':'Yellow', 'Low':'Green'} #scope="usa" ) fig.show() | 13 | 10 |
63,639,543 | 2020-8-28 | https://stackoverflow.com/questions/63639543/how-to-get-top-n-rows-with-a-max-limit-by-group-in-pandas | I have a dataframe which looks like this pd.DataFrame({'A': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10'], ...: 'B': ['A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C'], ...: 'R': [9, 1, 7, 4, 3, 5, 2, 6, 8, 10]}) Out[3]: A B R 0 C1 A 9 1 C2 A 1 2 C3 A 7 3 C4 B 4 4 C5 B 3 5 C6 B 5 6 C7 B 2 7 C8 C 6 8 C9 C 8 9 C10 C 10 column R is my rank column and I want to get the top 5 ranked items (column A), however, maximum of 3 items per group in column B can be selected. I know I can do the following to select the top 5 ranked items df.sort_values('R').head(5) Out[10]: A B R 1 C2 A 1 6 C7 B 2 4 C5 B 3 3 C4 B 4 5 C6 B 5 But this selects 4 items from group B. how can i restrict it to have only a maximum of 3 items per group selected? my resulting dataframe should look like this A B R 1 C2 A 1 6 C7 B 2 4 C5 B 3 3 C4 B 4 5 C8 C 6 Logic - item C6 is not selected as it is the 4th item of group B so the next available item to be selected is C8 which has the next best rank and does not breach the group limitation. | We can try with GroupBy.head new_df = df.sort_values('R').groupby('B', sort=False).head(3).head(5) print(new_df) A B R 1 C2 A 1 6 C7 B 2 4 C5 B 3 3 C4 B 4 7 C8 C 6 | 6 | 8 |
63,626,723 | 2020-8-28 | https://stackoverflow.com/questions/63626723/find-missing-elements-in-a-list-created-from-a-sequence-of-consecutive-integers | This is a Find All Numbers Disappeared in an Array problem from LeetCode: Given an array of integers where 1 β€ a[i] β€ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6] My code is below - I think its O(N) but interviewer disagrees def findDisappearedNumbers(self, nums: List[int]) -> List[int]: results_list=[] for i in range(1,len(nums)+1): if i not in nums: results_list.append(i) return results_list | You can implement an algorithm where you loop through each element of the list and set each element at index i to a negative integer if the list contains the element i as one of the values,. You can then add each index i which is positive to your list of missing items. It doesn't take any additional space and uses at the most 3 for loops(not nested), which makes the complexity O(3*n), which is basically O(n). This site explains it much better and also provides the source code. edit- I have added the code in case someone wants it: #The input list and the output list input = [4, 5, 3, 3, 1, 7, 10, 4, 5, 3] missing_elements = [] #Loop through each element i and set input[i - 1] to -input[i - 1]. abs() is necessary for #this or it shows an error for i in input: if(input[abs(i) - 1] > 0): input[abs(i) - 1] = -input[abs(i) - 1] #Loop through the list again and append each positive value to output list for i in range(0, len(input)): if input[i] > 0: missing_elements.append(i + 1) | 7 | 4 |
63,637,395 | 2020-8-28 | https://stackoverflow.com/questions/63637395/addition-between-int-and-custom-class | I was experimenting around with dunders in python when I found something: Say I created a class: class MyInt: def __init__(self, val): self.val = val def __add__(self, other): return self.val + other a = MyInt(3) The __add__ works perfectly fine when this is run: >>> print(a + 4) 7 However, when I ran this: >>> print(4 + a) TypeError: unsupported operand type(s) for +: 'int' and 'MyInt' I know that the int class does not support adding with MyInt, but are there any workarounds for this? | This is what the __radd__ method is for - if your custom object is on the right side of the operator, and the left side of the operator can't handle it. Note that the left side of the operator will take precedence, if possible. >>> class MyInt: ... def __init__(self, val): ... self.val = val ... def __add__(self, other): ... return self.val + other ... def __radd__(self, other): ... return self + other ... >>> a = MyInt(3) >>> print(a + 4) 7 >>> print(4 + a) 7 The third 'hidden' method you can override, for any given operator, will be __iadd__, which corresponds to the assignment operator +=. | 8 | 12 |
63,628,218 | 2020-8-28 | https://stackoverflow.com/questions/63628218/how-to-get-current-time-in-india-in-python | How would I get the current timestamp in python of India? I tried time.ctime() and datetime.utcnow() also datetime.now() but they all return a different time than here it is in india. The codes above return the time that not match the current time on my computer. and the time in my computer is definitely correct. | from pytz import timezone from datetime import datetime ind_time = datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S.%f') print(ind_time) >>> "2020-08-28 11:56:37.010822" | 6 | 19 |
63,603,325 | 2020-8-26 | https://stackoverflow.com/questions/63603325/error-no-matching-distribution-found-for-ipython-7-17-0 | I uploaded a Python app to Heroku. In my requirements.txt file I have a line for ipython==7.17.0 but Heroku seems unable to retrieve it, I don't understand why this might happen because I'm able to download that ipython version on my machine. The complete error thrown is: ERROR: Could not find a version that satisfies the requirement ipython==7.17.0 (from -r /tmp/build_76afe907/requirements.txt (line 32)) (from versions: 0.10, 0.10.1, 0.10.2, 0.11, 0.12, 0.12.1, 0.13, 0.13.1, 0.13.2, 1.0.0, 1.1.0, 1.2.0, 1.2.1, 2.0.0, 2.1.0, 2.2.0, 2.3.0, 2.3.1, 2.4.0, 2.4.1, 3.0.0, 3.1.0, 3.2.0, 3.2.1, 3.2.2, 3.2.3, 4.0.0b1, 4.0.0, 4.0.1, 4.0.2, 4.0.3, 4.1.0rc1, 4.1.0rc2, 4.1.0, 4.1.1, 4.1.2, 4.2.0, 4.2.1, 5.0.0b1, 5.0.0b2, 5.0.0b3, 5.0.0b4, 5.0.0rc1, 5.0.0, 5.1.0, 5.2.0, 5.2.1, 5.2.2, 5.3.0, 5.4.0, 5.4.1, 5.5.0, 5.6.0, 5.7.0, 5.8.0, 5.9.0, 5.10.0, 6.0.0rc1, 6.0.0, 6.1.0, 6.2.0, 6.2.1, 6.3.0, 6.3.1, 6.4.0, 6.5.0, 7.0.0b1, 7.0.0rc1, 7.0.0, 7.0.1, 7.1.0, 7.1.1, 7.2.0, 7.3.0, 7.4.0, 7.5.0, 7.6.0, 7.6.1, 7.7.0, 7.8.0, 7.9.0, 7.10.0, 7.10.1, 7.10.2, 7.11.0, 7.11.1, 7.12.0, 7.13.0, 7.14.0, 7.15.0, 7.16.0, 7.16.1) ERROR: No matching distribution found for ipython==7.17.0 (from -r /tmp/build_76afe907/requirements.txt (line 32)) | The last allowed version is 7.16.1, that means you use Python 3.6. 7.17 requires Python 3.7+. | 6 | 12 |
63,623,113 | 2020-8-27 | https://stackoverflow.com/questions/63623113/i-am-trying-to-use-cv2-solvepnp-but-i-am-getting-an-error | This is the error: cv2.solvePnP(obj_points, image_points, mtx, dist) cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\calib3d\src\solvepnp.cpp:754: error: (-215:Assertion failed) ( (npoints >= 4) || (npoints == 3 && flags == SOLVEPNP_ITERATIVE && useExtrinsicGuess) ) && npoints == std::max(ipoints.checkVector(2, CV_32F), ipoints.checkVector(2, CV_64F)) in function 'cv::solvePnPGeneric' And this is my code: mtx = np.load("./camera_params/mtx.npy") dist = np.load("./camera_params/dist.npy") obj_points = np.array([[0, 0, 0], [297, 0, 0], [297, 210, 0], [0, 210, 0]]) image_points = np.array([[416, 268], [422, 535], [826, 543], [829, 264]]) cv2.solvePnP(obj_points, image_points, mtx, dist) I don't have any idea how to solve it. I tried to play with the arguments but it didn't help. If you know a way to solve this error it be very helpful. | I had this error very recently, and I resolved it by making the argument ndarrays floats instead of ints. You can do that in 2 ways: obj_points = np.array([[0.0, 0.0, 0.0], [297.0, 0.0, 0.0], [297.0, 210.0, 0.0], [0.0, 210.0, 0.0]]) image_points = np.array([[416.0, 268.0], [422.0, 535.0], [826.0, 543.0], [829.0, 264.0]]) obj_points = np.array([[0, 0, 0], [297, 0, 0], [297, 210, 0], [0, 210, 0]]) obj_points = obj_points.astype('float32') image_points = np.array([[416, 268], [422, 535], [826, 543], [829, 264]]) image_points = image_points.astype('float32') | 6 | 5 |
63,616,798 | 2020-8-27 | https://stackoverflow.com/questions/63616798/how-to-pass-the-default-value-to-a-variable-if-none-was-passed | Can I make a default value in Pydantic if None is passed in the field? I have the following code, but it seems to me that the validator here only works on initialization of the model and not otherwise. My Code: class User(BaseModel): name: Optional[str] = '' password: Optional[str] = '' email: EmailStr @validator('name') def set_name(cls, name): return name or 'foo' Problem Encountered: user = User(name=None, password='some_password', email='[email protected]') print("Name is ", user.name) # > 'Name is foo' user.name = None print("Name is ", user.name) # > 'Name is None' Desired Output: user = User(name='some_name', password='some_password', email='[email protected]') user.name = None print("Name is ", user.name) # > 'Name is foo' Any ideas on how I can obtain the desired output? I think having getters and setters will help in tackling the issue. However, I could not get them to work in a Pydantic model: Attempting to implement getters and setters: class User(BaseModel): name: Optional[str] = '' password: Optional[str] = '' email: EmailStr def get_password(self): return self.password def set_password(self, password): self.password = hash_password(password) password = property(get_password, set_password) user = User(name='some_name', password='some_password', email='[email protected]') # > RecursionError: maximum recursion depth exceeded I also tried the property decorator: class User(BaseModel): name: Optional[str] = '' password: Optional[str] = '' email: EmailStr @property def password(self): return self._password @password.setter def password(self, password): pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") self._password = pwd_context.hash(password) user = User(name='some_name', email='[email protected]') user.password = 'some_password' # > ValueError: "User" object has no field "password" I also tried overwriting the init: class User(BaseModel): name: Optional[str] = "" password: Optional[str] = "" email: EmailStr def __init__(self, name, password, email): pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") password = pwd_context.hash(password) super().__init__(name=name, password=password, email=email) user = User(name="some_name", password="some_password", email='[email protected]') print(user.password) # > AYylwSnbQgCHrl4uue6kO7yiuT20lazSzK7x # Works as expected user.password = "some_other_password" print(user.password) # > "some_other_password" # Does not work user.password = None print(user.password) # > None # Does not work either | You need to enable validate_assignment option in model config: from typing import Optional from pydantic import BaseModel, validator class User(BaseModel): name: Optional[str] = '' password: Optional[str] = '' class Config: validate_assignment = True @validator('name') def set_name(cls, name): return name or 'foo' user = User(name=None, password='some_password', ) print("Name is ", user.name) user.name = None print("Name is ", user.name) Name is foo Name is foo | 61 | 56 |
63,615,560 | 2020-8-27 | https://stackoverflow.com/questions/63615560/boto3-dynamodb-put-item-error-only-accepts-keyword-arguments | I'm using boto3 in a lambda function to write information into a dynamodb table. I get the error put_item() only accepts keyword arguments. Searching on the web, i found that this error may mean that I am not matching dynamodb partition key, but it seems to me that I am doing everything correctly. Can anyone help me find the error? Excuse me but this is my first time using aws. This is my lambda function import json, boto3 def updateDynamo(Item): dynamodb = boto3.resource('dynamodb', region_name = 'eu-central-1') table = dynamodb.Table('userInformations') response = table.put_item(Item) return response def lambda_handler(event, context): userAttributes = event["request"]["userAttributes"] email = userAttributes["email"] name = userAttributes["name"] Item = { "email": email, "name" : name } response = updateDynamo(Item) print(email, name) return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') } This is the test event i'm using: { "version": "string", "triggerSource": "string", "region": "AWSRegion", "userPoolId": "string", "userName": "string", "callerContext": { "awsSdkVersion": "string", "clientId": "string" }, "request": { "userAttributes": { "email": "[email protected]", "name": "test user" } }, "response": {} } My table has email (all char are lowercase) as partition key. | put_item requires keyword only arguments. This means, that in your case instead of: response = table.put_item(Item) there should be response = table.put_item(Item=Item) | 7 | 11 |
63,614,660 | 2020-8-27 | https://stackoverflow.com/questions/63614660/testing-fastapi-formdata-upload | I'm trying to test the upload of a file and its metadata using Python and FastAPI. Here is how I defined the route for the upload: @app.post("/upload_files") async def creste_upload_files(uploaded_files: List[UploadFile], selectedModel: str = Form(...), patientId: str = Form(...), patientSex: str = Form(...), actualMedication: str = Form(...), imageDim: str = Form(...), imageFormat: str = Form(...), dateOfScan: str = Form(...)): for uploaded_dicom in uploaded_files: upload_folder = "webapp/src/data/" file_object = uploaded_dicom.file #create empty file to copy the file_object to upload_folder = open(os.path.join(upload_folder, uploaded_dicom.filename), 'wb+') shutil.copyfileobj(file_object, upload_folder) upload_folder.close() return "hello" (I'm not using the metadata but I will later). I use unittest for the testing: class TestServer(unittest.TestCase): def setUp(self): self.client = TestClient(app) self.metadata = { "patientId": "1", "patient_age": "M", "patientSex": "59", "patient_description": "test", "actualeMedication": "test", "dateOfScan": datetime.strftime(datetime.now(), "%d/%m/%Y"), "selectedModel": "unet", "imageDim": "h", "imageFormat": "h" } def tearDown(self): pass def test_dcm_upload(self): dicom_file = pydicom.read_file("tests/data/1-001.dcm") bytes_data = dicom_file.PixelData files = {"uploaded_files": ("dicom_file", bytes_data, "multipart/form-data")} response = self.client.post( "/upload_files", json=self.metadata, files=files ) print(response.json()) But it seems that the upload doesn't work, I get the following print of the response: {'detail': [{'loc': ['body', 'selectedModel'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'patientId'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'patientSex'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'actualMedication'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'imageDim'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'imageFormat'], 'msg': 'field required', 'type': 'value_error.missing'}, {'loc': ['body', 'dateOfScan'], 'msg': 'field required', 'type': 'value_error.missing'}]} It is possible that I should upload using a Formdata instead of the body request (json=self.metadata) but I don't know how it should be done. | The answer is just to replace json=self.metadata which can be used for body parameters by data=self.metadata for a formData | 8 | 13 |
63,604,630 | 2020-8-26 | https://stackoverflow.com/questions/63604630/dataclass-how-do-i-create-a-field-that-does-not-need-initializing-which-is-auto | I used field(init= False) to disable initializing self.ref. It is then a value in post. The following code raises AttributeError: 'Data' object has no attribute 'ref' from dataclasses import dataclass, field def make_list(): return [[0] for k in range(9)] @dataclass class Data: rows: list cols: list blocks: list ref: dict = field(init=False) def __init__(self, slots=None): self.rows = make_list() self.cols = make_list() self.blocks = make_list() if slots: for i in range(9): for j in range(9): self.cols[j][i] = self.rows[i][j] = slots[i][j] def __post_init__(self): print("post-init executed") self.ref = {"rows": self.rows, "cols": self.cols, "blocks": self.blocks} test = Data() print(test) I am using python 3.8. The code is tested in both pycharm/jupyter. (Same error) Edit: after correcting the typo: __post__init__ to __post_init__ , I am still getting the error. | Thanks to @wim and @juanpa.arrivillaga Deleting the __init__ would fix the problem and let the __post_init__ run again. (As pointed out by wim and juanpa.arrivillaga) If I write my own __init__ , why even bother writing __post_init__ , I can write all post processing all I want in there. (line order) from dataclasses import dataclass, field @dataclass class Data: rows: list cols: list = field(init=False) blocks: list = field(init=False) ref: dict = field(init=False) def __post_init__(self): print("post init\n\n") self.cols = [k*10 for k in self.rows] # code transform rows to cols self.blocks = [k*20 for k in self.rows] # code transform rows to blocks self.ref = {"rows": self.rows, "cols": self.cols, "blocks": self.blocks} test = Data([1,2,3]) print(test) Also, I might want to reconsider rewriting it using regular class as the code stands now since using dataclass here does not provide anything more than a regular class. | 20 | 17 |
63,601,580 | 2020-8-26 | https://stackoverflow.com/questions/63601580/use-gpu-with-opencv-python | I'm trying to use opencv-python with GPU on windows 10. I installed opencv-contrib-python using pip and it's v4.4.0.42, I also have Cuda on my computer and in path. Anyway, here is a (simple) code that I'm trying to compile: import cvlib as cv from cvlib.object_detection import draw_bbox bbox, label, conf = cv.detect_common_objects(img,confidence=0.5,model='yolov3-worker',enable_gpu=True) output_image = draw_bbox(img, bbox, label, conf) First, here is the line that tell me that tf is ok with cuda: 2020-08-26 5:51:55.718555: I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cudart64_101.dll but when I try to use my GPU to analyse the image, here is what happen: [ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-j8nxabm_\opencv\modules\dnn\src\dnn.cpp (1429) cv::dnn::dnn4_v20200609::Net::Impl::setUpNet DNN module was not built with CUDA backend; switching to CPU Is there a way to solve this without install opencv using cmake? It's a mess on windows... | The problem here is that version of opencv distributed with your system (Windows in this case) was not compiled with Cuda support. Therefore, you cannot use any cuda related function with this build. If you want to have an opencv with cuda support, you will have to either compile it yourself (which may be tedious on windows) or find a prebuilt one somewhere. In case you want to go for the 1st solution, here is a link that may help you with the process: https://programming.vip/docs/compile-opencv-with-cuda-support-on-windows-10.html. Keep in mind that this will require you to install a bunch of SDK in the process. | 22 | 10 |
63,599,687 | 2020-8-26 | https://stackoverflow.com/questions/63599687/is-it-better-to-pre-allocate-array-in-python-or-use-arr-append | In terms of readability and performance, should I pre-allocate memory for an array using [None]*n? Is allocating an empty one [] and using .append() over and over considered wasteful? | In this simple timing test, the use of [None] * n does indeed appear to be slightly quicker, but arguably not by enough to justify adopting this approach over the more usual idioms. import time def func1(size): a = [None] * size for i in range(size): a[i] = i def func2(size): a = [] for i in range(size): a.append(i) def func3(size): a = [i for i in range(size)] size = 1000000 repeat = 100 t0 = time.time() for _ in range(repeat): func1(size) t1 = time.time() for _ in range(repeat): func2(size) t2 = time.time() for _ in range(repeat): func2(size) t3 = time.time() print(t1 - t0, t2 - t1, t3 - t2) Results: [None * size] and then index: 4.82 seconds append in a loop: 6.37 seconds list comprehension: 6.34 seconds Repeating the tests with size=1000 and repeat=100000 give similar results: [None * size] and then index: 3.16 seconds append in a loop: 4.88 seconds list comprehension: 4.84 seconds And again with size=10 and repeat = 10000000: [None * size] and then index: 6.09 seconds append in a loop: 7.65 seconds list comprehension: 7.66 seconds | 8 | 8 |
63,599,290 | 2020-8-26 | https://stackoverflow.com/questions/63599290/how-to-save-json-responses-with-asynchronous-requests | I have a question regarding asynchronous requests: How do I save response.json() to a file, on the fly? I want to make a request and save response to a .json file, without keeping it in memory. import asyncio import aiohttp async def fetch(sem, session, url): async with sem: async with session.get(url) as response: return await response.json() # here async def fetch_all(urls, loop): sem = asyncio.Semaphore(4) async with aiohttp.ClientSession(loop=loop) as session: results = await asyncio.gather( *[fetch(sem, session, url) for url in urls] ) return results if __name__ == '__main__': urls = ( "https://public.api.openprocurement.org/api/2.5/tenders/6a0585fcfb05471796bb2b6a1d379f9b", "https://public.api.openprocurement.org/api/2.5/tenders/d1c74ec8bb9143d5b49e7ef32202f51c", "https://public.api.openprocurement.org/api/2.5/tenders/a3ec49c5b3e847fca2a1c215a2b69f8d", "https://public.api.openprocurement.org/api/2.5/tenders/52d8a15c55dd4f2ca9232f40c89bfa82", "https://public.api.openprocurement.org/api/2.5/tenders/b3af1cc6554440acbfe1d29103fe0c6a", "https://public.api.openprocurement.org/api/2.5/tenders/1d1c6560baac4a968f2c82c004a35c90", ) loop = asyncio.get_event_loop() data = loop.run_until_complete(fetch_all(urls, loop)) print(data) For now, the script just prints JSON files, and I can save them once they're all scraped: data = loop.run_until_complete(fetch_all(urls, loop)) for i, resp in enumerate(data): with open(f"{i}.json", "w") as f: json.dump(resp, f) But it doesn't feel right to me as it will definitely fail once I run out of memory for example. Any suggestions? Edit Limited my post to only one question | How do I save response.json() to a file, on the fly? Don't use response.json() in the first place, use the streaming API instead: async def fetch(sem, session, url): async with sem, session.get(url) as response: with open("some_file_name.json", "wb") as out: async for chunk in response.content.iter_chunked(4096) out.write(chunk) | 6 | 3 |
63,597,476 | 2020-8-26 | https://stackoverflow.com/questions/63597476/pandas-dataframe-multiline-query | Say I have a dataframe import numpy as np import pandas as pd df = pd.DataFrame(np.random.randint(10, size=(10,3)), columns=['a', 'b', 'c']) if I now try to query it using the query method: this works: df.query('''a > 3 and b < 9''') this throws an error: df.query( ''' a > 3 and b < 9 ''' ) I tried many variations of multiline strings but the result is always the following error: ~/ven/lib/python3.6/site-packages/pandas/core/computation/eval.py in eval(expr, parser, engine, truediv, local_dict, global_dict, resolvers, level, target, inplace) 306 if multi_line and target is None: 307 raise ValueError( --> 308 "multi-line expressions are only valid in the " 309 "context of data, use DataFrame.eval" 310 ) ValueError: multi-line expressions are only valid in the context of data, use DataFrame.eval Does anyone know how to make it work? The problem is that in reality I have a very long query to do and it would be very inconvenient having to write all in one line. I know I could use boolean indexing instead but my question is only about how to use multiline with the query method. Thank you | Use multi-line char backslash ( \ ) Ex: df = pd.DataFrame(np.random.randint(10, size=(10,3)), columns=['a', 'b', 'c']) print(df.query( ''' a > 3 and \ b < 9 ''' )) | 21 | 21 |
63,591,449 | 2020-8-26 | https://stackoverflow.com/questions/63591449/celery-task-hangs-after-calling-delay-in-django | While calling the .delay() method of an imported task from a django application, the process gets stuck and the request is never completed. We also don't get any error on the console. Setting up a set_trace() with pdb results in the same thing. The following questions were reviewed which didn't help resolve the issue: Calling celery task hangs for delay and apply_async celery .delay hangs (recent, not an auth problem) Eg.: backend/settings.py CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", RABBIT_URL) CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER", RABBIT_URL) backend/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') app = Celery('backend') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) app/tasks.py import time from celery import shared_task @shared_task def upload_file(request_id): time.sleep(request_id) return True app/views.py from rest_framework.views import APIView from .tasks import upload_file class UploadCreateAPIView(APIView): # other methods... def post(self, request, *args, **kwargs): id = request.data.get("id", None) # business logic ... print("Going to submit task.") import pdb; pdb.set_trace() upload_file.delay(id) # <- this hangs the runserver as well as the set_trace() print("Submitted task.") | The issue was with the setup of the celery application with Django. We need to make sure that the celery app is imported and initialized in the following file: backend\__init__.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) | 7 | 14 |
63,589,351 | 2020-8-26 | https://stackoverflow.com/questions/63589351/environment-variables-not-updating | I am using the dotenv package. I had a key that I had saved in my .env file but I updated it to a new key, but my script still outputs the old key. I have the ".env" file in the root directory. I thought that by using load_dotenv() that it's taking in the new keys whatever they may be at the current state in time and saving it to be used in the script. What am I doing wrong? import os from dotenv import load_dotenv import praw load_dotenv() reddit = praw.Reddit(client_id=os.getenv('reddit_personal_use'), client_secret=os.getenv('reddit_api_key'), user_agent=os.getenv('reddit_app_name'), username=os.getenv('reddit_username'), password=os.getenv('reddit_pw')) | I had to set override=True load_dotenv(override=True) load_dotenv does not override existing System environment variables. To override, pass override=True to load_dotenv(). | 25 | 63 |
63,583,880 | 2020-8-25 | https://stackoverflow.com/questions/63583880/make-isort-recognize-imports-from-django-apps-as-first-party-imports | I'm working on a project with many different Django apps. I want to use isort on this project but the imports from Django apps (from myapp1.mymodule import myfunction) are seen by isort as third-party imports. How can I make isort recognize them as first-party imports? I could add in the isort configuration (in the .cfg): known_first_party=myapp1,myapp2... but I'll have to maintain this list. Is there a better way? | You can use the src_paths option to specify the project folder. You do not need to maintain a known_first_party list. See the related source code: if ( _is_module(module_path) or _is_package(module_path) or _src_path_is_module(src_path, root_module_name) ): return (sections.FIRSTPARTY, f"Found in one of the configured src_paths: {src_path}.") | 8 | 7 |
63,488,416 | 2020-8-19 | https://stackoverflow.com/questions/63488416/how-to-move-files-from-current-path-to-a-specific-folder-named-like-or-similar-t | My Folder Structure looks like this: - 95000 - 95002 - 95009 - AR_95000.pdf - AR_95002.pdf - AR_95009.pdf - BS_95000.pdf - BS_95002.pdf - BS_95009.pdf [Note 95000, 95002, 95009 are folders] My goal is to move files AR_95000.pdf and BS_95000.pdf to the folder named 95000, then AR_95002.pdf and BS_95002.pdf to the folder named 95002 and so on. The PDFs are reports generated by system and thus I can not control the naming. | Using pathlib this task becomes super easy: from pathlib import Path root = Path("/path/to/your/root/dir") for file in root.glob("*.pdf"): folder_name = file.stem.rpartition("_")[-1] file.rename(root / folder_name / file.name) As you can see, one main advantage of pathlib over os/shutil (in this case) is the interface Path objects provide directly to os-like functions. This way the actual copying (rename()) is done directly as an instance method. References: Path.glob Path.stem str.rpartition Path.rename path concatenation | 22 | 50 |
63,587,660 | 2020-8-25 | https://stackoverflow.com/questions/63587660/yielding-asyncio-generator-data-back-from-event-loop-possible | I would like to read from multiple simultanous HTTP streaming requests inside coroutines using httpx, and yield the data back to my non-async function running the event loop, rather than just returning the final data. But if I make my async functions yield instead of return, I get complaints that asyncio.as_completed() and loop.run_until_complete() expects a coroutine or a Future, not an async generator. So the only way I can get this to work at all is by collecting all the streamed data inside each coroutine, returning all data once the request finishes. Then collect all the coroutine results and finally returning that to the non-async calling function. Which means I have to keep everything in memory, and wait until the slowest request has completed before I get all my data, which defeats the whole point of streaming http requests. Is there any way I can accomplish something like this? My current silly implementation looks like this: def collect_data(urls): """Non-async function wishing it was a non-async generator""" async def stream(async_client, url, payload): data = [] async with async_client.stream("GET", url=url) as ar: ar.raise_for_status() async for line in ar.aiter_lines(): data.append(line) # would like to yield each line here return data async def execute_tasks(urls): all_data = [] async with httpx.AsyncClient() as async_client: tasks = [stream(async_client, url) for url in urls] for coroutine in asyncio.as_completed(tasks): all_data += await coroutine # would like to iterate and yield each line here return all_events try: loop = asyncio.get_event_loop() data = loop.run_until_complete(execute_tasks(urls=urls)) return data # would like to iterate and yield the data here as it becomes available finally: loop.close() I've tried some solutions using asyncio.Queue and trio memory channels as well, but since I can only read from those in an async scope it doesn't get me any closer to a solution. The reason I want to use this from a non-asyncronous generator is that I want to use it from a Django app using a Django Rest Framework streaming API. | Normally you should just make collect_data async, and use async code throughout - that's how asyncio was designed to be used. But if that's for some reason not feasible, you can iterate an async iterator manually by applying some glue code: def iter_over_async(ait, loop): ait = ait.__aiter__() # helper async fn that just gets the next element # from the async iterator async def get_next(): try: obj = await ait.__anext__() return False, obj except StopAsyncIteration: return True, None # actual sync iterator (implemented using a generator) while True: done, obj = loop.run_until_complete(get_next()) if done: break yield obj The way the above works is by providing an async closure that keeps retrieving the values from the async iterator using the __anext__ magic method and returning the objects as they arrive. This async closure is invoked with run_until_complete() in a loop inside an ordinary sync generator. (The closure actually returns a pair of done indicator and actual object in order to avoid propagating StopAsyncIteration through run_until_complete, which might be unsupported.) With this in place, you can make your execute_tasks an async generator (async def with yield) and iterate over it using: for chunk in iter_over_async(execute_tasks(urls), loop): ... Just note that this approach is incompatible with asyncio.run, and assumes the event loop can only be run "occasionally". This might cause issues in more complex async code which might want to set up some background tasks - but for simple code it should be fine. | 7 | 13 |
63,493,530 | 2020-8-19 | https://stackoverflow.com/questions/63493530/how-to-plot-and-annotate-a-grouped-bar-chart | I came across a tricky issue about the matplotlib in Python. I want to create a grouped bar chart with several codes, but the chart goes wrong. Could you please offer me some advice? The code is as follows. import numpy as np import pandas as pd file="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/coursera/Topic_Survey_Assignment.csv" df=pd.read_csv(file,index_col=0) df.sort_values(by=['Very interested'], axis=0,ascending=False,inplace=True) df['Very interested']=df['Very interested']/2233 df['Somewhat interested']=df['Somewhat interested']/2233 df['Not interested']=df['Not interested']/2233 df df_chart=df.round(2) df_chart labels=['Data Analysis/Statistics','Machine Learning','Data Visualization', 'Big Data (Spark/Hadoop)','Deep Learning','Data Journalism'] very_interested=df_chart['Very interested'] somewhat_interested=df_chart['Somewhat interested'] not_interested=df_chart['Not interested'] x=np.arange(len(labels)) w=0.8 fig,ax=plt.subplots(figsize=(20,8)) rects1=ax.bar(x-w,very_interested,w,label='Very interested',color='#5cb85c') rects2=ax.bar(x,somewhat_interested,w,label='Somewhat interested',color='#5bc0de') rects3=ax.bar(x+w,not_interested,w,label='Not interested',color='#d9534f') ax.set_ylabel('Percentage',fontsize=14) ax.set_title("The percentage of the respondents' interest in the different data science Area", fontsize=16) ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend(fontsize=14) def autolabel(rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 3, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(rects1) autolabel(rects2) autolabel(rects3) fig.tight_layout() plt.show() The output of this code module is really a mess. But what I expect should look like the bar chart in the picture. Could you please tell me which point is not correct in my codes? | Imports and DataFrame import pandas as pd import matplotlib.pyplot as plt # given the following code to create the dataframe file = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/coursera/Topic_Survey_Assignment.csv" df = pd.read_csv(file, index_col=0) df.sort_values(by=['Very interested'], axis=0, ascending=False, inplace=True) # all columns are being divided by 2233 so those lines can be replace with the following single line df = df.div(2233) # display(df) Very interested Somewhat interested Not interested Data Analysis / Statistics 0.755934 0.198836 0.026870 Machine Learning 0.729512 0.213614 0.033139 Data Visualization 0.600090 0.328706 0.045678 Big Data (Spark / Hadoop) 0.596507 0.326467 0.056874 Deep Learning 0.565607 0.344828 0.060905 Data Journalism 0.192118 0.484102 0.273175 Using since matplotlib v3.4.2 Uses matplotlib.pyplot.bar_label and pandas.DataFrame.plot Some formatting can be done with the fmt parameter, but more sophisticated formatting should be done with the labels parameter, as show in How to add multiple annotations to a barplot. See How to add value labels on a bar chart for additional details and examples using .bar_label This answer shows how to use the fmt= or label= parameter filter out low values from the annotations. # your colors colors = ['#5cb85c', '#5bc0de', '#d9534f'] # plot with annotations is probably easier ax = df.plot(kind='bar', color=colors, figsize=(20, 8), rot=0, ylabel='Percentage', title="The percentage of the respondents' interest in the different data science Area") for c in ax.containers: ax.bar_label(c, fmt='%.2f', label_type='edge') Using before matplotlib v3.4.2 w = 0.8 / 3 will resolve the issue, given the current code. However, generating the plot can be accomplished more easily with pandas.DataFrame.plot # your colors colors = ['#5cb85c', '#5bc0de', '#d9534f'] # plot with annotations is probably easier ax = df.plot.bar(color=colors, figsize=(20, 8), ylabel='Percentage', title="The percentage of the respondents' interest in the different data science Area") ax.set_xticklabels(ax.get_xticklabels(), rotation=0) for p in ax.patches: ax.annotate(f'{p.get_height():0.2f}', (p.get_x() + p.get_width() / 2., p.get_height()), ha = 'center', va = 'center', xytext = (0, 10), textcoords = 'offset points') If file is no longer available, replace df = pd.read_csv(file, index_col=0) with: data = {'Very interested': [1332, 1688, 429, 1340, 1263, 1629], 'Somewhat interested': [729, 444, 1081, 734, 770, 477], 'Not interested': [127, 60, 610, 102, 136, 74]} df = pd.DataFrame(data, index=['Big Data (Spark / Hadoop)', 'Data Analysis / Statistics', 'Data Journalism', 'Data Visualization', 'Deep Learning', 'Machine Learning']) | 7 | 12 |
63,512,788 | 2020-8-20 | https://stackoverflow.com/questions/63512788/how-to-fix-the-google-auth-exceptions-refresherror-no-access-token-in-respon | I followed the video from TechWithTim step by step (https://www.youtube.com/watch?v=cnPlKLEGR7E) but I am still getting an error when I try to open the sheet. The code works fine until sheet = client.open("GuildTaxes").sheet1 line. Here is my code. import gspread from oauth2client.service_account import ServiceAccountCredentials scope = ["https://spreadsheets.google.com/feeds","https://www.googleapis.com/auth/sprea...", "https://www.googleapis.com/auth/drive...","https://www.googleapis.com/auth/drive"] creds = ServiceAccountCredentials.from_json_keyfile_name("GuildTaxes-9ba4508be840.json", scope) client = gspread.authorize(creds) sheet = client.open("GuildTaxes").sheet1 data = sheet.get_all_records() print(data) | I found the answer! After 2 hours, the scope in TechWithTim's video doesn't work for me, so if you stumble upon the same issue try using this one scope = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] It is the default scope. | 7 | 21 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.