qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
29
22k
response_k
stringlengths
26
13.4k
__index_level_0__
int64
0
17.8k
33,715,198
I am new to python. I was trying to make a random # generator but nothing works except for the else statement. I cannot tell what the issue is. Please Help! ``` import random randomNum = random.randint(1, 10) answer = int(raw_input("Try to guess a random number between 1 and 10. ")) if (answer > randomNum) and (answe...
2015/11/15
[ "https://Stackoverflow.com/questions/33715198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5563197/" ]
Your first `if` statement logic is incorrect. `answer` cannot *at the same time* be both smaller and larger than `randomNum`, yet that is what your test asks for. You want to use `or` instead of `and` there, if the `answer` value is larger *or* smaller than `randomNum`: ``` if (answer > randomNum) or (answer < rando...
**I used this code for my random number generator and it works, I hope it helps** You can change the highest and lowest random number you want to generate (0,20) ``` import random maths_operator_list=['+','-','*'] maths_operator = random.choice(maths_operator_list) number_one = random.randint(0,20) number_two = rando...
1,244
68,737,471
I have a dict with some value in it. Now at the time of fetching value I want to check if value is `None` replace it with `""`. Is there any single statement way for this. ``` a = {'x' : 1, 'y': None} x = a.get('x', 3) # if x is not present init x with 3 z = a.get('z', 1) # Default value of z to 1 y = a.get('y', 1) # ...
2021/08/11
[ "https://Stackoverflow.com/questions/68737471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8595891/" ]
If the only falsy values you care about are `None` and `''`, you could do: ``` y = a.get('y', 1) or '' ```
``` y = a.get('y',"") or "" ```
1,245
55,231,300
I am using Django Rest Framework. I have an existing database (cannot make any changes to it). I have defined a serializer - ReceiptLog with no model, which should create entries in TestCaseCommandRun and TestCaseCommandRunResults when a post() request is made to ReceiptLog api endpoint. Receipt log doesn't exist in th...
2019/03/18
[ "https://Stackoverflow.com/questions/55231300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6885999/" ]
Your serializer's `create` method MUST return an instance of the object it represents. Also, you should not iterate inside the serializer to create instances, that should be done on the view: you iterate through the data, calling the serializer each iteration.
Updated the serializers.py file to include the below code ``` class ReceiptLogSerializerClass(serializers.Serializer): #Fields def create(self, validated_data): raw_data_list = [] many = isinstance(validated_data, list) if many: raw_data_list = validated_data else: ...
1,248
55,052,811
I've got this basic python3 server but can't figure out how to serve a directory. ``` class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): print(self.path) if self.path == '/up': self.send_response(200) self.end_headers() ...
2019/03/07
[ "https://Stackoverflow.com/questions/55052811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1240649/" ]
if you are using 3.7, you can simply serve up a directory where your html files, eg. index.html is still ``` python -m http.server 8080 --bind 127.0.0.1 --directory /path/to/dir ``` for the [docs](https://docs.python.org/3/library/http.server.html)
The simple way -------------- You want to *extend* the functionality of `SimpleHTTPRequestHandler`, so you **subclass** it! Check for your special condition(s), if none of them apply, call `super().do_GET()` and let it do the rest. Example: ``` class MyHandler(http.server.SimpleHTTPRequestHandler): def do_GET(se...
1,253
40,749,737
Currently I have an Arduino hooked up to a Raspberry Pi. The Arduino controls a water level detection circuit in service to an automatic pet water bowl. The program on the Arduino has several "serial.println()" statements to update the user on the status of the water bowl, filling or full. I have the Arduino connected ...
2016/11/22
[ "https://Stackoverflow.com/questions/40749737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086994/" ]
After the first iteration of your while loop, you close the file and never open it again for editing. When you try to append to a file that is closed, you get an error. You could instead move the open statement inside your loop like so: ``` while 1: line=ser.readline() messagefinal1 = message1 + line + message...
If you want to continuously update your webpage you have couple of options. I don't know how you serve your page but you might want to look at using Flask web framework for python and think about using templating language such as jinja2. A templating language will let you create variables in your html files that can be...
1,259
62,002,462
I'm trying to prune a pre-trained model: **MobileNetV2** and I got this error. Tried searching online and couldn't understand. I'm running on **Google Colab**. **These are my imports.** ``` import tensorflow as tf import tensorflow_model_optimization as tfmot import tensorflow_datasets as tfds from tensorflow import...
2020/05/25
[ "https://Stackoverflow.com/questions/62002462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12540447/" ]
I believe you are following `Pruning in Keras Example` and jumped into `Fine-tune pre-trained model with pruning` section without setting your prunable layers. You have to reinstantiate model and set layers you wish to set as `prunable`. Follow this guide for further information on how to set prunable layers. <https:/...
I faced the same issue with: * tensorflow version: `2.2.0` Just updating the version of tensorflow to `2.3.0` solved the issue, I think Tensorflow added support to this feature in 2.3.0.
1,260
42,010,684
I have a script written in python 2.7 that calls for a thread. But, whatever I do, the thread won't call the function. The function it calls: ``` def siren_loop(): while running: print 'dit is een print' ``` The way I tried to call it: ``` running = True t = threading.Thread(target=siren_loop) t.start...
2017/02/02
[ "https://Stackoverflow.com/questions/42010684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5837270/" ]
So, after trying various things for hours i and hours, I found a solution but still don't understand the problem. Apparently the program didnt like the many steps. I took one step away (the start siren method) but used the exact same code, and suddenly it worked. Stl no clue why that was the problem. If anybody knows,...
`running` is a local variable in your code. Add `global running` to `start_sirene()`
1,264
20,794,258
I have an appengine app that I want to use as a front end to some existing web services. How can I consume those WS from my app? I'm using python
2013/12/27
[ "https://Stackoverflow.com/questions/20794258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/251154/" ]
You are calling `string.replace` without assigning the output anywhere. The function does not modify the original string - it creates a new one - but you are not storing the returned value. Try this: ``` ... str = str.replace(/\r?\n|\r/g, " "); ... ``` --- However, if you actually want to remove *all* whitespace f...
you need to convert the data into **JSON** format. **JSON.parse(data)** you will remove all new line character and leave the data in **JSON** format.
1,266
55,010,607
I am new to machine learning and have spent some time learning python. I have started to learn TensorFlow and Keras for machine learning and I literally have no clue nor any understanding of the process to make the model. How do you know which models to use? which activation functions to use? The amount of layers and d...
2019/03/05
[ "https://Stackoverflow.com/questions/55010607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9919507/" ]
`*m` is the same as `m[0]`, i.e. the first element of the array pointed to by `m` which is the character `'s'`. By using the `%d` format specifier, you're printing the given argument as an integer. The ASCII value of `'s'` is 115, which is why you get that value. If you want to print the string, use the `%s` format ...
You have a few problems here, the first one is that you're trying to add three bytes to a char, a char is one byte. the second problem is that char \*m is a pointer to an address and is not a modifiable lvalue. The only time you should use pointers is when you are trying to point to data example: ``` char byte = "A"...
1,269
18,787,722
Is there are a way to change the user directory according to the username, something like ``` os.chdir('/home/arn/cake/') ``` But imagine that I don't know what's the username on that system. How do I find out what's the username, I know that python doesn't have variables so it's hard for me to get the username with...
2013/09/13
[ "https://Stackoverflow.com/questions/18787722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2641084/" ]
``` pwd.getpwnam(username).pw_dir ``` is the home directory of `username`. The user executing the program has username `os.getlogin()`. "I know that python doesn't have variables" -- that's nonsense. You obviously mean environment variables, which you can access using `os.getenv` or `os.environ`.
Maybe there is a better answer but you can always use command calls: ``` import commands user_dir = commands.getoutput("cd; pwd") ```
1,271
32,702,954
I am trying to rename multiple mp3 files I have in a folder. They start with something like "1 Hotel California - The Eagles" and so on. I would like it to be just "Hotel California - The Eagles". Also, there could be a "05 Hotel California - The Eagles" as well, which means removing the number from a different files w...
2015/09/21
[ "https://Stackoverflow.com/questions/32702954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3803648/" ]
You need to verify that the names being changed actually changed. If the name doesn't have digits or spaces in it, the `translate` will return the same string, and you'll try to rename `name` to `name`, which Windows rejects. Try: ``` for name in list: newname = name.translate(None, "124567890 ") if name != ne...
You just need to change directory to where \*.mp3 files are located and execute 2 lines of below with python: ``` import os,re for filename in os.listdir(): os.rename(filename, filname.strip(re.search("[0-9]{2}", filename).group(0))) ```
1,272
27,821,776
I want to set a value in editbox of android app using appium. And I am using python script to automate it. But I am always getting some errors. My python script is ``` import os import unittest import time from appium import webdriver from time import sleep from selenium import webdriver from selenium.webdriver.co...
2015/01/07
[ "https://Stackoverflow.com/questions/27821776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4429165/" ]
To type a value into a WebElement, use the Selenium WebDriver method `send_keys`: ``` element = self.driver.find_element_by_class_name('android.widget.EditText') element.send_keys('qwerty') ``` See the [Selenium Python Bindings documentation](http://selenium-python.readthedocs.org/en/latest/api.html?highlight=send_k...
It's as simple as the error: The type element is, has no set\_value(str) or setValue(str) method. Maybe you meant ``` .setText('qwerty')? ``` Because there is no setText method in a EditText widget: <http://developer.android.com/reference/android/widget/EditText.html>
1,282
44,307,988
I'm really new to python and trying to build a Hangman Game for practice. I'm using Python 3.6.1 The User can enter a letter and I want to tell him if there is any occurrence of that letter in the word and where it is. I get the total number of occurrences by using `occurrences = currentWord.count(guess)` I hav...
2017/06/01
[ "https://Stackoverflow.com/questions/44307988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952215/" ]
One way to do this is to find the indices using list comprehension: ``` currentWord = "hello" guess = "l" occurrences = currentWord.count(guess) indices = [i for i, a in enumerate(currentWord) if a == guess] print indices ``` output: ``` [2, 3] ```
I would maintain a second list of Booleans indicating which letters have been correctly matched. ``` >>> word_to_guess = "thicket" >>> matched = [False for c in word_to_guess] >>> for guess in "te": ... matched = [m or (guess == c) for m, c in zip(matched, word_to_guess)] ... print(list(zip(matched, word_to_guess)...
1,283
51,411,244
I have the following dictionary: ``` equipment_element = {'equipment_name', [0,0,0,0,0,0,0]} ``` I can't figure out what is wrong with this list? I'm trying to work backwards from this post [Python: TypeError: unhashable type: 'list'](https://stackoverflow.com/questions/13675296/python-typeerror-unhashable-type-lis...
2018/07/18
[ "https://Stackoverflow.com/questions/51411244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/84885/" ]
It's not a dictionary, it's a set.
maybe you were looking for this syntax ``` equipment_element = {'equipment_name': [0,0,0,0,0,0,0]} ``` or ``` equipment_element = dict('equipment_name' = [0,0,0,0,0,0,0]) ``` or ``` equipment_element = dict([('equipment_name', [0,0,0,0,0,0,0])]) ``` This syntax is for creating a set: ``` equipment_element = {...
1,285
69,782,728
I am trying to read an image URL from the internet and be able to get the image onto my machine via python, I used example used in this blog post <https://www.geeksforgeeks.org/how-to-open-an-image-from-the-url-in-pil/> which was <https://media.geeksforgeeks.org/wp-content/uploads/20210318103632/gfg-300x300.png>, howev...
2021/10/30
[ "https://Stackoverflow.com/questions/69782728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16956765/" ]
The server at `prntscr.com` is actively rejecting your request. There are many reasons why that could be. Some sites will check for the user agent of the caller to make see if that's the case. In my case, I used [httpie](https://httpie.io/docs) to test if it would allow me to download through a non-browser app. It work...
I had the same problem and it was due to an expired URL. I checked the response text and I was getting "URL signature expired" which is a message you wouldn't normally see unless you checked the response text. This means some URLs just expire, usually for security purposes. Try to get the URL again and update the URL ...
1,287
3,757,738
Ok say I have a string in python: ``` str="martin added 1 new photo to the <a href=''>martins photos</a> album." ``` *the string contains a lot more css/html in real world use* What is the fastest way to change the 1 (`'1 new photo'`) to say `'2 new photos'`. of course later the `'1'` may say `'12'`. Note, I don't ...
2010/09/21
[ "https://Stackoverflow.com/questions/3757738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258236/" ]
It sounds like this is what you want (although *why* is another question :^) ``` import re def add_photos(s,n): def helper(m): num = int(m.group(1)) + n plural = '' if num == 1 else 's' return 'added %d new photo%s' % (num,plural) return re.sub(r'added (\d+) new photo(s?)',helper,s) s...
since you're not parsing html, just use an regular expression ``` import re exp = "{0} added ([0-9]*) new photo".format(name) number = int(re.findall(exp, strng)[0]) ``` This assumes that you will always pass it a string with the number in it. If not, you'll get an `IndexError`. I would store the number and the fo...
1,288
70,884,314
I'm trying to match all of the items in one list (list1) with some items in another list (list2). ``` list1 = ['r','g','g',] list2 = ['r','g','r','g','g'] ``` For each successive object in list1, I want to find all indices where that pattern shows up in list2: Essentially, I'd hope the result to be something along ...
2022/01/27
[ "https://Stackoverflow.com/questions/70884314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18050991/" ]
Here's an attempt: ```py list1 = ['r','g','g'] list2 = ['r','g','r','g','g'] def inits(lst): for i in range(1, len(lst) + 1): yield lst[:i] def rolling_windows(lst, length): for i in range(len(lst) - length + 1): yield lst[i:i+length] for sublen, sublst in enumerate(inits(list1), start=1): ...
Pure python solution which is going to be pretty slow for big lists: ``` def ind_of_sub_list_in_list(sub: list, main: list) -> list[int]: indices: list[int] = [] for index_main in range(len(main) - len(sub) + 1): for index_sub in range(len(sub)): if main[index_main + index_sub] != sub[index...
1,290
1,454,941
I Have run into a few examples of managing threads with the threading module (using Python 2.6). What I am trying to understand is how is this example calling the "run" method and where. I do not see it anywhere. The ThreadUrl class gets instantiated in the main() function as "t" and this is where I would normally exp...
2009/09/21
[ "https://Stackoverflow.com/questions/1454941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/89528/" ]
The method run() is called behind the scene by "threading.Thread" (Google inheritance and polymorphism concepts of OOP). The invocation will be done just after t.start() has called. If you have an access to threading.py (find it in python folder). You will see a class name Thread. In that class, there is a method call...
`t.start()` creates a new thread in the OS and when this thread begins it will call the thread's `run()` method (or a different function if you provide a `target` in the `Thread` constructor)
1,296
55,508,028
I'm trying to use the ocr method from computer visio to extract all the text from a specific image. Nevertheless it doesn't return the info I know which is there, because when I analize the image directly in the available option in this page <https://azure.microsoft.com/es-es/services/cognitive-services/computer-vision...
2019/04/04
[ "https://Stackoverflow.com/questions/55508028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11309249/" ]
I'll try to describe my thought process so you can follow. This function fits the pattern of creating an output list (here a string) from an input seed (here a string) by repeated function application (here dropping some elements). Thus I choose an implementation with `Data.List.unfoldr`. ``` unfoldr :: (b -> Maybe (a...
To demonstrate the Haskell language some alternative solutions to the accepted answer. Using **list comprehension**: ``` printing :: Int -> String -> String printing j ls = [s | (i, s) <- zip [1 .. ] ls, mod i j == 0] ``` Using **recursion**: ``` printing' :: Int -> String -> String printing' n ls | null ls'...
1,299
7,550,823
I've caught myself using this in place of a traditional for loop: ``` _.each(_.range(count), function(i){ ... }); ``` The disadvantage being creating an unnecessary array of size count. Still, i prefer the semantics of, for example, *.each(*.range(10,0,-1), ...); when iterating backwards. Is there any way to do ...
2011/09/26
[ "https://Stackoverflow.com/questions/7550823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/374943/" ]
Considering the [source of underscore.js](http://documentcloud.github.com/underscore/underscore.js) says the following about `range`: > > Generate an integer Array containing an arithmetic progression > > > I doubt there is a way to do lazy iteration without modifying the source.
If you don't mind getting your hands dirty, dig into the sources of the older but stable and feature-complete [MochiKit](http://mochi.github.com/mochikit/)'s [Iter](http://mochi.github.com/mochikit/doc/html/MochiKit/Iter.html) module. It tries to create something along the lines of Python's [itertools](http://docs.pyth...
1,300
23,175,165
In python, I am trying to check if a given list of values is currently sorted in increasing order and if there are adjacent duplicates in the list. If there are, the code should return True. I am not sure why this code does not work. Any ideas? Thanks in advance!! ``` def main(): values = [1, 4, 9, 16, 25] p...
2014/04/19
[ "https://Stackoverflow.com/questions/23175165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3495872/" ]
Your `increasingorder` function will almost certainly not work, because Python uses references, and the `sort` function modifies a list in-place and returns `None`. That means that after your call `a = hlist.sort()`, both `hlist` will be sorted and `a` will be `None`. so they will not compare equal. You probably meant...
Try creating a True False function for each value check operation you want done taking the list as a parameter. then call each function like "if 1 and 2 print 3" format. That may make thinking through the flow a little easier. Is this kind of what you were wanting? ``` def isincreasing(values): if values==sorted(...
1,302
20,529,457
Please excuse this naive question of mine. I am trying to monitor memory usage of my python code, and have come across the promising [`memory_profiler`](https://pypi.python.org/pypi/memory_profiler) package. I have a question about interpreting the output generated by @profile decorator. Here is a sample output that ...
2013/12/11
[ "https://Stackoverflow.com/questions/20529457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1146372/" ]
According to [the docs](https://pypi.python.org/pypi/memory_profiler): > > The first column represents the line number of the code that has been profiled, the second column (Mem usage) the memory usage of the Python interpreter after that line has been executed. The third column (Increment) represents the difference ...
The difference in memory between lines is given in the second column or you could write a small script to process the output.
1,303
67,395,047
I have written several python scripts that will backtest trading strategies. I am attempting to deploy these through docker compose. The feeder container copies test files to a working directory where the backtester containers will pick them up and process them. The processed test files are then sent to a "completed w...
2021/05/05
[ "https://Stackoverflow.com/questions/67395047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15838493/" ]
It's been three weeks with no responses, but I just wanted to update with what I've found. In all cases where I've left "docker-compose up" running it eventually started. At times it took 30 minutes, but it started every time.
I faced the same problem and fix it with this tip: > > resolved It turns out if I run my docker command with "python3 -u" it will force python to run unbuffered. It was a buffering issue. > > > source: <https://www.reddit.com/r/docker/comments/gk262t/comment/fqos8j8/?utm_source=share&utm_medium=web2x&context=3>
1,304
15,152,174
I am using python version 3. For homework, I am trying to allow five digits of input from the user, then find the average of those digits. I have figured that part out (spent an hour learning about the map function, very cool). The second part of the problem is to compare each individual element of the list to the av...
2013/03/01
[ "https://Stackoverflow.com/questions/15152174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2121886/" ]
you can add your custom class with your own css property like below ``` $this->addElement(new Zend_Form_Element_Button( 'send', array( 'label' => 'registrieren', 'class' => 'button-red', 'type' => 'submit', 'escape' => f...
Yes just apply the appropriate CSS to the 'div', 'tag' or 'class' as required. [22 CSS Button Styling Tutorials and Techniques](http://speckyboy.com/2009/05/27/22-css-button-styling-tutorials-and-techniques/) may help.
1,305
2,683,810
I'd ideally like a vim answer to this: I want to change ``` [*, 1, *, *] to [*, 2, *, *] ``` Here the stars refer to individual characters in the substring, which I would like to keep unchanged. For example ``` [0, 1, 0, 1] to [0, 2, 0, 1] [1, 1, 1, 1] to [1, 2, 1, 1] ``` If people know how to do this in perl or...
2010/04/21
[ "https://Stackoverflow.com/questions/2683810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194675/" ]
The following should do what you want: ``` :%s/\(\[[^,]*, *\)\(\d\)\([^]]*\]\)/\=submatch(1) . (submatch(2)+1) . submatch(3)/ ``` In Vim, that is.
If those are strings in Python ``` >>> a = "[0, 1, 0, 1]" >>> b = a[:4] + '2' + a[5:] >>> b '[0, 2, 0, 1]' ``` Lists are a little more trivial: ``` >>> c = [0, 1, 0, 1] >>> c[1] = 2 >>> c [0, 2, 0, 1] >>> ```
1,306
30,083,603
Alright here's a question that's eating me from inside so any help is appreciated. I have a web service that returns a list of items. The number of items returned is governed by two variables 'page' and 'per\_page'. So a URL like ``` abc.com?page=10&per_page=100 ``` Will show the 10th page with 100 items in it. I ...
2015/05/06
[ "https://Stackoverflow.com/questions/30083603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4484709/" ]
Is there a compelling reason to not over-request? `abc.com?page=2&per_page=1024` Just always set `page=2` and `per_page` = number of items cached. The only weird case is when the number of added elements is greater than the number of items cached, in which case you have to `abc.com?page=1&per_page=99999`
Here's the code with a small bug-fix to give the most optimal page size (the suggested code wouldn't return a page size that exactly divides the total count). ``` def items_per_page(total_item_count,new_item_count): for i in itertools.count(new_item_count): if total_items % i>= new_item_count or total_it...
1,313
44,967,366
Working in python with ESRI's arcpy, I'm trying to sum values across multiple fields with an arcpy updateCursor . I'm trying to convert the None items to an 0. However, I can't figure out a way to convert the None items. I'm open to anything. ``` with arcpy.da.UpdateCursor(feature_class, score_fields) as cursor: ...
2017/07/07
[ "https://Stackoverflow.com/questions/44967366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8269863/" ]
You should update `row` by assigning the result of the list comprehension to `row`: ``` for row in cursor: row = [0 if x is None else x+4 for x in row] ``` Also, note that since there is only one `None` object, better to test with `is` than use `==`; more Pythonic, more performant.
You can use an if statement to filter the `None` values in your list: ``` sum(row[i] for i in range(len(score_fields)) if row[i] is not None) ```
1,315
7,720,435
What is the best way to implement a tree structure (generic - not binary) in python? My intuition would have the following skeleton: ``` class TNode(self, data): #enter things for each individual node class TStructure(self): #enter code for implementing nodes that reference each other. ```
2011/10/11
[ "https://Stackoverflow.com/questions/7720435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/382906/" ]
Any function which is going to be inlined must have its full source in the .di file. Any function which is going to be used in CTFE must not only have its full source in the .di file, but the full source of every function that it uses - directly or indirectly - must be available to the compiler. Also, because of how te...
> > Hardly a paragon of optimization. > > > No, that **is** an optimization. The compiler will leave the implementation in the interface file if the implementation is small enough that it can later be inlined.
1,316
69,255,736
`TypeError: unsupported operand type(s) for /: 'str' and 'float'` I'm making a football game, and I get this whenever I try to run the following code to determine how far a play will go. `playdistance = round(random.uniform(float(rbs.get(possession)[-2:]/float(30.0))-2.5,float(rbs.get(possession)[-2:]/float(30.0))+5....
2021/09/20
[ "https://Stackoverflow.com/questions/69255736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16957998/" ]
You can't combine strings and numbers like that in Python. `rbs.get(possession)[-2:]` gives you a string, e.g. `'99'`, and `float(30.0)` gives you a number. The division of strings by numbers is not defined. You must convert the '99' to a number first before you can divide it by anything. Technically speaking, you on...
When I indent your code to make it more readable, the problem becomes evident ``` playdistance = round( random.uniform( float( rbs.get(possession)[-2:] / float(30.0) # error 1 ) - 2.5, float( rbs.get(possession)[-2:] / float(30.0) # error 2 ) + 5.5 ) ) ``` `r...
1,317
12,948,935
``` $ ps aux | grep file1.py xyz 6103 0.0 0.1 33476 6480 pts/1 S+ 12:00 0:00 python file1.py xyz 6188 0.0 0.1 33476 6472 pts/2 S+ 12:05 0:00 python file1.py xyz 7294 0.0 0.0 8956 872 pts/4 S+ 12:49 0:00 grep --color=auto file1.py ``` process 6103 has started at 12:00 and af...
2012/10/18
[ "https://Stackoverflow.com/questions/12948935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1051068/" ]
What about something like this, if you are not worried of the **os.popen()** ``` #!/usr/bin/python import os PROCNAME = "file1.py" pids = [] for proc_data in os.popen('/bin/ps -eo pid,comm,args'): bits = proc_data.strip().split() (pid, comm ) = bits[0:2] args = " ".join( bits[3:] ) if args == PROCNAME:...
please read up on `pidof`: ``` man pidof ```
1,320
58,461,785
While studying data types in Python, I encountered a data type range and used a variable to define it. However using type function to know about this still tells that it's a list data types. Am I missing something here? Please guide. Thank you so much. ``` x = range(3) print(type(x)) ``` Output is as shown below: ...
2019/10/19
[ "https://Stackoverflow.com/questions/58461785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8808220/" ]
It seems you are mixing up Python 3 and 2. These are two major versions of Python. Python 3000 introduced many intentionally backwards incompatible changes including in the workings of the range function. In Python 2, the range function immediately expanded out to a list `list_range = list(range(3))` In Python 3 it...
With Python2, range returned the list. If you try to run your code with python3, it returns the 'range' type as a output of your code.
1,321
2,913,626
I need to parse a string `'Open URN: 100000 LA: '` and get 100000 from it. on python regexp `(?<=Open URN: )[0-9]+(?= LA:)` works fine but in php it gives following error: ``` preg_match(): Unknown modifier '[' ``` I need it working php, so please help me to solve this problem and tell about difference in python and...
2010/05/26
[ "https://Stackoverflow.com/questions/2913626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/350981/" ]
You have to use [delimiters](http://www.php.net/manual/en/regexp.reference.delimiters.php) when you are using the [*Perl Compatible Regular Expressions* (PCRE) functions](http://www.php.net/manual/en/book.pcre.php) in PHP (to which [`preg_match()`](http://php.net/manual/en/function.preg-match.php) belongs). From the [...
Except of mentioned differences I found one more. re.match(r"\s", "a b") in python with preg\_match("/\s/", "a b"), the first doesn't return matches in python while the second will find space symbol. I didn't find why in official docs, it's hard to understand but it's a fact.
1,322
22,286,332
I am parsing log files in size of 1 to 10GB using python3.2, need to search for line with specific regex (some kind of timestamp), and I want to find the last occurance. I have tried to use: ``` for line in reversed(list(open("filename"))) ``` which resulted in very bad performance (in the good cases) and MemoryErr...
2014/03/09
[ "https://Stackoverflow.com/questions/22286332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3399166/" ]
Looks like you have mistake in code: ``` echo $row['PersonnelD']; ``` shouldn't it be following? ``` echo $row['PersonnelID']; ```
check the mysql\_fetch\_assoc() function may be its parameter is empty so it can't enter the while loop
1,323
38,092,236
(windows 7, python 2.7.3) Here is my code: ``` from Tkinter import * root = Tk() root.geometry('400x400') Frame(root, width=20, height=20, bg='red').pack(expand=NO, fill=None, side=LEFT) Label(root, width=20, height=20, bg='black').pack(expand=NO, fill=None, side=LEFT) root.mainloop() ``` And the result is like th...
2016/06/29
[ "https://Stackoverflow.com/questions/38092236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6032273/" ]
**Short answer:** 20 is the same as 20, but 20 meters is not the same as 20 kilometers. **Long answer:** The result you got is not as weird as you may think because the `width` and `height` options of `Tkinter.Frame()` are measured in terms of **pixels** whereas in `Tkinter.Label()`: * `width`: defines the width of...
As I know Label is used for text. Label() definition and Frame() might work differently for width and height parameters, correct me if am wrong. example: change width and height inside Label() to 1. you will see space for one character filled with black color in tk window. like `Label(root, width=1, height=1, bg='...
1,328
59,028,392
I have my docker containers up and running. There is one container running some python code and I found that it is causing some bug. I want to add some lines of code (mainly more logs) to a python script within that particular container. I want to just go into the container by `docker exec -ti container_name bash` an...
2019/11/25
[ "https://Stackoverflow.com/questions/59028392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3703783/" ]
A couple of facts about docker containers: 1. Docker container lives as long as the process it runs lives usually. 2. Docker container is immutable, so whatever changes you do in filesystem of the container itself won't survive the restart of container (I'm not talking about volumes, its more advanced stuff) Based on...
Answering because there's some misinformation in other answers here. The correct answer is in the comment from [MyTwoCents](https://stackoverflow.com/questions/59028392/do-docker-containers-pick-up-code-changes-on-the-fly#comment104300981_59028392): > > It will behave same way as it would when you do it on your syste...
1,329
17,771,131
While following a tutorial for python, I got to know that we can use *print* for a variable name, and it works fine. But after assigning the print variable, how do we get back the original print function? ``` >>> print("Hello World!!") Hello World!!! >>> print = 5 >>> print("Hi") ``` Now, the last call gives the err...
2013/07/21
[ "https://Stackoverflow.com/questions/17771131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1936532/" ]
``` >>> print = 5 >>> print = __builtins__.print >>> print("hello") hello ```
You can actually delete the variable so the built-in function will work again: ``` >>> print = 5 >>> print('cabbage') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable >>> del print >>> print('cabbage') cabbage ```
1,330
66,730,834
I have created a conda environment and activated it already. Then inside the `use_cases/` directory I execute: `pip install -e use_case_b` (<https://github.com/geoHeil/dagster-demo/tree/master/use_cases>): ``` ... ... Installing collected packages: use-case-b Attempting uninstall: use-case-b Found existing inst...
2021/03/21
[ "https://Stackoverflow.com/questions/66730834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2587904/" ]
When you get an error, please post it along with your question. When you are getting an error, it means that something is wrong with your code,and most likely not the flutter engine. Both are important for debugging, the error+your code. Try changing this ``` QuerySnapshot _getPost = await _firestore .collection(...
For people facing similar issues, let me tell what I found in my code: ***The error says that the children is null, not empty !*** So if you are getting the children for the parent widget like Row or Column from a separate method, ***just check if you are returning the constructed child widget from the method***. ``...
1,332
55,355,504
I have a txt file that contains "blocks of consecutive lines", each block representing one observation whereas the different lines within each block represent the value of one variable of the corresponding observation. I worked my way to here using python and I would like to read the .txt file into Stata. Therefore, I...
2019/03/26
[ "https://Stackoverflow.com/questions/55355504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11259841/" ]
Try ``` with open('my_file.txt','r') as f: # lines should hold the data with no new lines lines = [l.strip() for l in f.readlines()] ```
you can extend the balderman's answer: ``` with open('filename.txt','r') as f: lines = [l.strip() for l in f.readlines()] ``` This part will create the list of lines of whole file. To create a single line for variables in each block you can just use dictionary to store variables in each block. Example: ``` bloc...
1,333
45,715,062
I try to create a domain filter what should look like this: ``` (Followup date < today) AND (customer = TRUE OR user_id = user.id) ``` I did it like following: ``` [('follow_up_date', '&lt;=', datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')),['|', ('customer', '=', 'False'),('user_id', '=', 'user.id')]] ``` ...
2017/08/16
[ "https://Stackoverflow.com/questions/45715062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7126858/" ]
Odoo uses the [polish notation](https://en.wikipedia.org/wiki/Polish_notation). If you'd like to use the logical expression `(A) AND (B OR C)` as a domain, that means you will have to use: `AND A OR B C`. If you'd like more information about polish notation please check the link. This means that, if I understand the q...
Try without brackets in the second expression: ``` [('follow_up_date', '&lt;=', datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')),'|', ('customer', '=', 'False'),('user_id', '=', 'user.id')'] ``` I hope this help you.
1,334
66,029,297
I parsed a function from python which converts for ex. "5m" to 300 seconds (integer). My question is about the regex expression I did, because I know it's slow compared to anything else. What is the best way to get the integer part of the `timeframe` and the string part as well into a separate string? Basically, what I...
2021/02/03
[ "https://Stackoverflow.com/questions/66029297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13677853/" ]
there's no need to use [regexes](https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/) for this. just translate *what the existing python code does*: accessing substrings of your input. ``` var amount = int.Parse(timeframe.Substring(0, timeframe.Length - 1)); var unit = timeframe.Substr...
Alternatively, if you have a proper TimeSpan, you can cast your string to `TimeSpan` and then use the `TotalSeconds` prop. That will also get rid of all the if-else ifs that you have. ``` if (TimeSpan.TryParse(timeframe, out var timeSpan)) { Console.WriteLine(timeSpan.TotalSeconds); } ``` \*Edit: As is, you assu...
1,335
8,296,617
i hope the title itself was quite clear , i am solving 2D lid-driven cavity(square domain) problem using fractional step method , finite difference formulation (Navier-Stokes primitive variable form) , i have got u and v components of velocity over the entire domain , without manually calculating streamlines , is there...
2011/11/28
[ "https://Stackoverflow.com/questions/8296617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616809/" ]
Have a look at [Tom Flannaghan's `streamplot` function](http://www.atm.damtp.cam.ac.uk/people/tjf37/streamplot.py). The [relevant thread on the user's list is here](http://old.nabble.com/Any-update-on-streamline-plot-td30902670.html), and there's also another [similar code snippet by Ray Speth](http://web.mit.edu/speth...
Have a look at `matplotlib`'s `quiver`: <http://matplotlib.sourceforge.net/examples/pylab_examples/quiver_demo.html>
1,336
71,825,406
I try to search the answer in stackoverflow and try to find something in the github [issues](https://github.com/googleapis/python-logging/issues) but nothing I found. Can anyone give me some tip to solve the problem? I get the following error when trying to install Google Cloud Logging by pip with docker: ``` test_we...
2022/04/11
[ "https://Stackoverflow.com/questions/71825406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11296376/" ]
Upgrade your protobuf to 3.20.1. Unsure why its happening. Here's the git issue: <https://github.com/googleapis/python-iam/issues/185>
I had the same error while using `google-cloud-secret-manager` and `poetry`. Removing unused `gcloud` dependency as well as `google-cloud-secret-manager` and reinstalling `google-cloud-secret-manager` solved it. ``` poetry remove gcloud poetry remove google-cloud-secret-manager poetry add google-cloud-secret-manager ...
1,338
8,618,984
The server only allows access to the videos if the useragent is QT, how to add it to this script ? ``` #!/usr/bin/env python from os import pardir, rename, listdir, getcwd from os.path import join from urllib import urlopen, urlretrieve, FancyURLopener class MyOpener(FancyURLopener): version = 'QuickTime/7.6.2 (ve...
2011/12/23
[ "https://Stackoverflow.com/questions/8618984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/891489/" ]
I found the solution. Practically I needed to set the Layout\_width of each container with the weight property to 0px.
From what I can tell, it seems your weightSum should be 12, not 10. First LinearLayout has weight=2, the second weight=8 and the third weight=2. It might solve your problem!
1,339
29,985,453
I am getting this strange to me error when installing Keras on an Ubuntu server: ``` Cythonizing /tmp/easy_install-qQggXs/h5py-2.5.0/h5py/utils.pyx In file included from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1804:0, from /usr/local/lib/python2.7/dist-packages/n...
2015/05/01
[ "https://Stackoverflow.com/questions/29985453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4262897/" ]
you can use sparql query to Dbpedia to get result for you particular resource, which here is [Vienna](http://dbpedia.org/page/Vienna). To get all property and their value of resource Vienna use can use ``` select ?property ?value where { <http://dbpedia.org/resource/Vienna> ?property ?value } ``` [Check here](htt...
> > *But what I want is something … to get all items where any property fits "Vienna"[.]* > > > In SPARQL this is very easy. E.g., on [DBpedia's SPARQL endpoint](http://dbpedia.org/sparql/): ``` select ?resource where { ?resource ?property dbpedia:Vienna } ``` [SPARQL results (limited to 100)](http://dbpedia...
1,341
31,466,769
Similar to this question [How to add an empty column to a dataframe?](https://stackoverflow.com/questions/16327055/how-to-add-an-empty-column-to-a-dataframe), I am interested in knowing the best way to add a column of empty lists to a DataFrame. What I am trying to do is basically initialize a column and as I iterate ...
2015/07/17
[ "https://Stackoverflow.com/questions/31466769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403872/" ]
One more way is to use [`np.empty`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html): ``` df['empty_list'] = np.empty((len(df), 0)).tolist() ``` --- You could also knock off `.index` in your "Method 1" when trying to find `len` of `df`. ``` df['empty_list'] = [[] for _ in range(len(df))] ``` ...
EDIT: the commenters caught the bug in my answer ``` s = pd.Series([[]] * 3) s.iloc[0].append(1) #adding an item only to the first element >s # unintended consequences: 0 [1] 1 [1] 2 [1] ``` So, the correct solution is ``` s = pd.Series([[] for i in range(3)]) s.iloc[0].append(1) >s 0 [1] 1 [] 2 ...
1,345
27,138,716
I am new to Jquery and Javascript. I've only done the intros for codeacademy and I have what I remembered from my python days. I saw this tutorial: <http://www.codecademy.com/courses/a-simple-counter/0/1> I completed the tutorial and thought: "I should learn how to do this with Jquery". So I've been trying to use ...
2014/11/25
[ "https://Stackoverflow.com/questions/27138716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4293758/" ]
If you want to read the whole file with the spaces removed, `f.read()` is on the right track—unlike your other attempts, that gives you the whole file as a single string, not one line at a time. But you still need to replace the spaces. Which you need to do explicitly. For example: ``` f.read().replace(' ', '') ``` ...
This line: ``` f = open("clues.txt") ``` will open the file - that is, it returns a filehandle that you can read from This line: ``` open("clues.txt").read().replace(" ", "") ``` will open the file and return its contents, with all spaces removed.
1,348
65,682,339
This is not working, Cant figure it out... i want it to print either error sentence or break.. I wanted to do it in a try/except, but that was not so good. And I'm new to python :-) ```py while True: unitFrom = input("Enter unit of temperature, either Fahrenheit, Kelvin or Celsius:") list = ["Fa...
2021/01/12
[ "https://Stackoverflow.com/questions/65682339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14990031/" ]
1. Never use the built-in keywords to define new variables. 2. Take the list outside the loop to avoid initializing it on each iteration. 3. You need to have the list in lowercase since you're checking the lower-cased input in the list: Hence: ``` x_units = ["fahrenheit" , "celsius" , "kelvin"] # or x_units = [x.lowe...
Do you want to print break or want to execute `break` ? and `list = ["Fahrenheit" , "Celsius" , "Kelvin"]` is created new everytime execute it before `while True:` and use something other than list as array name as `list` is a keyword ``` answer_list = ["Fahrenheit" , "Celsius" , "Kelvin"] while True: unitFrom...
1,351
68,179,964
I am trying to check if all the objects in a specified bucket are public or not, using the boto3 module in python. I have tried using the `client.get_object()` and `client.list_objects()` methods, but I am unable to figure out what exactly I should search for as I am new to boto3 and AWS in general. Also, since my org...
2021/06/29
[ "https://Stackoverflow.com/questions/68179964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16081945/" ]
I think the best way to test if an object is public or not is to make an anonymous request to that object URL. ```py import boto3 import botocore import requests bucket_name = 'example-bucket' object_key = 'example-key' config = botocore.client.Config(signature_version=botocore.UNSIGNED) object_url = boto3.client('s...
may be a combination of these to tell the full story for each object ``` client = boto3.client('s3') bucket = 'my-bucket' key = 'my-key' client.get_object_acl(Bucket=bucket, Key=key) client.get_bucket_acl(Bucket=bucket) client.get_bucket_policy(Bucket=bucket) ```
1,355
70,222,086
Well, I would like to get a calendars data from outlook. My purpose is making small service in Python which can read & write in someones calendar in outlook account of course I suppose that I was provided access to it in Azure Active Directory. Before writing this, I read a lot of guides on how to do this. Also I tried...
2021/12/04
[ "https://Stackoverflow.com/questions/70222086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12961561/" ]
let's best go through the error messages: 1. `Error Message: The tenant for tenant guid 'xxxx' does not exist.` I am assuming that this is an Office 365 Business. Also that you are logged into Azure with your company address. Then you should see under: "App registrations>test feature> Overview" you should find the va...
For me, joining [Microsoft Developer Program](https://developer.microsoft.com/en-us/microsoft-365/dev-program) and using its azure directory fixed issues.
1,357
45,402,049
I've been working on a website for the past year and used python and flask to built it. Recently I encountered a lot of errors and problems and decided to start a new project (pyCharm). I figured I could copy pieces of code into the new project until I encountered a problem and then I'll know what the problem is. I cr...
2017/07/30
[ "https://Stackoverflow.com/questions/45402049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8380994/" ]
Move the `if` outside the `echo` and assign it to a variable, then use the variable in the `echo`. I'd also use ternary operator for this. It also looks like you are comparing the full array, not the index you want to be comparing. Try: ``` while ($row = $result->fetch_assoc()) { $style = $row['move'] > 0 ? ' ...
Untested, but I think this will work: ``` while ($row = $result->fetch_assoc()) { echo "<tr><td style='text-align:left'>".$row["rank"]."</td><td style='text-align:left'>".$row["team_name"]."</td><td>".$row["record"]."</td><td>".$row["average"]."</td><td ".($row["move"] > 0 ? 'style="color:green;"' : '').">".$row["...
1,358
53,178,013
I have a project for which I'd now like to use pipenv. I want to symlink this from my main bin directory, so I can run it from another directory (where it interacts with local files) but nevertheless run it in the pipenv with the appropriately installed files. Can I do something like ``` pipenv run python /PATH/TO/M...
2018/11/06
[ "https://Stackoverflow.com/questions/53178013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8482/" ]
Not sure if this was relevant with the version of pipenv you used in 2018, but as of current versions you can use the [PIPENV\_PIPFILE](https://pipenv.kennethreitz.org/en/latest/advanced/#pipenv.environments.PIPENV_PIPFILE) environment variable. You will end up with a wrapper shell script that looks something like: ``...
pipenv is a wrapper for virtualenv which keeps the virtualenv-files in some folder in your home directory. I found them in `/home/MYUSERNAME/.local/share/virtualenvs`. So i wrote a `small_script.sh`: ``` #!/bin/bash source /home/MYUSERNAME/.local/share/virtualenvs/MYCODE-9as8Da87/bin/activate python /PATH/TO/MY/CODE...
1,361
1,976,622
I'm using python-dbus and cherrypy to monitor USB devices and provide a REST service that will maintain status on the inserted USB devices. I have written and debugged these services independently, and they work as expected. Now, I'm merging the services into a single application. My problem is: I cannot seem to get b...
2009/12/29
[ "https://Stackoverflow.com/questions/1976622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179157/" ]
You should be able to use .NET's Reflection to analyze your application AppDomain(s) and dump a list of loaded assemblies and locations. ``` var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in loadedAssemblies) { Console.WriteLine(assembly.GetName().Name); Console.WriteLine...
Check out [`AppDomain.GetAssemblies`](http://msdn.microsoft.com/en-us/library/system.appdomain.getassemblies.aspx) ``` For Each Ass As Reflection.Assembly In CurrentDomain.GetAssemblies() Console.WriteLine(Ass.ToString()) Next ```
1,362
1,777,862
I am trying to rewrite the following program in C instead of C# (which is less portable). It is obvious that "int system ( const char \* command )" will be necessary to complete the program. Starting it with "int main ( int argc, char \* argv[] )" will allow getting the command-line arguments, but there is still a prob...
2009/11/22
[ "https://Stackoverflow.com/questions/1777862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/216356/" ]
Windows is all messed up. Every program has its own rules.
``` screensaver.scr "spaced argument" nonspaced_argument argc = 2 argv[0] = "screensaver.scr" argv[1] = "spaced argument" argv[2] = "nonspaced_argument" ``` Sorry my English :).
1,368
17,161,552
I have read that while writing functions it is good practice to copy the arguments into other variables because it is not always clear whether the variable is immutable or not. [I don't remember where so don't ask]. I have been writing functions according to this. As I understand creating a new variable takes some ove...
2013/06/18
[ "https://Stackoverflow.com/questions/17161552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2235567/" ]
I think it's best to keep it simple in questions like these. The second link in your question is a really good explanation; in summary: Methods take parameters which, as pointed out in that explanation, are passed "by value". The parameters in functions take the value of variables passed in. For primitive types like...
If you are **rebinding** the name then mutability of the object it contains is irrelevant. Only if you perform **mutating** operations must you create a copy. (And if you read between the lines, that indirectly says "don't mutate objects passed to you".)
1,370
73,419,189
I am learning continue statement in python while loop. If I run a following code, the output shows from 2 instead of 1. ``` a = 1 while a <= 8: a += 1 if a == 5: continue print(a) ```
2022/08/19
[ "https://Stackoverflow.com/questions/73419189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507620/" ]
You can use the HPA (Horizontal Pod Autoscaler). Here is what the typical yaml configuration looks like. ``` apiVersion: autoscaling/v1 kind: HorizontalPodAutoscaler metadata: name: hpa_name spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: deployment_name_to_autoscale minReplicas: 1 ...
In GKE, you can achieve this with [Horizontal Pod Autoscaler (HPA)](https://cloud.google.com/kubernetes-engine/docs/concepts/horizontalpodautoscaler). The autoscaling event can be configured to be triggered by system (eg. cpu or memory) or custom metrics (eg. pubsub queued messages count). You can also set the minimum ...
1,373
55,599,993
I want to write a program in Python which takes a C program as input, executes it against the test cases which are also as inputs and print the output for each test case. I am using Windows I tried with subprocess.run but it is not accepting inputs at runtime (i.e dynamically) ```py from subprocess import * p1=run("r...
2019/04/09
[ "https://Stackoverflow.com/questions/55599993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11315221/" ]
I agree with @juanpa.arrivillaga's suggestion. You can use `subprocess.Popen` and `communicate()` for that: ``` import subprocess import sys p = subprocess.Popen('rah.exe', stdout=sys.stdout, stderr=sys.stderr) p.communicate() ``` **Update:** The script above won't work on IDLE because IDLE changes the IO objects `s...
> > I tried with subprocess.run but it is not accepting inputs at runtime (i.e dynamically) > > > If you don't do anything, the subprocess will simply inherit their parent's stdin. That aside, because you're intercepting the output of the subprocess and printing it afterwards you won't get the interleaving you're...
1,378
54,371,847
I'm trying to install tensorflow but python 3.7 does not support that, so I want to get python 3.6 instead without using anaconda. So any suggestion please ?
2019/01/25
[ "https://Stackoverflow.com/questions/54371847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10968495/" ]
I have done this multiple times. My first tip is use [virtual environments](https://realpython.com/python-virtual-environments-a-primer/). That way you can use python 3.6 for what ever project requires that version of python, and python 3.7 for other projects that need that version. However on windows these are the b...
Consider using [pyenv-win](https://github.com/pyenv-win/pyenv-win) in order to manage your global and (per-project) local Python versions. However, it only works with the Windows Subsystem for Linux.
1,379
66,975,127
I'm trying to install a simple Django package in a Docker container. Here is my dockerfile ``` FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY Pipfile Pipfile.lock /app/ RUN pip install pipenv && pipenv install --system COPY . /app/ ``` And here is my docker-compose: ``` ve...
2021/04/06
[ "https://Stackoverflow.com/questions/66975127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3678257/" ]
you can use [present](https://laravel.com/docs/8.x/validation#rule-present) validation The field under validation must be present in the input data but can be empty. ``` 'topics' => 'present|array' ```
Validating array based form input fields doesn't have to be a pain. You may use "dot notation" to validate attributes within an array. For example, if the incoming HTTP request contains a `photos[profile]` field, you may validate it like so: ``` use Illuminate\Support\Facades\Validator; $validator = Validator::make($...
1,382
47,370,718
Suppose we have * an n-dimensional numpy.array A * a numpy.array B with dtype=int and shape of (n, m) How do I index A by B so that the result is an array of shape (m,), with values taken from the positions indicated by the columns of B? For example, consider this code that does what I want when B is a python list: ...
2017/11/18
[ "https://Stackoverflow.com/questions/47370718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073784/" ]
One alternative would be converting to linear indices and then index with `np.take` or index into its flattened version - ``` np.take(a,np.ravel_multi_index(b, a.shape)) a.flat[np.ravel_multi_index(b, a.shape)] ``` **Custom `np.ravel_multi_index` for performance boost** We could implement a custom version to simula...
Another alternative that fits your need involves the use of [`np.ravel`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html) ``` >>> a[map(np.ravel, b)] array([ 1, 10, 20]) ``` However not fully [`numpy`](http://www.numpy.org/)-based. --- ***Performance-concerns.*** *Updated following the commen...
1,383
5,373,195
When I tried to parse a csv which was exported by MS SQL 2005 express edition's query, the string python gives me is totally unexpected. For example if the line in the csv file is :" aaa,bbb,ccc,dddd", then when python parsed it as string, it becomes :" a a a a , b b b , c c c, d d d d" something like that.....What hap...
2011/03/21
[ "https://Stackoverflow.com/questions/5373195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/612678/" ]
Sounds to me like the output of the MS SQL 2005 query is a unicode file. The python [csv module](http://docs.python.org/library/csv.html) cannot handle unicode files, but there is some [sample code](http://docs.python.org/library/csv.html#csv-examples) in the documentation for the csv module describing how to work arou...
Try to open the file in notepad and use the replace all function to replace `' '` with `''`
1,385
47,544,183
I'm trying to use multiprocessing, but I keep getting this error: ``` AttributeError: Can't get attribute 'processLine' on <module '__main__' ``` (The processLine function returns word, so I guess the problem is here, but I don't know how to get around it) ``` import multiprocessing as mp pool = mp.Pool(4) jobs ...
2017/11/29
[ "https://Stackoverflow.com/questions/47544183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8138305/" ]
The `multiprocessing` module needs to be able to import your module safely. Any code not inside a function or class should be protected by the standard Python import guard: ``` if __name__ == '__main__': ...code goes here... ``` But there are other problems with your code. For example, you've got: ``` word = jo...
I worked around the AttributeError issue by using VS Code in administrator mode to run it instead of Anaconda Spyder.
1,388
10,688,389
I have a ever growing csv file that looks like: ``` 143100, 2012-05-21 09:52:54.165852 125820, 2012-05-21 09:53:54.666780 109260, 2012-05-21 09:54:55.144712 116340, 2012-05-21 09:55:55.642197 125640, 2012-05-21 09:56:56.094999 122820, 2012-05-21 09:57:56.546567 124770, 2012-05-21 09:58:57.046050 103830, 2012-05-21 09:...
2012/05/21
[ "https://Stackoverflow.com/questions/10688389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672387/" ]
The Python idiom would be to use a generator expression to filter the lines: ``` sys.stdout.writelines(line for line in sys.stdin if not line.startswith('-')) ``` Or in a processing context: ``` filtered = (line for line in sys.stdin if not line.startswith('-')) for line in filtered: # ... ```
Instead of rewriting the files, I would filter the data on read, i.e. just before plotting.
1,389
16,881,955
I am trying to learn python and for that purpose i made a simple addition program using python 2.7.3 ``` print("Enter two Numbers\n") a = int(raw_input('A=')) b = int(raw_input('B=')) c=a+b print ('C= %s' %c) ``` i saved the file as *add.py* and when i double click and run it;the program run and exits instantenously...
2013/06/02
[ "https://Stackoverflow.com/questions/16881955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/996366/" ]
add an empty `raw_input()` at the end to pause until you press `Enter` ``` print("Enter two Numbers\n") a = int(raw_input('A=')) b = int(raw_input('B=')) c=a+b print ('C= %s' %c) raw_input() # waits for you to press enter ``` Alternatively run it from `IDLE`, command line, or whichever editor you use.
Run your file from the command line. This way you can see exceptions. Execute `cmd` than in the "dos box" type: ``` python myfile.py ``` Or on Windows likley just: ``` myfile.py ```
1,392
34,777,676
So I have created a function in my program that allows the user to save whatever he/she draws on the Turtle canvas as a Postscript file with his/her own name. However, there have been issues with some colors not appearing in the output as per the nature of Postscript files, and also, Postscript files just won't open on...
2016/01/13
[ "https://Stackoverflow.com/questions/34777676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5661257/" ]
[If you don't supply the file parameter](https://www.tcl.tk/man/tcl8.4/TkCmd/canvas.htm#M60) in the call to `cnv.postscript`, then a `cnv.postscript` returns the PostScript as a (unicode) string. You can then convert the unicode to bytes and feed that to `io.BytesIO` and feed that to `Image.open`. [`Image.open`](http:...
Adding to unutbu's answer, you can also write the data again to a BytesIO object, but you have to seek to the beginning of the buffer after doing so. Here's a flask example that displays the image in browser: ```python @app.route('/image.png', methods=['GET']) def image(): """Return png of current canvas""" ps...
1,395
73,025,430
I am currently running a function using python's concurrent.futures library. It looks like this (I am using Python 3.10.1 ): ``` with concurrent.futures.ThreadPoolExecutor() as executor: future_results = [executor.submit(f.get_pdf_multi_thread, ssn) for ssn in ssns] for future in concurrent.futures.as_co...
2022/07/18
[ "https://Stackoverflow.com/questions/73025430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8972132/" ]
to find the functions and procedures where a table is referenced, you can scan the `routine_definition` column of the `sysibm.routines` view for the table name. Use `regexp_instr` function to look for the pattern FROM|UPDATE|INSERT INTO followed by the table name. ``` with t1 as ( ...
you can use ibm function RELATED\_OBJECTS SQL <https://www.ibm.com/docs/en/i/7.3?topic=services-related-objects-table-function>
1,396
26,129,650
I am a beginner in python. I want to ask the user to input his first name. The name should only contain letters A-Z,if not, I want to display an error and request the user to enter the name again until the name is correct. Here is the code am trying. However, The string is not checked even when it contains numbers and ...
2014/09/30
[ "https://Stackoverflow.com/questions/26129650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1671718/" ]
You don't need `re`, just use [str.isalpha](http://www.tutorialspoint.com/python/string_isalpha.htm) ``` def get_first_name(): while True: first_name = raw_input("Please enter your first name.") if not first_name.isalpha(): # if not all letters, ask for input again print "Invalid ent...
``` if (re.match("^[A-Za-z]+$", first_name)==False): ``` re.match is returning None when there is no match. None does not equal False. You could write it like this: ``` if not re.match("^[A-Za-z]+$", first_name): ```
1,397
63,498,826
[![Image of cone](https://i.stack.imgur.com/NuZNp.jpg)](https://i.stack.imgur.com/NuZNp.jpg) How do I make it so everything in the image is in gray-scale except the orange cone. Using opencv python.
2020/08/20
[ "https://Stackoverflow.com/questions/63498826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13991355/" ]
You can achieve your goal by using `bitwise_and()` function and `thresholding`. Steps: * generate `mask` for the required region.(here `thresholding` is used but other methods can also be used) * extract required `regions` using `bitwise_and` (image & mask). * Add `masked regions` to get output. Here's sample code: ...
Here is an alternate way to do that in Python/OpenCV. * Read the input * Threshold on color using cv2.inRange() * Apply morphology to clean it up and fill in holes as a mask * Create a grayscale version of the input * Merge the input and grayscale versions using the mask via np.where() * Save the results Input: [![e...
1,398
54,450,504
I was looking for this information for a while, but as additional packages and python versions can be installed through `homebrew` and `pip` I have the feeling that my environment is messed up. Furthermore a long time ago, I had installed some stuff with `sudo pip install` and as well `sudo python ~/get-pip.py`. Is th...
2019/01/30
[ "https://Stackoverflow.com/questions/54450504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1767754/" ]
Technically inline JavaScript with a `<script>` tag could do what you are asking. You could even look into the many templating solutions available via JavaScript libraries. That would not actually provide any benefit, though. JavaScript changes what is ultimately displayed, not the file itself. Since your use case doe...
This … > > My html file contains in many places the code `&nbsp;&nbsp;&nbsp;` > > > … is actually what is wrong in your file! `&nbsp;` is not meant to use for layout purpose, you should fix that and use CSS instead to layout it correctly. `&nbsp;` is meant to stop breaking words at the end of a line that are s...
1,399
55,223,059
May I know why I get the error message - NameError: name 'X\_train\_std' is not defined ``` from sklearn.linear_model import LogisticRegression lr = LogisticRegression(C=1000.0, random_state=0) lr.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=lr, ...
2019/03/18
[ "https://Stackoverflow.com/questions/55223059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9658840/" ]
I want to share a text about Dependency Injection, It makes us to change our mind using dependency injection : ***Do not (always) use DI: Injectables versus newables*** > > Something that was immensely useful to me when learning about DI > frameworks was the realisation that using a DI framework does not mean > t...
We can inject same class with @Named ``` @Provides @Named(CMS.Client.DELIVERY_API_CLIENT) fun provideCMSClient(): CDAClient { return CDAClient.builder() .setSpace("4454") .setToken("777") .build() } @Provides @Nam...
1,404
67,867,496
Please forgive my ignorant question. I'm in the infant stage of learning Python. I want to convert Before\_text into After\_text. ``` <Before_text> Today, I got up early, so I’m absolutely exhausted. I had breakfast: two slices \n of cold toast and a disgusting coffee, then I left the house at 8 o’clock still \n feeli...
2021/06/07
[ "https://Stackoverflow.com/questions/67867496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14949033/" ]
If you want to use [fileinput.input()](https://docs.python.org/3/library/fileinput.html) you should provide input filenames as arguments (`sys.argv`), simple example, if you have `cat.py` as follows ``` import fileinput for line in fileinput.input(): print(line, end='') ``` and text files `file1.txt`, `file2.txt...
According to the docs, `fileinput.input()` is a shortcut that takes things from the command line input and tries to open them one at a time, or if nothing is specified it uses `stdin` as its input. Please show us how you are invoking your script. I suspect you have an `-f` in there that the function is trying to open.
1,405
60,174,534
I know this is kind of stupid since BigQueryML now provides Kmeans with good initialization. Nonetheless I was required to train a model in tensorflow and then pass it to BigQuery for prediction. I saved my model and everything works fine, until I try to upload it to bigquery. I get the following error: ``` TensorFl...
2020/02/11
[ "https://Stackoverflow.com/questions/60174534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12880545/" ]
You can check the shape in the savedmodel file by using the command line program saved\_model\_cli that ships with tensorflow. Make sure your export signature in tensorflow specifies the shape of the output tensor.
The main issue is that the output tensor shape of TF built-in KMeans estimator model has unknown rank in the saved model. Two possible ways to solve this: * Try training the KMeans model on BQML directly. * Reimplement the TF KMeans estimator model to reshape the output tensor into a specific tensor shape.
1,406
14,101,852
I have this text file: www2.geog.ucl.ac.uk/~plewis/geogg122/python/delnorte.dat I want to extract column 3 and 4. I am using np.loadtxt - getting the error: ``` ValueError: invalid literal for float(): 2000-01-01 ``` I am only interested in the year 2005. How can I extracted both columns?
2012/12/31
[ "https://Stackoverflow.com/questions/14101852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1860229/" ]
You can provide a custom conversion function for a specific column to `loadtxt`. Since you are only interested in the year I use a `lambda`-function to split the date on `-` and to convert the first part to an `int`: ``` data = np.loadtxt('delnorte.dat', usecols=(2,3), converters={2: lambda s: int...
You should not use NumPy.loadtxt to read these values, you should rather use the [`csv` module](http://pastebin.com/JyVC4XfF) to load the file and read its data.
1,408
20,005,173
Maximum, minimum and total numbers using python. For example: ``` >>>maxmin() Enter integers, one per line, terminated by -10 : 2 1 3 7 8 -10 Output : total =5, minimum=1, maximum = 8 ``` Here is my code. I need some help with this. ``` def maxmin(): minimum = None maximum = None w...
2013/11/15
[ "https://Stackoverflow.com/questions/20005173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1725323/" ]
``` def maxmintotal(): num = 0 numbers = [] while True: num = int(input('Please enter a number, or -10 to stop: ' )) if num == -10: break numbers.append(num) print('Numbers:', len(numbers)) print('Maximum:', max(numbers)) print('Minumum:', min(numbers)) `...
You have to define `num` before you use it in the `while`, also your nested `if` should be out of the other `if`: ``` def maxmin(): minimum = None maximum = None num = None while True: num = input('Please enter a number, or -10 to stop: ') if num == -10: break if (...
1,410
71,197,496
I have python script that creates dataflow template in the specified GCS path. I have tested the script using my GCP Free Trial and it works perfect. My question is using same code in production environment I want to generate a template but I can not use Cloud-Shell as there are restrictions also can not directly run t...
2022/02/20
[ "https://Stackoverflow.com/questions/71197496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2458847/" ]
First, you can do this with RXJS, or promises, but either way intentionally makes room for asynchronous programming, so when your `transform` method synchronously returns `this.value` at the end, I don't think you're getting what you're expecting? I'm guessing the reason it is compiling but you don't think it is workin...
If I understand the problem well, your code has a fundamental problem and the fact that "*Everything works well, if I use Observables*" is a fruit of a very special case. Let's look at this very stripped down version of your code ``` function translationObservable(key) { return of("Obs translates key: " + key); } ...
1,415
73,066,287
I have a project hosted on Microsoft Azure. It has Azure Functions that are Python code and they recently stopped working (500 Internal Server Error). The code has errors I haven't had before and no known changes were made (but the possibility exists because people from other teams could have changed a configuration so...
2022/07/21
[ "https://Stackoverflow.com/questions/73066287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6126073/" ]
I was facing the same issue last Thursday. However, we have tried most of the solutions which are available on Internet but none of them help us. And in the end, we have just updated Azure Function Runtime Python 3.6 to 3.7 and Boomm.. it's working. Moreover, we have also noticed that when we tried to create new Azur...
We had the exact same issue on Friday. What worked for us was to replace pyodbc with pypyodbc. We did this so that we didn't have to change it in our code: ``` import pypyodbc as pyodbc ``` Also, we upgraded our Azure Functions to use Python 3.7 (will probably update to 3.9 soon). Azure will not be supporting Python...
1,416
60,520,118
I want to scrape phone no but phone no only displays after clicked so please is it possible to scrape phone no directly using python?My code scrape phone no but with starr\*\*\*. here is the link from where I want to scrape phone no:<https://hipages.com.au/connect/abcelectricservicespl/service/126298> please guide me! ...
2020/03/04
[ "https://Stackoverflow.com/questions/60520118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7514427/" ]
Find the Id or class of that element and use jQuery to change the name. If the element is a Anchor tag, use the below code. ``` jQuery(document).ready(function($) { $("#button_id").text("New Text"); }); ``` If the element is button, use below code based on type of button. ``` <input type='button' value='Add' id='...
From the screenshot, it seems like you are trying to change the text of a menu link (My Account). If so make sure that you haven't given any custom name for My Account page in the Wordpress navigation. Inspect the page using developer tools and find the Class/Id of that element. Then you can use jQuery to alter the co...
1,417
4,300,979
Defining a function, MyFunction(argument, \*args): [do something to argument[arg] for arg in \*args] if \*args is empty, the function doesn't do anything, but I want to make the default behavior 'use the entire set if length of \*args == 0' ``` def Export(source, target, *args, sep=','): for item in source: ...
2010/11/29
[ "https://Stackoverflow.com/questions/4300979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/508440/" ]
Is there a way to pass an "entire set" argument to `SubsetOutput`, so you can bury the conditional inside its call rather than have an explicit `if`? This could be `None` or `[]`, for example. ``` # Pass None to use full subset. def Export(source, target, *args, sep=','): for item in source: SubsetOutput(W...
Just check its not none, you don't have to create a separate argument ``` def test(*args): if not args: return #break out return True #or whatever you want ```
1,418
52,172,821
I'm currently trying to convert a nested dict into a list of objects with "children" and "leaf". Here my input dict and the output I'm trying to obtain: Input: ``` { "a": { "aa": {} }, "b": { "c": { "d": { 'label': 'yoshi' } }, "e": {...
2018/09/04
[ "https://Stackoverflow.com/questions/52172821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2688174/" ]
I have commented the function as I feel necessary. ``` def convert(d): children = [] #iterate over each child's name and their dict (child's childs) for child, childs_childs in d.items(): #check that it is not a left node if childs_childs and \ all(isinstance(v,dict) for k,v in c...
Try this solution (`data` is your input dictionary): ``` def walk(text, d): result = {'text': text} # get all children children = [walk(k, v) for k, v in d.items() if k != 'label'] if children: result['children'] = children else: result['leaf'] = True # add label if exists ...
1,421
44,382,348
I am just 4 days old to python. I am just trying to understand the root \_\_init\_\_.py import functionality. Googled lot to understand the same but not able to find one useful link (may be my search key is not relevant) . Please share some links. I am getting error as "ImportError: cannot import name Person" Below i...
2017/06/06
[ "https://Stackoverflow.com/questions/44382348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6346252/" ]
Either, as @gonczor suggested, you can simply leave \_\_init\_\_ empty (moreover, you don't need the root one) and import directly from the package: ``` from model.myclass import Person ``` Or, if you intentionally want to flatten the interface of the package, this is as simple as this: model/\_\_init\_\_.py ``` f...
The error basically says the interpreter can't find anything that would match `Person` in a given namespace, in your case `model` package. It's because it's in `model.myclass` package, but it's imported to `root` and not to `run`. Modules in python are basically directories with `__init__.py` script. But it's tricky t...
1,423
55,668,648
I need to find the starting index of the specific sequences (sequence of strings) in the list in python. For ex. ``` list = ['In', 'a', 'gesture', 'sure', 'to', 'rattle', 'the', 'Chinese', 'Government', ',', 'Steven', 'Spielberg', 'pulled', 'out', 'of', 'the', 'Beijing', 'Olympics', 'to', 'protest', 'against', 'China...
2019/04/13
[ "https://Stackoverflow.com/questions/55668648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3404345/" ]
You could simply iterate over list of your words and check at every index if following words match any of your sequences. ``` words = ['In', 'a', 'gesture', 'sure', 'to', 'rattle', 'the', 'Chinese', 'Government', ',', 'Steven', 'Spielberg', 'pulled', 'out', 'of', 'the', 'Beijing', 'Olympics', 'to', 'protest', 'against...
**You can do something like:** ``` def find_sequence(seq, _list): seq_list = seq.split() all_occurrence = [idx for idx in [i for i, x in enumerate(_list) if x == seq_list[0]] if seq_list == list_[idx:idx+len(seq_list)]] return -1 if not all_occurrence else all_occurrence[0] ``` --- **Output:** ``` for ...
1,424
69,682,188
For the sake of practice, I am writing a class BankAccount to learn OOP in python. In an attempt to make my program more redundant am trying to write a test function `test_BankBankAccount()` to practice how to do test functions as well. The test function `test_BankBankAccount()` is suppose to test that the methods `de...
2021/10/22
[ "https://Stackoverflow.com/questions/69682188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16925420/" ]
@KoenLostrie is absolutely correct as to *Why your trigger does not fire on Insert*. But that is just half the problem. But, the other issue stems from the same misconception: NULL values The call to `check_salary` passes `:old.job_id` but it is still null, resulting in cursor ( `for i in (Select ...)`) returning no ro...
Congrats on the well documented question. The issue is with the `WHEN` clause of the trigger. On insert the old value is `NULL` and in oracle, you can't compare to NULL using "=" or "!=". Check this example: ``` PDB1--KOEN>create table trigger_test 2 (name VARCHAR2(10)); Table TRIGGER_TEST created. PDB1--KOEN>...
1,425
38,797,047
I'm running ubuntu 12.04 and usually use python 2.7, but I need a python package that was built with python 3.4 and that uses lxml. After updating aptitude, I can install python 3.2 and lxml, but the package I want only works with 3.4. After installing python 3.4, I try to install lxml dependencies using ``` pip3 inst...
2016/08/05
[ "https://Stackoverflow.com/questions/38797047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1106278/" ]
You are running ``` pip3 install libxml2-dev ``` when you should be running ``` sudo apt-get install libxml2 libxml2-dev ``` (you may also need `libxslt` and its dev version as well) `pip` doesn't install system libraries, `apt` and friends do that.
See <http://www.lfd.uci.edu/~gohlke/pythonlibs/#libxml-python> Download the package and then do a `pip install <package.whl>`.
1,428
28,627,414
Welcome... I'm creating a project where I parse xlsx files with xlrd library. Everything works just fine. Then I configured RabbitMQ and Celery. Created some tasks in main folder which works and can be accessed from iPython. The problems starts when I'm in my application (application created back in time in my project)...
2015/02/20
[ "https://Stackoverflow.com/questions/28627414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4563194/" ]
You would need to extend the scale class and override the `calculateXLabelRotation` method to use a user inputted rotation rather than trying to work it out it's self. If you do this you would then need to extend the bar or line chart and override the init method to make use of this scale class. (or you could make thes...
Note that **for chart.js 3.x the way of specifying the axis scale options has changed**: see <https://www.chartjs.org/docs/master/getting-started/v3-migration.html#scales> Consequently in the above answer for 2.x you need to remove the square brackets like this: ``` var myChart = new Chart(ctx, { type: 'bar', dat...
1,429
29,790,344
I want to generate the following xml file: ``` <foo if="bar"/> ``` I've tried this: ``` from lxml import etree etree.Element("foo", if="bar") ``` But I got this error: ``` page = etree.Element("configuration", if="ok") ^ SyntaxError: invalid syntax ``` Any ideas? I'm usi...
2015/04/22
[ "https://Stackoverflow.com/questions/29790344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4131226/" ]
``` etree.Element("foo", {"if": "bar"}) ``` The attributes can be passed in as a dict: ``` from lxml import etree root = etree.Element("foo", {"if": "bar"}) print etree.tostring(root, pretty_print=True) ``` output ``` <foo if="bar"/> ```
'if' is a reserved word in Python, which means that you can't use it as an identifier.
1,431
21,662,881
My approach is: ``` def build_layers(): layers = () for i in range (0, 32): layers += (True) ``` but this leads to ``` TypeError: can only concatenate tuple (not "bool") to tuple ``` Context: This should prepare a call of [bpy.ops.pose.armature\_layers](http://www.blender.org/documentation/blender...
2014/02/09
[ "https://Stackoverflow.com/questions/21662881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/241590/" ]
`(True)` is not a tuple. Do this instead: ``` layers += (True, ) ``` Even better, use a generator: ``` (True, ) * 32 ```
Since tuples are immutable, each concatenation creates a new tuple. It is better to do something like: ``` def build_layers(count): return tuple([True]*count) ``` If you need some logic to the tuple constructed, just use a list comprehension or generator expression in the tuple constructor: ``` >>> tuple(bool(o...
1,434
57,612,054
I'm testing an API endpoint that is supposed to raise a ValidationError in a Django model (note that the exception is a Django exception, not DRF, because it's in the model). ``` from rest_framework.test import APITestCase class TestMyView(APITestCase): # ... def test_bad_request(self): # ... ...
2019/08/22
[ "https://Stackoverflow.com/questions/57612054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/686617/" ]
**Question**: Isn't DRF's APIClient supposed to handle every exception? **Answer**: No. It's a test client, it won't handle any uncaught exceptions, that's how test clients work. Test clients propagate the exception so that the test fails with a "crash" when an exception isn't caught. You can test that exceptions are...
Something in your code is causing a python error which is halting execution before your POST request can return a valid HTTP response. Your code doesn't even reach the line `self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)` because there is no response. If you're calling your tests in the normal way...
1,436
2,261,671
I have a bit counting method that I am trying to make as fast as possible. I want to try the algorithm below from [Bit Twiddling Hacks](http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel), but I don't know C. What is 'type T' and what is the python equivalent of (T)~(T)0/3? > > A generalization ...
2010/02/14
[ "https://Stackoverflow.com/questions/2261671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/270316/" ]
T is a integer type, which I'm assuming is unsigned. Since this is C, it'll be fixed width, probably (but not necessarily) one of 8, 16, 32, 64 or 128. The fragment `(T)~(T)0` that appears repeatedly in that code sample just gives the value 2\*\*N-1, where N is the width of the type T. I suspect that the code may requi...
What you copied is a template for generating code. It's not a good idea to transliterate that template into another language and expect it to run fast. Let's expand the template. (T)~(T)0 means "as many 1-bits as fit in type T". The algorithm needs 4 masks which we will compute for the various T-sizes we might be inte...
1,438
74,335,162
I have a file with a function and a file that calls the functions. Finally, I run .bat I don't know how I can add an argument when calling the .bat file. So that the argument was added to the function as below. file\_with\_func.py ``` def some_func(val): print(val) ``` run\_bat.py ``` from bin.file_with_func i...
2022/11/06
[ "https://Stackoverflow.com/questions/74335162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17356459/" ]
You need to turn a bunch of POJO's (Plain Old JavaScript Objects) into a class with methods specialized for this kind of object. The idiomatic way is to create a class that takes the POJO's data in some way (since I'm lazy I just pass the entire thing). TypeScript doesn't change how you approach this - you just need to...
> > The problem is that deserialized json is just a data container... > > > That's right. In order to deserialize JSON to a class instance with methods, you need to tell deserializer which class is used to create the instance. However, it's not a good idea to define such class information using `interface` in Typ...
1,439
67,267,305
I have a custom training loop that can be simplified as follow ``` inputs = tf.keras.Input(dtype=tf.float32, shape=(None, None, 3)) model = tf.keras.Model({"inputs": inputs}, {"loss": f(inputs)}) optimizer = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9, nesterov=True) for inputs in batches: with tf.Gra...
2021/04/26
[ "https://Stackoverflow.com/questions/67267305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782553/" ]
Create the EMA object before the training loop: ``` ema = tf.train.ExponentialMovingAverage(decay=0.9999) ``` And then just apply the EMA after your optimization step. The ema object will keep shadow variables of your model's variables. (You don't need the call to `tf.control_dependencies` here, see the note in the ...
EMA with customizing `model.fit` -------------------------------- Here is a working example of **Exponential Moving Average** with customizing the `fit`. [Ref](https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage). ``` from tensorflow import keras import tensorflow as tf class EMACustomModel...
1,440
21,243,719
I am using python (2.7) and I have a long nested list of X,Y coordinates specifying end points of lines. I need to shift the Y coordinates by a specified amount. For instance, this is what I would like to do: ``` lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))] ``` perform some coding that is ...
2014/01/20
[ "https://Stackoverflow.com/questions/21243719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3216653/" ]
I'd do something like: ``` >>> dy = 100 >>> lines = [((2, 98), (66, 32)), ((67, 31), (96, 2)), ((40, 52), (88, 3))] >>> newlines = [tuple((x,y+dy) for x,y in subline) for subline in lines] >>> newlines [((2, 198), (66, 132)), ((67, 131), (96, 102)), ((40, 152), (88, 103))] ``` which is roughly the same as: ``` newl...
Tuples are immutable, so as currently structured it's impossible without making either the line or the point a list, or rebuilding from scratch each time point as a list, line as a tuple: ``` line = lines[0] for point in line: point[1] += 100 ``` line as a list, point as a tuple: ``` line = lines[0] for i, (x,...
1,441
63,871,922
I am using **Ubuntu 20.04**.I upgraded Tensorflow-2.2.0 to Tensorflow-2.3.0. When the version was **2.2.0**, tensorflow was utilizing GPU well. But after upgrading to version **2.3.0** it doesn't detecting GPU. I have seen this [Link](https://stackoverflow.com/questions/63515767/tensorflow-2-3-0-does-not-detect-gpu) f...
2020/09/13
[ "https://Stackoverflow.com/questions/63871922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13442402/" ]
In your `~/.bashrc` add: ``` LD_LIBRARY_PATH=/usr/local/cuda-10.1/lib64 ``` If you have a different location for the lib64 folder, you need to adjust it accordingly. As a side note, if you want to switch between multiple CUDA versions frequently you can also set an environment variable for a specific command direct...
> > 2020-09-13 21:28:48.883415: W tensorflow/stream\_executor/platform/default/dso\_loader.cc:59] Could not load dynamic library 'libcublas.so.10'; dlerror: libcublas.so.10: cannot open shared object file: No such file or directory; > > > In my case, this caused by being installed `libcublas10` and `libcublas-d...
1,444
787,711
I'm trying to write a function to return the truth value of a given PyObject. This function should return the same value as the if() truth test -- empty lists and strings are False, etc. I have been looking at the python/include headers, but haven't found anything that seems to do this. The closest I came was PyObject\...
2009/04/24
[ "https://Stackoverflow.com/questions/787711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Isn't this it, in object.h: ``` PyAPI_FUNC(int) PyObject_IsTrue(PyObject *); ``` ?
Use `int PyObject_IsTrue(PyObject *o)` Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1. (from [Python/C API Reference Manual](http://docs.python.org/c-api/object.html))
1,445
54,399,465
I have a dataframe like this, ``` ColA Result_ColA ColB Result_ColB Result_ColC 1 True 1 True True 2 False 2 True False 3 True 3 True False ``` I want to identify the row numbers inside a list in python, which has a value False present in any of the Resul...
2019/01/28
[ "https://Stackoverflow.com/questions/54399465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7638174/" ]
Alternatively you could use countDocuments() to check the number of documents in the query? This will just count the number rather than returning it.
Pass id in `findOne()` Make a one common function. ``` const objectID = require('mongodb').ObjectID getMongoObjectId(id) { return new objectID(id) } ``` Now just call function ``` findOne({_id:common.getMongoObjectId('ID value hear')}) ``` It will same as `where` condition in mysql.
1,446
21,508,816
sorry if this is dumb question, but this is the first time i've used python and Mongo DB. Anyway, the problem I have is that I am trying to insert() a string to be stored in my data base -by read()-ing data in with a loop and then giving insert() line 1 and line2 in a single string (This is probably a messy way of doin...
2014/02/02
[ "https://Stackoverflow.com/questions/21508816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3196428/" ]
The relevant part of your code is this: ``` post=collection.insert() ``` What you're doing there is calling the `insert` method without arguments rather than assigning that method to `post`. As the [`insert` method](http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.inser...
It appears as has been pointing out that you are attempting to create a [closure](https://stackoverflow.com/questions/4020419/closures-in-python) on the insert method. In this case I don't see the point as it will never be passed anywhere and/or need to reference something in the scope outside of where it was used. Jus...
1,447
63,993,901
I have just started my first python project. When it comes to running the shell script, the following error appears. What can be the cause of that problem? Maybe it is easy to solve. Thanks for your help, I am glad to provide more specific information as you need. Thanks.[enter image description here](https://i.stack....
2020/09/21
[ "https://Stackoverflow.com/questions/63993901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14315301/" ]
This is a very "basic" example: ``` chars = 'abcdefghijklmnopqrstuvwxyz' my_list = [] for c1 in chars: for c2 in chars: for c3 in chars: for c4 in chars: my_list.append(c1+c2+c3+c4) print(my_list) ```
It's not easy to know what you consider "magical", but I don't see the magic in loops. Here is one variation: ``` cs = 'abcdefghijklmnopqrstuvwxyz' list(map(''.join, [(a,b,c,d) for a in cs for b in cs for c in cs for d in cs])) ```
1,448
43,724,030
I try out creating Word documents with python-docx. The created file is in letter dimensions 8.5 x 11 inches. But in Germany the standard format is A4 8.27 x 11.69 inches. ``` from docx import Document from docx.shared import Inches document = Document() document.add_heading('Document Title', 0) document.settings p...
2017/05/01
[ "https://Stackoverflow.com/questions/43724030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5418245/" ]
It appears that a `Document` is made of several [`Section`](http://python-docx.readthedocs.io/en/latest/api/section.html#docx.section.Section)s with `page_height` and `page_width` attributes. To set the dimensions of the first section to A4, you could try (untested): ``` section = document.sections[0] section.page_he...
I believe you want this, from the [documentation](http://python-docx.readthedocs.io/en/latest/user/sections.html#page-dimensions-and-orientation). > > Three properties on Section describe page dimensions and orientation. > Together these can be used, for example, to change the orientation of > a section from portra...
1,450
21,368,393
I installed Anaconda, but now that I wanted to use StringFunction in scitools.std I get error: ImportError: No module named scitools.std! So I did this: ``` sudo apt-get install python-scitools ``` Still didn't work. How can I help my computer "find scitools"? Thank you for your time. Kind regards, Marius
2014/01/26
[ "https://Stackoverflow.com/questions/21368393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317563/" ]
Why not use PostGIS for this? ----------------------------- You're overlooking what's possibly the ideal storage for this kind of data - PostGIS's data types, particularly the `geography` type. ``` SELECT ST_GeogFromText('POINT(35.21076593772987 11.22855348629825)'); ``` By using `geography` you're storing your dat...
[All of the character types](http://www.postgresql.org/docs/current/static/datatype-character.html) (TEXT, VARCHAR, CHAR) behave similarly from a performance point of view. They are normally stored in-line in the table row, unless they are very large, in which case they may be stored in a separate file (called a TOAST ...
1,453
56,265,979
i installed python-aiml using pip. when i used the library i am getting wrong out put. so i am trying to change the .aiml file output: ``` Enter your message >> who is your father I was programmed by . ``` i want to assign some values to `"<bot name="botmaster"/>"`,`<bot name="country"/>` etc below is the aiml fil...
2019/05/22
[ "https://Stackoverflow.com/questions/56265979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9422110/" ]
Make sure webpreferences is like this. ``` webPreferences: { nodeIntegration: true, enableRemoteModule: true, contextIsolation: false, }, ```
I fix this issue to add `webPreferences:{ nodeIntegration: true,preload: '${__dirname}/preload.js}',` in `electron.js` file and add `preload.js` file in your directory (I added in `/public` directory where my `electron.js` file exists) **electron.js** ``` mainWindow = new BrowserWindow({ title: 'Electron App', heig...
1,456
65,741,617
I'm very new to all of this, so bear with me. I started, and activated, a virtual environment. But when I pip install anything, it installs to the computer, not the the virtual env. I'm on a Mac, trying to build a Django website. Example: With the virtual machine activated. I type: ``` python -m pip install Django ...
2021/01/15
[ "https://Stackoverflow.com/questions/65741617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15014571/" ]
Run this line from your project folder where "env" is your virtual enviroment ``` # A virtualenv's python: $ env/bin/python -m pip install django ```
If you want to install to your virtualenvironment you have to activate it, otherwise it will install to the main folder.
1,466
35,633,516
In [PEP 754](https://www.python.org/dev/peps/pep-0754/#id5)'s rejection notice, it's stated that: > > This PEP has been rejected. After sitting open for four years, it has > failed to generate sufficient community interest. > > > Several ideas of this PEP were implemented for Python 2.6. > float('inf') and repr(f...
2016/02/25
[ "https://Stackoverflow.com/questions/35633516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4532996/" ]
My guess is that no one wanted to clutter the namespace needlessly. If you want to do math, you can still do: ``` import math print(math.inf) print(-math.inf) print(math.nan) ``` Output: ``` inf -inf nan ```
you can use float('inf') np.nan
1,468