eshangj/stackoverflow_q_and_a_sample huggingface dataset:
Question: Given an array of integers arr, your task is to count the number of contiguous subarrays that represent a sawtooth sequence of at least two elements. For arr = [9, 8, 7, 6, 5], the output should be countSawSubarrays(arr) = 4. Since all the elements are arranged in decreasing order, it won’t be possible to form any sawtooth subarray of length 3 or more. There are 4 possible subarrays containing two elements, so the answer is 4. For arr = [10, 10, 10], the output should be countSawSubarrays(arr) = 0. Since all of the elements are equal, none of subarrays can be sawtooth, so the answer is 0. For arr = [1, 2, 1, 2, 1], the output should be countSawSubarrays(arr) = 10. All contiguous subarrays containing at least two elements satisfy the condition of the problem. There are 10 possible contiguous subarrays containing at least two elements, so the answer is 10. What would be the best way to solve this question? I saw a possible solution here:https://medium.com/swlh/sawtooth-sequence-java-solution-460bd92c064 But this code fails for the case [1,2,1,3,4,-2] where the answer should be 9 but it comes as 12. I have even tried a brute force approach but I am not able to wrap my head around it. Any help would be appreciated! EDIT: Thanks to Vishal for the response, after a few tweaks, here is the updated solution in python. Time Complexity: O(n) Space Complexity: O(1) def samesign(a,b): if a/abs(a) == b/abs(b): return True else: return False def countSawSubarrays(arr): n = len(arr) if n<2: return 0 s = 0 e = 1 count = 0 while(e<n): sign = arr[e] - arr[s] while(e<n and arr[e] != arr[e-1] and samesign(arr[e] - arr[e-1], sign)): sign = -1*sign e+=1 size = e-s if (size==1): e+=1 count += (size*(size-1))//2 s = e-1 e = s+1 return count arr1 = [9,8,7,6,5] print(countSawSubarrays(arr1)) arr2 = [1,2,1,3,4,-2] print(countSawSubarrays(arr2)) arr3 = [1,2,1,2,1] print(countSawSubarrays(arr3)) arr4 = [10,10,10] print(countSawSubarrays(arr4))  Result: 4 9 10 0

Answer: This can be solved by just splitting the array into multiple sawtooth sequences..which is O(n) operation. For example [1,2,1,3,4,-2] can be splitted into two sequence [1,2,1,3] and [3,4,-2] and now we just have to do C(size,2) operation for both the parts. Here is psedo code explaining the idea ( does not have all corner cases handled )  public int countSeq(int[] arr) { int len = arr.length; if (len < 2) { return 0; } int s = 0; int e = 1; int sign = arr[e] - arr[s]; int count = 0; while (e < len) { while (e < len && arr[e] - arr[e-1] != 0 && isSameSign(arr[e] - arr[e-1], sign)) { sign = -1 * sign; e++; } // the biggest continue subsequence starting from s ends at e-1; int size = e - s; count = count + (size * (size - 1)/2); // basically doing C(size,2) s = e - 1; e = s + 1; } return count;  }
Question: I'm running a Jupyter Notebook on VS code and trying to display/play a video. From all the other forums, I've seen that using IPython.display is the standard method; however, it isn't working for me. For example, for Video: from IPython.display import Video Video('test.mp4')  This code generates a video box in the output and I don't have any errors but I can't press play. The same happens when I try playing an Audio file. I've ensured that the file is in the current folder and I'm using Python 3.8.2 in a virtual environment (venv) and IPython 7.27.0.

Answer: To get it to work I did the following: Uninstalled and reinstalled VS Code and installed the extensions Python, Jupyter and Jupyter Keymap Installed FFmpeg through Homebrew: brew install ffmpeg  Converted the video codec from "MPEG4" to "H.264": ffmpeg -i test.mp4 video.mp4  Then used the following code to display the video: from IPython.display import Video Video('video.mp4', width=128, height=128)
Question: print("Fazli's Vet Services\n") print("Exam: 50") print("Vaccinations: 25") print("Trim Nails: 5") print("Bath: 20\n") exam = "exam" vaccinations = "vaccinations" trim_nails = "trim nails" bath = "bath" none = "none" exam_price = 50 vaccination_price = 25 trim_nails_price = 5 bath_price = 20 none_price = 0 first_service = input("Select first service:") second_service = input("Select second service:") print("\nFazli's Vet Invoice") if first_service == exam: print("Service 1 - Exam: " + str(exam_price)) elif first_service == vaccinations: print("Service 1 - Vaccinations: " + str(vaccination_price)) elif first_service == trim_nails: print("Service 1 - Trim Nails: " + str(trim_nails_price)) elif first_service == bath: print("Service 1 - Bath: " + str(bath_price)) elif first_service == none: print("Service 1 - None " + str(none_price)) else: print("Service 1 - None " + str(none_price)) if second_service == exam: print("Service 2 - Exam: " + str(exam_price)) elif second_service == vaccinations: print("Service 2 - Vaccinations: " + str(vaccination_price)) elif second_service == trim_nails: print("Service 2 - Trim Nails: " + str(trim_nails_price)) elif second_service == bath: print("Service 2 - Bath: " + str(bath_price)) elif second_service == none: print("Service 2 - None " + str(none_price)) else: print("Service 2 - None " + str(none_price))  Above is a code I have so far. It prints: Fazli's Vet Services Exam: 50 Vaccinations: 25 Trim Nails: 5 Bath: 20 Select first service: exam Select second service: bath Fazli's Vet Invoice Service 1 - Exam: 50 Service 2 - Bath: 20  My goal is for the code to add up the two services and make a total price. My end goal should look like this: Chanucey's Vet Services Exam: 45 Vaccinations: 32 Trim Nails: 8 Bath: 15 Select first service: Exam Select second service: none Chauncey's Vet Invoice Service 1 - Exam: 45 Service 2 - None: 0 Total: 45  Notice how the code added both prices and made a "Total." Is there any way I can do this? I'm a beginner computer science major, so we aren't too far into Python. ALL CODE IS IN PYTHON

Answer: Use dictionary - print("Fazli's Vet Services\n") print("Exam: 50") print("Vaccinations: 25") print("Trim Nails: 5") print("Bath: 20\n") dictionary = {'exam':50,'vaccinations':25,'trim nails':5,'bath':20,'none':0} first_service = input("Select first service:").lower() second_service = input("Select second service:").lower() print("\nFazli's Vet Invoice") if first_service in dictionary: price1 = int(dictionary[first_service]) print(f'Service 1 - {first_service.capitalize()} : {price1}') else: price1 = 0 print(f'Service 1 - None : 0') if second_service in dictionary: price2 = int(dictionary[second_service]) print(f'Service 1 - {second_service.capitalize()} : {price2}') else: price2 = 0 print(f'Service 1 - None : 0') print('Total : ',price1+price2)
Question: I'm following this blog post to create a runtime environment using Docker for use with AWS Lambda. I'm creating a layer for using with Python 3.8: 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"  And then archiving the layer as zip: zip -9 -r mylayer.zip python  All standard so far. The problem arises in the .zip size, which is > 250mb and so creates the following error in Lambda: Failed to create layer version: Unzipped size must be smaller than 262144000 bytes. Here's my requirements.txt: s3fs scrapy pandas requests  I'm including s3fs since I get the following error when trying to save a parquet file to an S3 bucket using pandas: [ERROR] ImportError: Install s3fs to access S3. This problem is that including s3fs massively increases the layer size. Without s3fs the layer is < 200mb unzipped. My most direct question would be: How can I reduce the layer size to < 250mb while still using Docker and keeping s3fs in my requirements.txt? I can't explain the 50mb+ difference, especially since s3fs < 100kb on PyPi. Finally, for those questioning my use of Lambda with Scrapy: my scraper is trivial, and spinning up an EC2 instance would be overkill.

Answer: The key idea behind shrinking your layers is to identify what pip installs and what you can get rid off, usually manually. In your case, since you are only slightly above the limit, I would get rid off pandas/tests. So before you create your zip layer, you can run the following in the layer's folder (mylayer from your past question): rm -rvf python/lib/python3.8/site-packages/pandas/tests  This should trim your layer below the 262MB limit after unpacking. In my test it is now 244MB. Alternatively, you can go over python folder manually, and start removing any other tests, documentations, examples, etc, that are not needed.
Question: I am using Django and I am accessing request.POST from my view. The code is as follows: data = request.POST print(data)  Which returns: <QueryDict: {'name': ['Sam'], 'phone': ['+10795524594'], 'message': ['Es-sénia'], 'Coupon': [''], 'csrfmiddlewaretoken': ['xcGnoJOtnAmXcUBXe01t7ItuMC8BAFHE 6H9Egqd8BuooxLbp3ZrqvwzTZAxukMJW', 'xcGnoJOtnAmXcUBXe01t7ItuMC8BAFHE6H9Egqd8BuooxLbp3Zrq``vwzTZAxukMJW'], 'Size': ['S', 'M']}>  But, whether using .dict() method or using data.get("Size"), I only get one element; not the whole list. How can I fix this?

Answer: Use data.getlist(key). It is a bit weird, see the docs: https://docs.djangoproject.com/en/3.2/ref/request-response/#django.http.QueryDict.getlist
Question: I'm trying to understand how to use the overload decorator when typing functions. If I write the following code and run it through mypy: from typing import Union, overload @overload def myfunc(a: float, b: float) -> float: ... @overload def myfunc(a: int, b: int) -> int: ... def myfunc(a: Union[float, int], b: Union[float, int]) -> Union[float, int]: return a + b  Then I get a "error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader Found 1 error in 1 file (checked 1 source file)" I don't understand why the parameter types of signature 1 (ie. floats) are broader that signature 2 (ie. ints). What is going on here?

Answer: mypy has a weird special case that treats int as valid where float is expected, because requiring people to write Union[int, float] all over the place would have been awkward enough to seriously hinder adoption of type annotations. That means myfunc(1, 2) matches both signatures. When multiple signatures of an overloaded function match a call, mypy will pick the signature defined first. With the way you've written your code, it's impossible for mypy to pick the int signature. The float signature will always be picked for any call. You can fix this by putting the int signature first: @overload def myfunc(a: int, b: int) -> int: ... @overload def myfunc(a: float, b: float) -> float: ...
Question: I'm trying to define a class that takes another class as an attribute _model and will instantiate objects of that class. from abc import ABC from typing import Generic, TypeVar, Any, ClassVar, Type Item = TypeVar("Item", bound=Any) class SomeClass(Generic[Item], ABC): _model: ClassVar[Type[Item]] def _compose_item(self, **attrs: Any) -> Item: return self._model(**attrs)  I think it should be obvious that self._model(**attrs) returns an instance of Item, since _model is explicitly declared as Type[Item] and attrs is declared as Dict[str, Any]. But what I'm getting from mypy 0.910 is: test.py: note: In member "_compose_item" of class "SomeClass": test.py:11: error: Returning Any from function declared to return "Item" return self._model(**attrs) ^  What am I doing wrong?

Answer: MyPy can sometimes be a bit funny about the types of classes. You can solve this by specifying _model as Callable[..., Item] (which, after all, isn't a lie) instead of Type[Item]: from abc import ABC from typing import Generic, TypeVar, Any, ClassVar, Callable Item = TypeVar("Item") class SomeClass(Generic[Item], ABC): _model: ClassVar[Callable[..., Item]] def _compose_item(self, **attrs: Any) -> Item: return self._model(**attrs)
Question: I'm trying to create a data stream in Python using the Twitter API, but I'm unable to import the StreamListener correctly. Here's my code: import tweepy from tweepy import Stream from tweepy.streaming import StreamListener class MyListener(StreamListener): def on_data(self, data): try: with open('python.json', 'a') as f: f.write(data) return True except BaseException as e: print("Error on_data: %s" % str(e)) return True def on_error(self, status): print(status) return True twitter_stream = Stream(auth, MyListener()) twitter_stream.filter(track=['#python'])  And I'm getting this error: Traceback (most recent call last): File "c:\Users\User\Documents\GitHub\tempCodeRunnerFile.python", line 6, in <module> from tweepy.streaming import StreamListener ImportError: cannot import name 'StreamListener' from 'tweepy.streaming' (C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\tweepy\streaming.py) 

Answer: Tweepy v4.0.0 was released yesterday and it merged StreamListener into Stream. I recommend updating your code to subclass Stream instead. Alternatively, you can downgrade to v3.10.0.
Question: When I run this from enum import Enum class MyEnumType(str, Enum): RED = 'RED' BLUE = 'BLUE' GREEN = 'GREEN' for x in MyEnumType: print(x)  I get the following as expected: MyEnumType.RED MyEnumType.BLUE MyEnumType.GREEN  Is it possible to create a class like this from a list or tuple that has been obtained from elsewhere? Something vaguely similar to this perhaps: myEnumStrings = ('RED', 'GREEN', 'BLUE') class MyEnumType(str, Enum): def __init__(self): for x in myEnumStrings : self.setattr(self, x,x)  However, in the same way as in the original, I don't want to have to explicitly instantiate an object.

Answer: You can use the enum functional API for this: from enum import Enum myEnumStrings = ('RED', 'GREEN', 'BLUE') MyEnumType = Enum('MyEnumType', myEnumStrings)  From the docs:  The first argument of the call to Enum is the name of the enumeration. The second argument is the source of enumeration member names. It can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to values.
Question: I had complex and nested data structure like below: { 0: { 0: {'S': 'str1', 'T': 4, 'V': 0x3ff}, 1: {'S': 'str2', 'T': 5, 'V': 0x2ff}}, 1: { 0: {'S': 'str3', 'T': 8, 'V': 0x1ff}, 1: {'S': 'str4', 'T': 7, 'V': 0x0ff}}, ...... }  It's a 2D dictionary basically. The innermost dict follows {Str: str, str:int, str:int}, while its outer dict always has integer as the key to index. Is there a way for Pydantic to validate the data-type and data structure? I mean if someone changes the data with a string as a key to the outer dict, the code should prompt an error. Or if someones tweaks the inner dict with putting 'V' value to a string, a checker needs to complain about it. I am new to Pydantic, and found it always requires a str-type field for any data... Any ideas?

Answer: You could use Dict as custom root type with int as key type (with nested dict). Like so: from pydantic import BaseModel, StrictInt from typing import Union, Literal, Dict sample = {0: {0: {'S': 'str1', 'T': 4, 'V': 0x3ff}, 1: {'S': 'str2', 'T': 5, 'V': 0x2ff}}, 1: {0: {'S': 'str3', 'T': 8, 'V': 0x1ff}, 1: {'S': 'str4', 'T': 7, 'V': 0x0ff}} } # innermost model class Data(BaseModel): S: str T: int V: int class Model(BaseModel): __root__: Dict[int, Dict[int, Data]] print(Model.parse_obj(sample))
Question: I am trying to create an Enum class dynamically, using type(name, base, dict). from enum import Enum class FriendlyEnum(Enum): def hello(self): print(self.name + ' says hello!')  The normal way works fine: class MyEnum(FriendlyEnum): foo = 1 bar = 2 MyEnum.foo.hello() # -> foo says hello!  But if I try dynamically: MyEnum = type('MyEnum', (FriendlyEnum,), {'foo':1,'bar':2} ) MyEnum.foo.hello() # -> File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 146, in __new__ enum_members = {k: classdict[k] for k in classdict._member_names} AttributeError: 'dict' object has no attribute '_member_names'  Any suggestions? It might be useful for testing the methods of a parent Enum class, dynamically creating new Enum classes with different attributes and same inherited methods.

Answer: The Enum class can be called to dynamically create a new Enum type. This will also work for subclasses of Enum MyEnum = FriendlyEnum('MyEnum', {'foo': 1, 'bar': 2}) MyEnum.foo.hello()
Question: I am trying to read data from athena into python's pandas dataframe. However, I encounter this error  WaiterError: Waiter BucketExists failed: Max attempts exceeded. Previously accepted state: Matched expected HTTP status code: 404  Do anyone have the same problem when using data wrangler? This is my code below import awswrangler as wr import pandas as pd wr.athena.read_sql_query('select * from ath_bi_orders limit 10', database='default') 

Answer: I have faced the same issue and resolved it by specifying AWS_DEFAULT_REGION env variable. Like this. os.environ['AWS_DEFAULT_REGION'] = 'ap-northeast-1' # specify your AWS region.  Execute it before you throw the query.
Question: I have written the following code : def check_token(token): response = requests.get("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com") key_list = response.json() decoded_token = jwt.decode(token, key=key_list, algorithms=["RS256"]) print(f"Decoded token : {decoded_token}")  I am trying to decode the token provided by firebase client side to verify it server-side. The above code is throwing the following exception : TypeError: Expecting a PEM-formatted key.  I have tried to not pass a list to the jwt.decode method, only the key content and i have a bigger error that the library could not deserialize the Key. I was following this answer but i am getting this error. Is it a requests conversion problem ? What am i doing wrong ?

Answer: The 2nd parameter key in decode() seems to take a string value instead of list. The Google API request returns a dict/map containing multiple keys. The flow goes like:  Fetch public keys from the Google API endpoint Then read headers without validation to get the kid claim then use it to get appropriate key from that dict That is a X.509 Certificate and not the public key as in this answer so you need to get public key from that.  The following function worked for me: import jwt import requests from cryptography.hazmat.backends import default_backend from cryptography import x509 def check_token(token): n_decoded = jwt.get_unverified_header(token) kid_claim = n_decoded["kid"] response = requests.get("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com") x509_key = response.json()[kid_claim] key = x509.load_pem_x509_certificate(x509_key.encode('utf-8'), backend=default_backend()) public_key = key.public_key() decoded_token = jwt.decode(token, public_key, ["RS256"], options=None, audience="<FIREBASE_PROJECT_ID>") print(f"Decoded token : {decoded_token}") check_token("FIREBASE_ID_TOKEN")
Question: I have an SVG file, for example, this <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <path fill="none" stroke="red" d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z" /> </svg>  How can I get the list of the points (x, y) for those paths? I have seen that answer but it's not full, so I'm asking for the full solution. I would like to have an option to choose how many points would be there or control of the density of the points.

Answer: Here you can change the scale, offset, and density of the points: from svg.path import parse_path from xml.dom import minidom def get_point_at(path, distance, scale, offset): pos = path.point(distance) pos += offset pos *= scale return pos.real, pos.imag def points_from_path(path, density, scale, offset): step = int(path.length() * density) last_step = step - 1 if last_step == 0: yield get_point_at(path, 0, scale, offset) return for distance in range(step): yield get_point_at( path, distance / last_step, scale, offset) def points_from_doc(doc, density=5, scale=1, offset=0): offset = offset[0] + offset[1] * 1j points = [] for element in doc.getElementsByTagName("path"): for path in parse_path(element.getAttribute("d")): points.extend(points_from_path( path, density, scale, offset)) return points string = """<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <path fill="none" stroke="red" d="M 10,30 A 20,20 0,0,1 50,30 A 20,20 0,0,1 90,30 Q 90,60 50,90 Q 10,60 10,30 z" /> </svg>""" doc = minidom.parseString(string) points = points_from_doc(doc, density=1, scale=5, offset=(0, 5)) doc.unlink()  And you can also visualize those points: import pygame from svg.path import parse_path from xml.dom import minidom ... # other functions and string def main(): screen = pygame.display.set_mode([500, 500]) screen.fill((255, 255, 255)) doc = minidom.parseString(string) points = points_from_doc(doc, 0.05, 5, (0, 5)) doc.unlink() for point in points: pygame.draw.circle(screen, (0, 0, 255), point, 1) pygame.display.flip() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: return pygame.init() main() pygame.quit()  density == 0.05:  density == 0.1:  density == 0.5:  density == 1:  density == 5:
Question: import pathlib file_path = 'vocab.txt' vocab = pathlib.Path(file_path).read_text().splitlines() print(len(vocab)) count = 0 with open(file_path, 'r', encoding='utf8') as f: for line in f: count += 1 print(count)  The two counts are 2122 and 2120. Shouldn't they be same?

Answer: So, looking at the documentation for str.splitlines, we see that the line delimiters for this method are a superset of "universal newlines":  This method splits on the following line boundaries. In particular, the boundaries are a superset of universal newlines.      Representation Description     \n Line Feed   \r Carriage Return   \r\n Carriage Return + Line Feed   \v or \x0b Line Tabulation   \f or \x0c Form Feed   \x1c File Separator   \x1d Group Separator   \x1e Record Separator   \x85 Next Line (C1 Control Code)   \u2028 Line Separator   \u2029 Paragraph Separator     A a line for a text-file will by default use the universal-newlines approach to interpret delimiters, from the docs:  When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If newline is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If newline has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
Question: I'm currently running the openstack executable and it generates python deprecation warnings. After some searching I did find this howto. The relevant part is here:  Use the PYTHONWARNINGS Environment Variable to Suppress Warnings in Python We can export a new environment variable in Python 2.7 and up. We can export PYTHONWARNINGS and set it to ignore to suppress the warnings raised in the Python program.  However, doing this: PYTHONWARNINGS="ignore" openstack image show image name -f value -c id  does nothing, deprecation warnings are still displayed. I've tried setting PYTHONWARNINGS to various things:  ignore "ignore" "all" "deprecated" "ignore::DeprecationWarning" "error::Warning,default::Warning:has_deprecated_syntax" "error::Warning"  but none of them seem to do anything. I was able to work around the issue by appending 2>/dev/null to the end but I would like to know why PYTHONWARNINGS doesn't seem to do anything.

Answer: PYTHONWARNINGS certainly does suppress python's warnings. Try running: PYTHONWARNINGS="ignore" python -c "import warnings; warnings.warn('hi')"  But in this case you are not calling python, but openstack, which is apparently not inheriting the same environment. Without looking at the source I can't say why. It may even be explicitly settings the warning level, which will override anything you do before hand. If you don't want to see errors, sending STDERR to /dev/null is the proper approach.