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
58,877,657
I am learning python I have project structure shown below. ``` i3cmd i3lib __init__.py i3common.py i3sound i3sound.py ``` ============================================================== **init**.py is empty i3common.py (removed actual code to simplify the post) ``` def rangeofdata(cmd, d...
2019/11/15
[ "https://Stackoverflow.com/questions/58877657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8446934/" ]
I think you are just missing the installation of the `Lombok` on `intellij` double click on `Lombok.jar` and chose the `intelliJ IDE` Example config for lombok annotation procession in your `build.gradle` : ``` dependencies { compileOnly('org.projectlombok:lombok:1.16.20') annotationProcessor 'org.projectlomb...
Line `compileOnly 'org.projectlombok:lombok:1.18.8'` shows that you're using gradle. I think the easiest way to check whether it works or not can be just running the gradle build (without IDE). Since lombok is an annotation processor, as long as the code passes the compilation, it's supposed to work (and the chances ...
16,010
8,595,689
I'm trying to send a request to an API that only accepts XML. I've used `elementtree.SimpleXMLWriter` to build the XML tree and it's stored in a StringIO object. That's all fine and dandy. The problem is that I have to urlencode the StringIO object in order to send it to the API. But when I try, I get: ``` File "C:...
2011/12/21
[ "https://Stackoverflow.com/questions/8595689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/625840/" ]
As the links you provided point out, php is not a persistent language and there is no way to have persistence across sessions (i.e. page loads). You can create a middle ground though by running a second php script as a daemon, and have your main script (i.e. the one the user hits) connect to that (yes - over a socket.....
If you need to keep the connection open, you need to keep the PHP script open. Commonly PHP is just invoked and then closed after the script has run (CGI, CLI), or it's a mixture (mod\_php in apache, FCGI) in which sometimes the PHP interpreter stays in memory after your script has finished (so everything associated fr...
16,013
60,780,826
I try to write a python function that counts a specific word in a string. My regex pattern doesn't work when the word I want to count is repeated multiple times in a row. The pattern seems to work well otherwise. Here is my function ``` import re def word_count(word, text): return len(re.findall('(^|\s|\b)'+re....
2020/03/20
[ "https://Stackoverflow.com/questions/60780826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7915157/" ]
Problem is in your regex. Your regex is using 2 capture groups and `re.findall` will return any capture groups if available. That needs to change to non-capture groups using `(?:...)` Besides there is reason to use `(^|\s|\b)` as `\b` or word boundary is suffice which covers all the cases besides `\b` is zero width. ...
I am not sure this is 100% because I don't understand the part about passing the function the word to search for when you are just looking for words that repeat in a string. So maybe consider... ``` import re pattern = r'\b(\w+)( \1\b)+' def word_count(text): split_words = text.split(' ') count = 0 for s...
16,014
66,702,514
I am trying to create a function that would take a user inputted number and determine if the number is an integer or a floating-point depending on what the mode is set to. I am very new to python and learning the language and I am getting an invalid syntax error and I don't know what to do. So far I am making the integ...
2021/03/19
[ "https://Stackoverflow.com/questions/66702514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15429618/" ]
`.testcontainer.properties` in my `$HOME` directory fixed the issue for me. This file is used to override properties but I am still not sure how that fixes the issue. I see in my `.gitlab.yml` that what we do and just imitated that in my local, that solved the issue.
For some it might help to update the version of testcontainers
16,015
62,421,333
I have a dataframe like image1. I want to convert it to image2. I have tried r, python, and excel but failed. Excel formula: =INDEX(AV2:AW2,MODE(MATCH(AV2:AW2,AV2:AW2,0))) give me N/A output. the "k2" column would be the most common element from "knumbers" column. Any Help. Best, Zillur [![image1](https://i.stack.imgur...
2020/06/17
[ "https://Stackoverflow.com/questions/62421333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4168405/" ]
In R, you can split the strings on comma, count the frequency using `table` and get the most frequently occurring string. ``` df$k2 <- sapply(strsplit(df$knumbers, ','), function(x) names(sort(table(x), decreasing = TRUE)[1])) ```
Python solution: ``` # Initialise pandas, and mode in session: import pandas as pd from statistics import mode # Scalar denoting the full path to file (including file name): filepath => string scalar filepath = '' # Read in the Excel sheet: df => Data Frame df = pd.read_excel(filepath) # Find modal element per r...
16,016
9,905,874
I'm running into a problem that I haven't seen anyone on StackOverflow encounter or even google for that matter. My main goal is to be able to replace occurences of a string in the file with another string. Is there a way there a way to be able to acess all of the lines in the file. The problem is that when I try to ...
2012/03/28
[ "https://Stackoverflow.com/questions/9905874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1297872/" ]
Try: ``` f = open("filename.txt", "rb") ``` On Windows, `rb` means open file in binary mode. According to the docs, text mode vs. binary mode only has an impact on end-of-line characters. But (if I remember correctly) I believe opening files in text mode on Windows also does something with EOF (hex 1A). You can als...
If you use the file like this: ``` with open("filename.txt") as f: for line in f: newfile.write(line.replace("string1", "string2")) ``` It should only read into memory one line at a time, unless you keep a reference to that line in memory. After each line is read it will be up to pythons garbage colle...
16,017
68,945,015
I need a simple python library to convert PDF to image (render the PDF as is), but after hours of searching, I keep hitting the same wall, I find libraries like `pdf2image` python library (and many similar ones), which depend on external applications or wrap command-line tools. Although there are workarounds to allow ...
2021/08/26
[ "https://Stackoverflow.com/questions/68945015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/452748/" ]
You said "Ended up using pdf2image" [pdf2image (MIT)](https://pypi.org/project/pdf2image/). A python (3.6+) module that wraps pdftoppm (GPL?) and pdftocairo (GPL?) to convert PDF to a PIL Image object. Generally [Poppler (GPL)](https://en.wikipedia.org/wiki/Poppler_(software)) spinoffs from Open Source [Xpdf (GPL)](h...
You can convert PDF's to images without external dependencies using PyMuPDF. I use it for Azure functions. Install with `pip install PyMuPDF` In your python file: ``` import fitz pdfDoc = fitz.open(filepath) img = pdfDoc[0].get_pixmap(matrix=fitz.Matrix(2,2)) bytesimg = img.tobytes() ``` This takes the first page ...
16,020
31,941,951
In my Python code I use a third party shared object, a `.so` file, which I suspect to contains a memory leak. During the run of my program I have a loop where I repeatedly call functions of the shared object. While the programm is running I can see in `htop`, that the memory usage is steadily increasing. When the RAM...
2015/08/11
[ "https://Stackoverflow.com/questions/31941951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380038/" ]
The exact cause of the exception is, that the number `1439284609013` is too big to fit into `Integer`. However, the actual issue lies elsewhere. I have looked at the source code, your parameters seem to be wrong: ``` emp1 ~/KT/bkp 1439284609013 1439284641872 ``` You have given a `String`, another `String` and two `...
I entered only the start time and end time. Export is expecting versions before start and end time. So finally I entered the version number it worked. ``` ./hbase org.apache.hadoop.hbase.mapreduce.Export emp1 ~/KT/bkp 2147483647 1439284609013 1439284646830 ```
16,021
67,280,726
I want to extract some data from a text file to a dataframe : the text file look like this ``` URL: http://www.nytimes.com/2016/06/30/sports/baseball/washington-nationals-max-scherzer-baffles-mets-completing-a-sweep.html WASHINGTON — Stellar .... stretched thin. “We were going t......e do anything.” Wednesday’s ... ...
2021/04/27
[ "https://Stackoverflow.com/questions/67280726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10586681/" ]
``` # read file file = open('ny.txt', encoding="utf8").read() url = [] text = [] # split text at every 2-new-lines # elements at 'odd' positions are 'urls' # elements at 'even' positions are 'text/content' for ind, line in enumerate(file.split('\n\n')): if ind%2==0: url.append(line) else: text...
You can do it easily in the following way: ``` import pandas as pd text = '''URL: http://www.nytimes.com/2016/06/30/sports/baseball/washington-nationals-max-scherzer-baffles-mets-completing-a-sweep.html WASHINGTON — Stellar .... stretched thin. “We were going t......e do anything.” Wednesday’s ... starter. “We’re n....
16,023
63,506,041
Am new to python and am trying to read a PDF file to pull the `ID No.`. I have been successful so far to extract the text out of the PDF file using `pdfplumber`. Below is the code block: ``` import pdfplumber with pdfplumber.open('ABC.pdf') as pdf_file: firstpage = pdf_file.pages[0] raw_text = firstpage.extra...
2020/08/20
[ "https://Stackoverflow.com/questions/63506041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7855187/" ]
Try using a regular expression: ``` import pdfplumber import re with pdfplumber.open('ABC.pdf') as pdf_file: firstpage = pdf_file.pages[0] raw_text = firstpage.extract_text() m = re.search(r'ID No\. : (\d+)', raw_text) if m: print(m.group(1)) ``` Of course you'll have to iterate over *all* t...
If the length of the id number is always the same, I would try to find the location of it with the find-function. `position = raw_text.find('ID No. : ')`should return the position of the I in ID No. position + 9 should be the first digit of the id. When the number has always a length of 8 you could get it with `int(raw...
16,024
14,657,498
I'd like to create a `text/plain` message using Markdown formatting and transform that into a `multipart/alternative` message where the `text/html` part has been generated from the Markdown. I've tried using the filter command to filter this through a python program that creates the message, but it seems that the messa...
2013/02/02
[ "https://Stackoverflow.com/questions/14657498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053149/" ]
Inside your `DialogFragment`, call [`Fragment.setRetainInstance(boolean)`](http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance%28boolean%29) with the value `true`. You don't need to save the fragment manually, the framework already takes care of all of this. Calling this will prevent your...
One of the advantages of using `dialogFragment` compared to just using `alertDialogBuilder` is exactly because dialogfragment can automatically recreate itself upon rotation without user intervention. However, when the dialogfragment does not recreate itself, it is possible that you overwrite `onSaveInstanceState` but...
16,026
40,390,874
So, I'm making a Bank class in python. It has the basic functions of deposit, withdrawing, and checking your balance. I'm having trouble with a transfer method though. This is my code for the class. ``` def __init__(self, customerID): self.ID = customerID self.total = 0 def deposit(self, amount): self.to...
2016/11/02
[ "https://Stackoverflow.com/questions/40390874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6023942/" ]
``` def __init__(self, customerID): self.ID = customerID self.__class__.__dict__.setdefault("idents",{})[self.ID] = self self.total = 0 @classmethod def get_bank(cls,id): return cls.__dict__.setdefault("idents",{}).get(id) ``` is one kind of gross way you could do it ``` bank2_found = Bank.get_bank(...
You could store all the ID numbers and their associated objects in a dict with the ID as the key and the object as the value.
16,034
31,977,902
How can I calculates the elapsed time between a start time and an end time of a event using python, in format like 00:00:00 and 23:59:59?
2015/08/13
[ "https://Stackoverflow.com/questions/31977902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5221453/" ]
Make it easy on yourself and try to make your code easy to read. I personally prefer to write my html cleanly and outside of echo statements like so: **Html** ``` if (strlen($in) > 0 and strlen($in) < 20) { $sql = "select name, entry, displayid from item_template where name like '%{$in}%' LIMIT 10"; // the query ...
Ok, here goes... 1. Use event delegation in your JavaScript to handle the button clicks. This will work for all present and future buttons ``` jQuery(function($) { var $theInput = $('#theinput'); $(document).on('click', '.button', function() { $theInput.val(this.value); }); }); ``` 2. Less import...
16,035
47,717,179
If my python script is pivoting and i can no predict how many columns will be outputed, can this be done with the U-SQL REDUCE statement? e.g. ``` @pythonOutput = REDUCE @filteredBets ON [BetDetailID] PRODUCE [BetDetailID] string, EventID float USING new Extension.Python.Reducer(pyScript:@myScript); ```...
2017/12/08
[ "https://Stackoverflow.com/questions/47717179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2725941/" ]
If you have a way to produce a `SqlMap<string,string>` value from within Python (I am not sure if that is supported right now, you can do it with a C# reducer :)), then you could use the map for the dynamic schema part. If it is not supported in Python, please file a feature request at <http://aka.ms/adlfeedback>.
The only way right now is to serialize all the columns into a single column, either as a byte[] or string in your python script. SqlMap/SqlArray are not supported yet as output columns.
16,036
50,113,683
i try to train.py in object\_detection in under git url <https://github.com/tensorflow/models/tree/master/research/object_detection> However, the following error occurs. > > ModuleNotFoundError: No module named 'object\_detection' > > > So I tried to solve the problem by writing the following code. ``` import ...
2018/05/01
[ "https://Stackoverflow.com/questions/50113683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9019755/" ]
try this: python setup.py build python setup.py install
I had to do: `sudo pip3 install -e .` ([ref](https://github.com/tensorflow/models/issues/2031#issuecomment-343782858)) `sudo python3 setup.py install` System: OS: Ubuntu 16.04, Anaconda (I guess this is why I need to use `pip3` and `python3` even I made virtual environment with Pyehon 3.8)
16,037
49,191,477
The `hypot` function, introduced into C in the 1999 revision of the language, calculates the hypotenuse of a right triangle given the other sides as arguments, but with care taken to avoid the over/underflow which would result from the naive implementation as ``` double hypot(double a, double b) { return sqrt(a*a +...
2018/03/09
[ "https://Stackoverflow.com/questions/49191477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468334/" ]
Assuming IEEE 754 basic 64-bit binary floating-point, I would consider an algorithm such as: * Set *s* (for scale) to be 2−512 if 2100 ≤ *a*, 2+512 if *a* < 2−100, and 1 otherwise. * Let *a*' be *a*•*s* and *b*' be *b*•*s*. * Compute sqrt(*a*'•*a*' − *b*'•*b*') / *s*. Notes about the reasoning: * If *a* is large (or...
`hypot` has its idiosyncrasies in that it's one of a *very select few* C standard library functions that does **not** propagate `NaN`! (Another one is `pow` for the case where the first argument being 1.) Setting that aside, I'd be inclined to write merely ``` returns sqrt(h * h - a * a); // h is the hypotenuse ``` ...
16,047
393,637
I'm running a Django application. Had it under Apache + mod\_python before, and it was all OK. Switched to Lighttpd + FastCGI. Now I randomly get the following exception (neither the place nor the time where it appears seem to be predictable). Since it's random, and it appears only after switching to FastCGI, I assume ...
2008/12/26
[ "https://Stackoverflow.com/questions/393637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5475/" ]
Possible solution: <http://groups.google.com/group/django-users/browse_thread/thread/2c7421cdb9b99e48> > > Until recently I was curious to test > this on Django 1.1.1. Will this > exception be thrown again... surprise, > there it was again. It took me some > time to debug this, helpful hint was > that it only s...
In the end I switched back to Apache + mod\_python (I was having other random errors with fcgi, besides this one) and everything is good and stable now. The question still remains open. In case anybody has this problem in the future and solves it they can record the solution here for future reference. :)
16,053
43,893,431
I am new to python(version 3.4.) and I am wondering how I can make a code similar to this one: ``` #block letters B1 = ("BBBB ") B2 = ("B B ") B3 = ("B B ") B4 = ("BBBB ") B5 = ("B B ") B6 = ("B B ") B7 = ("BBBB ") B = [B1, B2, B3, B4, B5, B6, B7] E1 = ("EEEEE ") E2 = ("E ") E3 = ("E ") E4 = ("EEE...
2017/05/10
[ "https://Stackoverflow.com/questions/43893431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7991835/" ]
> > **Assumption**: you have **all** the letters constructed and that **all letters have the same number of rows**. > > > In that case you can **construct a dictionary**, like: ``` ascii_art = { 'B': B, 'E': E, 'N': N } ``` of course in real life, you construct a dictionary with all letters, and perhaps spaces,...
First you'd have to manually make the alphabet as you did before, ``` N1 = ("N N") N2 = ("NN N") N3 = ("N N N") N4 = ("N N N") N5 = ("N N N") N6 = ("N NN") N7 = ("N N") N = [N1, N2, N3, N4, N5, N6, N7] ``` Do that for each letter. [a-z] ``` # Now to let user input print your alphabet we will use a dict...
16,063
1,839,567
I have a vector consisting of a point, speed and direction. We will call this vector R. And another vector that only consists of a point and a speed. No direction. We will call this one T. Now, what I am trying to do is to find the shortest intersection point of these two vectors. Since T has no direction, this is prov...
2009/12/03
[ "https://Stackoverflow.com/questions/1839567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/223779/" ]
My math could be a bit rusty, but try this: *p* and *q* are the position vectors, *d* and *e* are the direction vectors. After time *t*, you want them to be at the same place: **(1)** *p+t\*d = q+t\*e* Since you want the direction vector *e*, write it like this **(2)** *e = (p-q)/t + d* Now you don't need the tim...
1. Let's assume that the first point, A, has zero speed. In this case, it should be very simple to find the direction which will give the fastest intersection. 2. Now, A **does** have a speed. We can force it to have zero speed by deducting it's speed vector from the vector of B. Now we can solve as we did in 1. Just ...
16,068
34,278,955
On the linux system I'm using, the scheduler is not very generous giving cpu time to subprocesses spawned from python's multiprocessing module. When using 4 subprocceses on a 4-core machine, I get around 22% CPU according to `ps`. However, if the subprocesses are child processes of the shell, and not the python program...
2015/12/15
[ "https://Stackoverflow.com/questions/34278955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483516/" ]
I don't believe your benchmarks are executing as independent tasks as you might think they do. You didn't show the code of `function` but I suspect it does some synchronization. I wrote the following benchmark. If I run the script with either the `--fork` or the `--mp` option, I always get 400 % CPU utilization (on my...
Welcome to the CPython Global Interpreter Lock. Your threads show up as distinct processes to the linux kernel (that is how threads are implemented in Linux in general: each thread gets its own process so the kernel can schedule them). So why isn't Linux scheduling more than one of them to run at a time (that is why ...
16,073
49,037,104
So, I am making a login system in python with tkinter and I want it to move to another page after the email and password have been validated. The only way I have found to do this is by using a button click command. I only want it to move on to the next page after the email and password have been validated. Thanks in ad...
2018/02/28
[ "https://Stackoverflow.com/questions/49037104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7698965/" ]
You can split the string and then `Array.includes` to check whether the value exists in the array or not. ```js function check(str, val){ return str.split(", ").includes(val+""); } var str = "1, 13, 112, 12, 1212, 555" console.log(check(str, 12)); console.log(check(str, 121)); console.log(check(str, 1212)); ...
Another possible answer  : ```js var twelve = /(^| )12(,|$)/; var s = "1, 13, 112, 12, 1212, 555"; console.log(twelve.test(s)); // true ``` About the regular expression ---------------------------- Following your comment, let me give you a little help to understand the first line. `/(^| )12(,|$)/` is a regular ex...
16,074
7,598,159
I am trying to access the Amazon Advertising through Python and I created a Python script to automate the authentication process. This file, called amazon.py is located in ~/PROJECT/APP/amazon.py. I want to be able to play around with the API, so I launched python manage.py shell from the ~/PROJECT directory to enter ...
2011/09/29
[ "https://Stackoverflow.com/questions/7598159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971235/" ]
``` int* ptr = (int*)&a; ``` This is dangerous (this itself doesn't invoke UB, though). But this, ``` *ptr = 3; ``` This invokes undefined behavior (UB), because you're attempting to modify the `const` object pointing to by `ptr`. UB means anything could happen. Note that `a` is truly a const object. §7.1.5.1/4 (...
Don't do things like this. It's undefined behavior. If you lie to the compiler, it will get its revenge (c)
16,077
12,961,475
I am looking for a way to parse the following commandline syntax using the argparse module in python3: ``` myapp.py [folder] [[from] to] ``` Meaning: The user may optionally define a folder, which defaults to cwd. Additionally the user may pass up to two integers. If only one number is given, it should be stored in ...
2012/10/18
[ "https://Stackoverflow.com/questions/12961475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1110748/" ]
Use options; that's what they're there for (and what `argparse` is good at parsing). Thus, a syntax like ``` myapp.py [-F folder] [[from] to] ``` would make a lot more sense, and be easier to parse.
I couldn't see a way to do it without using a named argument for folder: ``` # usage: argparsetest2.py [-h] [--folder [FOLDER]] [to] [fr] import argparse import os parser = argparse.ArgumentParser() parser.add_argument('--folder', dest='folder', nargs='?', default=os.getcwd()) parser.add_argument('to', type=int, nar...
16,082
46,341,816
I'm working on a Python project using PyCharm and now I need to generate the corresponding API documentation. I'm documenting the code methods and classes using `docstrings`. I read about Sphinx and Doxygen, with Sphinx being the most recommended right now. I tried to configure Sphinx whitin PyCharm but I had no luck i...
2017/09/21
[ "https://Stackoverflow.com/questions/46341816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8078050/" ]
Just solved excatly the same problem Juan. **Sphinx unfortunately is not a fully automated doc generator from code comments** like doxygen, jautodoc etc. As in the link mentioned in mzjn's [comment](https://stackoverflow.com/a/25555982/1980180) some steps are necessary for a proper work. As I see you are working on P...
Prior to `make html` you should do the reading the apidoc comments from your code and creating .rst files. You should run something like this from your project root folder: ``` sphinx-apidoc . -o ./docs -f tests ``` This will rewrite .rst files (hence `-f`) in `docs` folder and ignore to do the apidoc reading in `te...
16,085
13,788,349
Reading Guido's infamous answer to the question [Sorting a million 32-bit integers in 2MB of RAM using Python](http://neopythonic.blogspot.fr/2008/10/sorting-million-32-bit-integers-in-2mb.html), I discovered the module [heapq](http://docs.python.org/2.7/library/heapq.html). I also discover I didn't understand jack ab...
2012/12/09
[ "https://Stackoverflow.com/questions/13788349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
`heapq` implements [binary heaps](https://en.wikipedia.org/wiki/Binary_heap), which are a partially sorted data structure. In particular, they have three interesting operations: * `heapify` turns a list into a heap, in-place, in O(*n*) time; * `heappush` adds an element to the heap in O(lg *n*) time; * `heappop` retri...
For example: you have a set of 1000 floating-point number. You want to repeatedly remove the smallest item from the set and replace it with a random number between 0 and 1. The fastest way to do it is with the heapq module: ``` heap = [0.0] * 1000 # heapify(heap) # usually you need this, but not if the list is initi...
16,086
51,347,732
I am trying to replace a block of text which is spanning over multiple lines of text file using python. Here is how my input file looks like. input.txt: ``` ABCD abcd ( . X (x), .Y (y) ); ABCD1 abcd1 ( . X1 (x1), .Y1 (y1) ); ``` I am reading the above file with the below code and trying to replace the tex...
2018/07/15
[ "https://Stackoverflow.com/questions/51347732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3843912/" ]
Running `oc whoami --show-console` returns the link to the console app.
Thanks, `oc login` helped me to get the web console url
16,087
34,394,650
I have a python's pexpect code where it sends some commands listed in a file. Say I store some commands in a file named `commandbase` ``` ls -l /dev/ ls -l /home/ramana ls -l /home/ramana/xyz ls -l /home/ramana/xxx ls -l /home/ramana/xyz/abc ls -l /home/ramana/xxx/def ls -l /home/dir/ ``` and so on. Observe here t...
2015/12/21
[ "https://Stackoverflow.com/questions/34394650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4894197/" ]
This can be done with a list comprehension... ``` paths = ['/dev/', '/dev/ramana/', ...] command = 'ls -l' commandsandpaths = [command + ' ' + x for x in paths] ``` `commandsandpaths` will be a list with... ``` ls -l /dev/ ls -l /dev/ramana/ ``` Personally, I prefer to use string formatting rather than string con...
Your requirements are a little more complicated than it appears at first glance. Below I have adopted a convention to use lists `[...]` to indicate things to concatenate, and tuples `(...)` for things to choose from, i.e. optionals. Your list of path names can now be expressed as this:- ``` database = ( 'dev', ...
16,090
35,205,173
I am trying to learn numpy array slicing. But this is a syntax i cannot seem to understand. What does `a[:1]` do. I ran it in python. ``` a = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]) a = a.reshape(2,2,2,2) a[:1] ``` **Output:** ``` array([[[ 5, 6], [ 7, 8]], [[13, 14], [15,...
2016/02/04
[ "https://Stackoverflow.com/questions/35205173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1939166/" ]
The commas in slicing are to separate the various dimensions you may have. In your first example you are reshaping the data to have 4 dimensions each of length 2. This may be a little difficult to visualize so if you start with a 2D structure it might make more sense: ``` >>> a = np.arange(16).reshape((4, 4)) >>> a ...
It might pay to explore the `shape` and individual entries as we go along. Let's start with ``` >>> a = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]) >>> a.shape (16, ) ``` This is a one-dimensional array of length 16. Now let's try ``` >>> a = a.reshape(2,2,2,2) >>> a.shape (2, 2, 2, 2) ``` It's a multi-d...
16,092
62,719,356
Hi i'm codding a bot in python to the zoom download api, but but now i'm going through this. I need to know the name of the file I am downloading through that URL, but inside the URL it does not contain the name of the file. It is just downloaded automatically through it. Ex of an download URL: <https://zztop.us/rec/...
2020/07/03
[ "https://Stackoverflow.com/questions/62719356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13860212/" ]
with the help of Mostafa Labib I managed to get where I wanted, here is the code working for those who want to know the filename of a file downloaded by download\_url of zoom ``` from urllib.request import urlopen from os.path import basename url="https://zztop.us/rec/download/6cUsfr5pjo3GNfGtgSDAv9xIXbzy9vms0iRKq6YNn...
You can use urllib to parse the link then get the filename from the headers. ``` from urllib.request import urlopen url = "https://zztop.us/rec/download/6cUsf-r5pjo3GNfGtgSDAv9xIXbzy9vms0iRKq6YNn0m8UHILNlKiMrMWMecDkmKyv5o675Hp1ZrKPF16" response = urlopen(url) filename = response.headers.get_filename() print(filename)...
16,094
11,459,861
I am a molecular biologist using Biopython to analyze mutations in genes and my problem is this: I have a file containing many different sequences (millions), most of which are duplicates. I need to find the duplicates and discard them, keeping one copy of each unique sequence. I was planning on using the module editd...
2012/07/12
[ "https://Stackoverflow.com/questions/11459861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1513202/" ]
If you want to filter out exact duplicates, you can use the `set` Python built-in type. As an example : ``` a = ["tccggatcc", "actcctgct", "tccggatcc"] # You have a list of sequences s = set(a) # Put that into a set ``` `s` is then equal to `['tccggatcc', 'actcctgct']`, without duplicates.
Don't be afraid of files! ;-) I'm posting an example by assuming the following: 1. its a text-file 2. one sequence per line - ``` filename = 'sequence.txt' with open(filename, 'r') as sqfile: sequences = sqfile.readlines() # now we have a list of strings #discarding the duplicates: uniques = list(set(sequences)...
16,095
2,396,382
this is the script >> ``` import ClientForm import urllib2 request = urllib2.Request("http://ritaj.birzeit.edu") response = urllib2.urlopen(request) forms = ClientForm.ParseResponse(response, backwards_compat=False) response.close() form = forms[0] print form sooform = str(raw_input("Form Name: ")) username = str(ra...
2010/03/07
[ "https://Stackoverflow.com/questions/2396382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288208/" ]
The only `<form>` tag in the HTML served at that URL (save it to a file and look for yourself!) is: ``` <form method="GET" action="http://www.google.com/u/ritaj"> ``` which does a customized Google search and has nothing to do with logging in (plus, for some reason, ClientForm has some problem identifying that speci...
the actual address seems to be using `https` instead of `http`. check the [urllib2](http://docs.python.org/library/urllib2.html) doc to see if it handles HTTPS( i believe you need ssl)
16,103
25,240,268
Say for example, I have two text files containing the following: **File 1** > > "key\_one" = "String value for key one" > > "key\_two" = "String value for key two" > > // COMMENT // > > "key\_three" = "String value for key two" > > > **File 2** > > // COMMENT > > "key\_one" = "key\_one" > > ...
2014/08/11
[ "https://Stackoverflow.com/questions/25240268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1813167/" ]
There is a quote that I heard from somewhere: "If you have a problem and you try to solve it with regular expressions, you now have two problems". What you want to achieve can be easily done with just a few inbuilt Python string methods such as `startswith()` and `split()`, without using any regex. In short you can d...
``` import pprint ``` def get\_values(f): file1 = open(f,"r").readlines() values = {} for line in file1: if line[:2] !="//" and "=" in line: #print line key, value = line.split("=") #print key, value values[key]=value ``` return values ``` def replace\_values(v1, v2): for key in v1: v = v1[key] if key in...
16,104
50,201,607
TL;DR When updating from CMake 3.10 to CMake 3.11.1 on archlinux, the following configuration line: find\_package(Boost COMPONENTS python3 COMPONENTS numpy3 REQUIRED) leads to CMake linking against 3 different libraries ``` -- Boost version: 1.66.0 -- Found the following Boost libraries: -- python3 -- numpy3 -- ...
2018/05/06
[ "https://Stackoverflow.com/questions/50201607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7141288/" ]
This bug is due to an invalid dependency description in `FindBoost.cmake` ``` set(_Boost_NUMPY_DEPENDENCIES python) ``` This has been fixed at <https://github.com/Kitware/CMake/commit/c747d4ccb349f87963a8d1da69394bc4db6b74ed> Please use latest one, or you can rewrite it manually: ``` set(_Boost_NUMPY_DEPENDENC...
[CMake 3.10 does not properly support Boost 1.66](https://stackoverflow.com/a/42124857/2799037). The Boost dependencies are hard-coded and if they chance, CMake has to adopt. Delete the build directory and reconfigure. The configure step uses cached variables which prevents re-detection with the newer routines.
16,109
7,092,407
Im working a mongodb database using pymongo python module. I have a function in my code which when called updates the records in the collection as follows. ``` for record in coll.find(<some query here>): #Code here #... #... coll.update({ '_id' : record['_id'] },record) ``` Now, if i modify the code as f...
2011/08/17
[ "https://Stackoverflow.com/questions/7092407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/898562/" ]
Increase your memory buffer size `php_value memory_limit 64M` in your .htacess or `ini_set('memory_limit','64M');` in your php file
It depends your implimentation. last time when I was working on csv file with more then 500000 records, I got the same message. Later I introduce classes and try to close the open objects. it reduces it memeory consumption. if you are opening an image and editing it. it means it is loading in a memory. in that case siz...
16,110
41,504,340
This question [explains](https://stackoverflow.com/questions/7300321/how-to-use-pythons-pip-to-download-and-keep-the-zipped-files-for-a-package) how to make pip download and save packages. If I follow this formula, Pip will download wheel (.whl) files if available. ``` (venv) [user@host glances]$ pip download -d whee...
2017/01/06
[ "https://Stackoverflow.com/questions/41504340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1179137/" ]
According to `pip install -h`: > > --no-use-wheel Do not Find and prefer wheel archives when searching indexes and find-links locations. DEPRECATED in favour of --no-binary. > > > And > > --no-binary Do not use binary packages. Can be supplied multiple times, and each time adds to the existing value. Accepts ei...
use `pip download --no-binary=:all: -r requirements.txt` According to the pip documentation: **--no-binary:** > > Do not use binary packages. Can be supplied multiple times, and each > time adds to the existing value. Accepts either :all: to disable all > binary packages, :none: to empty the set, or one or more ...
16,115
6,022,450
I'm using Scrapy to scrape a website. The item page that I want to scrape looks like: <http://www.somepage.com/itempage/&page=x>. Where `x` is any number from `1` to `100`. Thus, I have an `SgmlLinkExractor` Rule with a callback function specified for any page resembling this. The website does not have a listpage with...
2011/05/16
[ "https://Stackoverflow.com/questions/6022450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648121/" ]
You could list all the known URLs in your [`Spider`](http://doc.scrapy.org/topics/spiders.html#spiders) class' [start\_urls](http://doc.scrapy.org/topics/spiders.html#scrapy.spider.BaseSpider.start_urls) attribute: ``` class SomepageSpider(BaseSpider): name = 'somepage.com' allowed_domains = ['somepage.com'] ...
If it's just a one time thing, you can create a local html file `file:///c:/somefile.html` with all the links. Start scraping that file and add `somepage.com` to allowed domains. Alternately, in the parse function, you can return a new Request which is the next url to be scraped.
16,116
58,635,279
I have created a brand new [Python repository](https://github.com/neuropsychology/NeuroKit) based on a cookie-cutter template. Everything looks okay, so I am trying now to set the testing and testing coverage using travis and codecov. I am new to pytest but I am trying to do things right. After looking on the internet,...
2019/10/31
[ "https://Stackoverflow.com/questions/58635279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4198688/" ]
1) create pytest.ini file in your project directory and add the following lines ``` [pytest] testpaths = tests python_files = *.py python_functions = test_* ``` 2) create .coveragerc file in project directory and add the following lines ``` [report] fail_under = 90 show_missing = True ``` 3) pytest for code cover...
Looks like you're missing `coverage` on your installs. You have it on scripts but it might not be running. Try adding `pip install coverage` in your travis.yml file. Have a go at this too: [codecov](https://github.com/codecov/example-python)
16,117
44,492,238
I am learning python & trying to scrape a website, having 10 listing of properties on each page. I want to extract information from each listing on each page. My code for first 5 pages is as follows :- ``` import requests from bs4 import BeautifulSoup urls = [] for i in range(1,5): pages = "http://www.realcommer...
2017/06/12
[ "https://Stackoverflow.com/questions/44492238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7961265/" ]
There is one problem in your code is that you declared the variable "urls" twice. You need to update the code like below: ``` import requests from bs4 import BeautifulSoup urls = [] for i in range(1,6): pages = "http://www.realcommercial.com.au/sold/property-offices-retail-showrooms+bulky+goods-land+development-...
Use headers in the code and use string concatenation instead of .format(i) The code looks like this ``` import requests from bs4 import BeautifulSoup urls = [] for i in range(1,6): pages = 'http://www.realcommercial.com.au/sold/property-offices-retail-showrooms+bulky+goods-land+development-hotel+leisure-medical...
16,118
21,778,187
I would like to find text in file with regular expression and after replace it to another name. I have to read file line by line at first because in other way re.match(...) can`t find text. My test file where I would like to make modyfications is (no all, I removed some code): ``` //... #include <boost/test/included/...
2014/02/14
[ "https://Stackoverflow.com/questions/21778187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693143/" ]
Looks like this isn't possible to do. To cut down on duplicate code, simply declare the error handling function separately and reuse it inside the response and responseError functions. ``` $httpProvider.interceptors.push(function($q) { var handleError = function (rejection) { ... } return { response...
To add to this answer: rejecting the promise in the response interceptor DOES do something. Although one would expect it to call the responseError in first glance, this would not make a lot of sense: the request is fulfilled with succes. But rejecting it in the response interceptor will make the caller of the promise ...
16,120
49,773,418
after writing import tensorflow\_hub, the following error emerges: ``` class LatestModuleExporter(tf.estimator.Exporter): ``` AttributeError: module 'tensorflow.python.estimator.estimator\_lib' has no attribute 'Exporter' I'm using python 3.6 with tensorflow 1.7 on Windows 10 thanks!
2018/04/11
[ "https://Stackoverflow.com/questions/49773418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2393805/" ]
You can reinstall TensorFlow\_hub: ``` pip install ipykernel pip install tensorflow_hub ```
I believe your python3 runtime is not really running with tensorflow 1.7. That attribute exists since tensorflow 1.4. I suspect some mismatch between python2/3 environment, mismatch installing with pip/pip3 or an issue with installing both tensorflow and tf-nightly pip packages. You can double check with: ``` $ pytho...
16,123
15,448,584
I have 2 lists `a = [2, 6, 12, 13, 1, 4, 5]` and `b = [12, 1]`. Elements in list `b` are a subset of list `a`. From the above pair of lists, I need to create a list of tuples as following : ``` [(12,6),(12,2),(1,13),(1,12),(1,6),(1,2)] ``` Basically, at the point of intersection of list `b` and list `a`, so from ...
2013/03/16
[ "https://Stackoverflow.com/questions/15448584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1923226/" ]
You typically need to use `glibtool` and `glibtoolize`, since `libtool` already exists on OS X as a binary tool for creating Mach-O dynamic libraries. So, that's how MacPorts installs it, using a program name transform, though the port itself is still named 'libtool'. Some `autogen.sh` scripts (or their equivalent) wi...
I hope my answer is not too naive. I am a noob to OSX. [brew](http://brew.sh/) install libtool solved a similar issue for me.
16,129
68,438,620
I am trying to build and run the sample `python` application from AWS SAM. I just installed python, below is what command lines gives.. ``` D:\Udemy Work>python Python 3.9.6 (tags/v3.9.6:db3ff76, Jun 28 2021, 15:26:21) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more infor...
2021/07/19
[ "https://Stackoverflow.com/questions/68438620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1379286/" ]
You basically need unpivot or melt: <https://pandas.pydata.org/docs/reference/api/pandas.melt.html> ``` pd.melt(df, id_vars=['Number','From','To'], value_vars = ['D1_value','D2_value'])\ .rename({'variable':'Type'},axis=1)\ .dropna(subset=['value'],axis=0) ```
You can also use `pd.wide_to_long`, after reordering the column positions: ``` temp = df.rename(columns = lambda col: "_".join(col.split("_")[::-1]) if col.endswith("value") else col) pd.wide_to_long(temp, stubnames = 'value', i=['Number', 'Fro...
16,135
28,967,976
I'm reading a pcap file in python using scapy which contains Ethernet packets that have trailer. How can I remove these trailers? P.S: Ethernet packets can not be less than 64 bytes (including FCS).Network adapters add padding zero bytes to end of the packet to overcome this problem. These padding bytes called "Traile...
2015/03/10
[ "https://Stackoverflow.com/questions/28967976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133144/" ]
It seems there is no official way to remove it. This work on frames that have IPv4 as network layer protocol: ``` packet_without_trailer=IP(str(packet[IP])[0:packet[IP].len]) ```
Just use the upper layers and ignore the Ethernet layer: `packet = eval(originalPacket[IP])`
16,136
5,127,860
When I have lots of different modules using the standard python logging module, the following stack trace does little to help me find out where, exactly, I had a badly formed log statement: ``` Traceback (most recent call last): File "/usr/lib/python2.6/logging/__init__.py", line 768, in emit msg = self.format(r...
2011/02/26
[ "https://Stackoverflow.com/questions/5127860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254704/" ]
The logging module is designed to stop bad log messages from killing the rest of the code, so the `emit` method catches errors and passes them to a method `handleError`. The easiest thing for you to do would be to temporarily edit `/usr/lib/python2.6/logging/__init__.py`, and find `handleError`. It looks something like...
Rather than editing installed python code, you can also find the errors like this: ``` def handleError(record): raise RuntimeError(record) handler.handleError = handleError ``` where handler is one of the handlers that is giving the problem. Now when the format error occurs you'll see the location.
16,137
52,629,106
Hello everyone I have a file of which consist of some random information but I only want the part that is important to me. ``` name: Zack age: 17 As Mixed: Zack:17 Subjects opted : 3 Subject #1: Arts name: Mike age: 15 As Mixed: Mike:15 Subjects opted : 3 Subject #1: Arts ``` Above is a example of my text file I wan...
2018/10/03
[ "https://Stackoverflow.com/questions/52629106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9606164/" ]
You can split the data at the `:` and grab only `As Mixed` parameter ``` content = [i.strip('\n').split(': ') for i in open('filename.txt')] results = [b for a, b in content if a.startswith('As Mixed')] ``` Output: ``` ['Zack:17', 'Mike:15'] ``` To write the results to a file: ``` with open('filename.txt', 'w') ...
Try this ``` import re found = [] match = re.compile('(Mike|Zack):(\w*)') with open('/hope/ninja/Destop/raw.twt', "r") as raw: for rec in raw: found.extend(match.find_all(rec)) print(found) #output: [('Mike', '15'), ('Zack', '17')] ``` This uses regular expressions to find the value needed, basically `(...
16,147
31,112,523
I am using this python script to download OSM data and convert it to an undirected networkx graph: <https://gist.github.com/rajanski/ccf65d4f5106c2cdc70e> However,in the ideal case, I would like to generate a directed graph from it in order to refelct the directionality of the osm street network. First of all, can y...
2015/06/29
[ "https://Stackoverflow.com/questions/31112523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2772305/" ]
The order of the nodes only matters if the way is tagged with *[oneway](https://wiki.openstreetmap.org/wiki/Key:oneway)=yes* or *oneway=-1*. Otherwise the way is bidirectional. This applies only for vehicles of course. The only exception is *[highway=motorway](https://wiki.openstreetmap.org/wiki/Tag:highway%3Dmotorway)...
OK, I updated my script in order to enable directionality: <https://gist.github.com/rajanski/ccf65d4f5106c2cdc70e>
16,148
45,382,324
I will try to be very specific and informative. I want to create a Dockerfile with all the packages that are used in geosciences for the good of the geospatial/geoscientific community. The Dockerfile is built on top of the [scipy-notebook](https://github.com/jupyter/docker-stacks/tree/master/scipy-notebook) docker-stac...
2017/07/28
[ "https://Stackoverflow.com/questions/45382324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5361345/" ]
> > looks like it would work in the older groovy Jenkinsfiles > > > you can use the `script` step to enclose a block of code, and, inside this block, declarative pipelines basically act like scripted, so you can still use the technique described in the answer you referenced. welcome to stackoverflow. i hope you e...
I was facing the same issue and found that instead of using the following avoids 'Requires approval of the script in my Jenkins server at Jenkins > Manage jenkins > In-process Script Approval'. Instead of: env['setup\_build\_number'] = setupResult.getNumber() (from code mentioned in Solution above) Use this: env.setu...
16,149
26,154,104
I'm trying to run the following Cypher query in neomodel: ``` MATCH (b1:Bal { text:'flame' }), (b2:Bal { text:'candle' }), p = shortestPath((b1)-[*..15]-(b2)) RETURN p ``` which works great on neo4j via the server console. It returns 3 nodes with two relationships connecting. However, when I attempt the following ...
2014/10/02
[ "https://Stackoverflow.com/questions/26154104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4101066/" ]
Ok, I figured it out. I used the tutorial [here]( based on @nigel-small 's answer. ``` from py2neo import cypher session = cypher.Session("http://localhost:7474") tx = session.create_transaction() tx.append("START beginning=node(3), end=node(16) MATCH p = shortestPath(beginning-[*..500]-end) RETURN p") tx.execute() ...
The error message you provide is specific to neomodel and looks to have been raised as there is not yet any support for inflating py2neo Path objects in neomodel. This should however work fine in raw py2neo as paths are fully supported, so it may be worth trying that again. Py2neo certainly wouldn't raise an error fro...
16,150
70,929,680
I have a dataframe ``` import pandas as pd import numpy as np df1 = pd.DataFrame.from_dict( {"col1": [0, 0, 0, 0, 0], "col2": ["15", [10,15,20], "30", [20, 25], np.nan]}) ``` which looks like this | col1 | col2 | | --- | --- | | 0 | "15" | | 0 | [10,15,20] | | 0 | "30" | | 0 | [20,25] | | 0 | NaN | For co...
2022/01/31
[ "https://Stackoverflow.com/questions/70929680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15815734/" ]
Let us try `explode` then `groupby` with `max` ``` out = df1.col2.explode().groupby(level=0).max() Out[208]: 0 15 1 20 2 30 3 25 4 NaN Name: col2, dtype: object ```
``` import pandas as pd import numpy as np df1 = pd.DataFrame.from_dict( {"col1": [0, 0, 0, 0, 0], "col2": ["15", [10,15,20], "30", [20, 25], np.nan]}) res=df1['col2'] lis=[] for i in res: if type(i)==str: i=int(i) if type(i)==list: i=max(i) lis.append(i) else: lis.ap...
16,151
28,708,752
I apologize for my ignorance of how python handles strings in advance. I have a .txt file that is at least 1000 lines long. It looks something like below ``` :dodge 1 6 some description string of unknown length E7 8 another description string 3445 0 oil temp something description voltage over limit etc :ford AF 4 de...
2015/02/25
[ "https://Stackoverflow.com/questions/28708752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2884999/" ]
You simply need to split twice on whitespace and join the string, you don't need a regex for a simple repeating pattern: ``` with open("testDTC.txt") as f: for line in f: if line.strip() and not line.startswith(":"): spl = line.split(None,2) print("{} ;{}".format(" ".join(spl[:2]),s...
Based on your example, it seems that in your second column you have a number or numbers separated by spaces, e.g. `8`, `6` followed by some description in third colum which seem not to have any numbers. If this is the case in general, not only for this example, you can use this fact to search for the number separated b...
16,154
42,409,365
I am trying to check a website for specific .js files and image files as part of a regular configuration management check. I am using python and selenium. My code is: ``` #!/usr/bin/env python #import modules required for the test to run import time from pyvirtualdisplay import Display from selenium import webdriver ...
2017/02/23
[ "https://Stackoverflow.com/questions/42409365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7609361/" ]
You need to use ``` for i in page: print(i.get_attribute('src')) ``` This should print `JavaScript` file name like `https://www.google-analytics.com/analytics.js` Also you should note that some `<script>` tags could contain just `JavaScript` code, but not reference to remote file. If you want to get this code y...
as you are using phantomJS, why not use its scripts to capture these data. You can use `netlog.js` to capture all network data loaded for a given page in HAR format. Later use a `python-HAR parser` to list down all your .js or img files. command line: ``` phantomjs --cookies-file=/tmp/foo netlog.js https://google.com...
16,161
62,772,454
If given a year-week range e.g, start\_year, start\_week = (2019,45) and end\_year, end\_week = (2020,15) In python how can I check if Year-Week of interest is within the above range of not? For example, for Year = 2020 and Week = 5, I should get a 'True'.
2020/07/07
[ "https://Stackoverflow.com/questions/62772454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6870708/" ]
Assuming all Year-Week pairs are well-formed (so there's no such thing as `(2019-74)` you can just check with: ``` start_year_week = (2019, 45) end_year_week = (2020, 15) under_test_year_week = (2020, 5) in_range = start_year_week <= under_test_year_week < end_year_week # True ``` Python does tuple comparison by f...
You can parse year and week to a `datetime` object. If you do the same with your test-year /-week, you can use comparison operators to see if it falls within the range. ``` from datetime import datetime start_year, start_week = (2019, 45) end_year, end_week = (2020, 15) # start date, beginning of week date0 = datet...
16,162
45,403,597
trying to deploy my app to uwsgi server my settings file: ``` STATIC_ROOT = "/home/root/djangoApp/staticRoot/" STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/home/root/djangoApp/static/', ] ``` and url file: ``` urlpatterns = [ #urls ] + static(settings.STATIC_URL, d...
2017/07/30
[ "https://Stackoverflow.com/questions/45403597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8375888/" ]
The two paths you have in STATICFILES\_DIRS are the same. So Django copies the files from one of them, then goes on to the second and tries to copy them again, only to see the files already exist. Remove one of those entries, preferably the second.
do you have more than one application? If so, you should put any file on a subdirectory with a unique name (like the app name for example). collectstatic collects files from all the /static/ subdirectories, and if there is a duplication, it throw this error.
16,165
72,664,087
I'm using python3 tkinter to build a small GUI on Linux Centos I have my environment set up with all the dependencies installed (cython, numpy, panda, etc) When I go to install tkinter ``` pip3 install tk $ python3 Python 3.6.8 (default, Nov 16 2020, 16:55:22) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux Type "he...
2022/06/17
[ "https://Stackoverflow.com/questions/72664087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11760778/" ]
> > Why is 'pip install tk' not being recognized as a valid installation of tkinter but 'sudo yum install python3-tkinter' works? > > > Because `pip install tk` installs an old package called tensorkit, not tkinter. You can't install tkinter with pip.
so i don't know if centOS uses apt put you can try first uninstalling tinkter with pip and then use apt to install it ``` sudo apt-get install python3-tk ```
16,166
73,584,455
I am trying to create a diverging dot plot with python and I am using seaborn relplot to do the small multiples with one of the columns. The datasouce is MakeoverMonday 2018w18: [MOM2018w48](https://data.world/makeovermonday/2018w48) I got this far with this code: ``` sns.set_style("whitegrid") g=sns.relplot(x=cost ...
2022/09/02
[ "https://Stackoverflow.com/questions/73584455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3433875/" ]
Like most query interfaces, the `Query()` function can only execute one SQL statement at a time. MySQL's prepared statements don't work with multi-query. You could solve this by executing the `SET` statement in one call, then the `SELECT` in a second call. But you'd have to take care to ensure they are executed on the...
Unless drivers implement a special interface, the query is prepared on the server first before execution. Bindvars are therefore database specific: * MySQL: uses the ? variant shown above * PostgreSQL: uses an enumerated $1, $2, etc bindvar syntax * SQLite: accepts both ? and $1 syntax * Oracle: uses a :name syntax * ...
16,167
40,322,718
I'm new to getting data using API and Python. I want to pull data from my trading platform. They've provided the following instructions: <http://www.questrade.com/api/documentation/getting-started> I'm ok up to step 4 and have an access token. I need help with step 5. How do I translate this request: ``` GET /v1/a...
2016/10/29
[ "https://Stackoverflow.com/questions/40322718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4838024/" ]
As you point out, after step 4 you should have received an access token as follows: ``` { “access_token”: ”C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp”, “token_type”: ”Bearer”, “expires_in”: 300, “refresh_token”: ”aSBe7wAAdx88QTbwut0tiu3SYic3ox8F”, “api_server”: ”https://api01.iq.questrade.com” } ``` To mak...
Improving a bit on Peter's reply (Thank you Peter!) start by using the token you got from the QT website to obtain an access\_token and get an api\_server assigned to handle your requests. ``` # replace XXXXXXXX with the token given to you in your questrade account import requests r = requests.get('https://login.que...
16,170
51,750,967
[![enter image description here](https://i.stack.imgur.com/qpDFX.jpg)](https://i.stack.imgur.com/qpDFX.jpg)I'm trying to control a relay board (USB RLY08) using a section of python code I found online (<https://github.com/jkesanen/usbrly08/blob/master/usbrly08.py>). It is currently returning an error which I'm not sure...
2018/08/08
[ "https://Stackoverflow.com/questions/51750967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4153219/" ]
You are getting this error probably because **pyserial** module is not installed on your system. Try installing pyserial package from PyPi index using below command : ``` python -m pip install pyserial ```
you need to install pyserial e.g. with ``` pip install pyserial ```
16,171
30,316,639
I am looking for a way to calculate a square root with an arbitrary precision (something like 50 digits after the dot). In python, it is easily accessible with [Decimal](https://docs.python.org/2/library/decimal.html): ``` from decimal import * getcontext().prec = 50 Decimal(2).sqrt() # and here you go my 50 digits ...
2015/05/19
[ "https://Stackoverflow.com/questions/30316639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090562/" ]
This is my own implementation of square root calculation. While waiting for answers, I decided to give [methods of computing square roots](http://en.wikipedia.org/wiki/Methods_of_computing_square_roots) a try. It has a whole bunch of methods but at the very end I found a link to a [Square roots by subtraction](http://w...
Adding precision ---------------- There is probably a solution in go but as I don't code in go, here is a general solution. For instance if your selected language doesn't provide a solution to handle the precision of floats (already happened to me): If your language provides you N digits after the dot, you can, in t...
16,173
51,395,535
I'm trying to get my head around \*\*kwargs in python 3 and am running into a strange error. Based on [this post](https://stackoverflow.com/questions/1769403/understanding-kwargs-in-python) on the matter, I tried to create my own version to confirm it worked for me. ``` table = {'Person A':'Age A','Person B':'Age B','...
2018/07/18
[ "https://Stackoverflow.com/questions/51395535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8032508/" ]
call kw function with `kw(**table)` Python 3 Doc: [link](https://docs.python.org/3.2/glossary.html)
There's no need to make `kwargs` a variable keyword argument here. By specifying `kwargs` with `**` you are defining the function with a variable number of keyword arguments but no positional argument, hence the error you're seeing. Instead, simply define your `kw` function with: ``` def kw(kwargs): ```
16,174
66,204,201
I'm trying to install pymatgen in Google colab via the following command: ``` !pip install pymatgen ``` This throws the following error: ``` Collecting pymatgen Using cached https://files.pythonhosted.org/packages/06/4f/9dc98ea1309012eafe518e32e91d2a55686341f3f4c1cdc19f1f64cb33d0/pymatgen-2021.2.14.tar.gz ...
2021/02/15
[ "https://Stackoverflow.com/questions/66204201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15211978/" ]
You will need to validate within the addNewUser method. And then `throw` an exception when your validate hits. Example ```java if(username.length > 10) { throw new Exception("Username is too long"); } ``` it will then be catched by your try-catch statement.
There are a few things to consider here. With a try-catch block you can manage exceptions that occur in your program flow. When writing a program it's a good idea to make it as clear as possible so that other people reading it later can understand it better. To that end, consider refactoring the methods. For example ...
16,179
16,536,071
I was working on these functions (see [this](https://stackoverflow.com/questions/16525224/how-to-breakup-a-list-of-list-in-a-given-way-in-python)): ``` def removeFromList(elementsToRemove): def closure(list): for element in elementsToRemove: if list[0] != element: return ...
2013/05/14
[ "https://Stackoverflow.com/questions/16536071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2338725/" ]
Use `copy.deepcopy`: ``` from copy import deepcopy new_list = deepcopy([[1], [1, 2], [1, 2, 3]]) ``` Demo: ``` >>> lis = [[1], [1, 2], [1, 2, 3]] >>> new_lis = lis[:] # creates a shallow copy >>> [id(x)==id(y) for x,y in zip(lis,new_lis)] [True, True, True] #inner lists are st...
both with `list(my_list)` and `my_list[:]` you get a shallow copy of the list. ``` id(copy_my_list[0]) == id(my_list[0]) # True ``` so use `copy.deepcopy` to avoid your problem: ``` copy_my_list = copy.deepcopy(my_list) id(copy_my_list[0]) == id(my_list[0]) # False ```
16,181
29,813,423
the below python gui code i am trying to select the values from the drop down menu buttons(graph and density) and trying to pass them as command line arguments to os.system command in the readfile() function as shown below but I am having a problem in passing the values I have selected from the drop down menu to os.sys...
2015/04/23
[ "https://Stackoverflow.com/questions/29813423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2014111/" ]
It is easy to implement with [functools.partial](https://docs.python.org/2/library/functools.html#functools.partial) - apply needed value to your function for each button. Here is a sample: ``` from functools import partial import Tkinter as tk BTNLIST = [0.0, 0.1, 0.2] def btn_clicked(payload=None): """Just pri...
The way you have it, `graph` and `density` are local variables to `graphselected()` and `buttonClicked()`. Therefore, `readfile()` can never access these variables unless you declare them as global in all three functions. Then you want to format a string to incorporate the values in `graph` and `density`. You can do t...
16,184
6,958,833
I'm trying to insert a string that was received as an argument into a sqlite db using python: ``` def addUser(self, name): cursor=self.conn.cursor() t = (name) cursor.execute("INSERT INTO users ( unique_key, name, is_online, translate) VALUES (NULL, ?, 1, 0);", t) s...
2011/08/05
[ "https://Stackoverflow.com/questions/6958833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/752462/" ]
You need this: ``` t = (name,) ``` to make a single-element tuple. Remember, it's **commas** that make a tuple, not brackets!
Your `t` variable isn't a tuple, i think it is a 7-length string. To make a tuple, don't forget to put a trailing coma: ``` t = (name,) ```
16,185
41,196,390
I have my `index.py` in `/var/www/cgi-bin` My `index.py` looks like this : ``` #!/usr/bin/python print "Content-type:text/html\r\n\r\n" print '<html>' print '<head>' print '<title>Hello Word - First CGI Program</title>' print '</head>' print '<body>' print '<h2>Hello Word! This is my first CGI program</h2>' print '<...
2016/12/17
[ "https://Stackoverflow.com/questions/41196390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3405554/" ]
Try this : Enable `CGI` `a2enmod cgid` `chmod a+x /var/www/cgi-bin/index.py` but check `cgi-bin` directory owner is `wwwdata` ? Need a `directory` definition on every `Virtualhost` ! Some time required `restart` for killing all `apache` threads ! ``` DocumentRoot /var/www/htdocs #A include B if owner are same !...
use this file to run cgi script: ``` import cgi; import cgitb;cgitb.enable() ```
16,186
19,090,032
I need to scrape career pages of multiple companies(with their permission). Important Factors in deciding what do I use 1. I would be scraping around 2000 pages daily, so need a decently fast solution 2. Some of these pages populate data via ajax after page is loaded. 3. My webstack is Ruby/Rails with MySql etc. 4. ...
2013/09/30
[ "https://Stackoverflow.com/questions/19090032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1549934/" ]
The real benefit of closures and higher-order functions is that they can represent what the programmer sometimes has in mind. If you as the programmer find that what you have in mind is a piece of code, a function, an instruction on how to compute something (or do something), then you should use a closure for this. If...
With a closure, one can save the `self` variable. In particular, when there are many variables to be passed, a closure could be more readable. ``` class Incr: """a class that increments internal variable""" def __init__(self, i): self._i = i def __call__(self): self._i = (self._i + 1) % 10 ...
16,187
43,190,221
I have a training file in the following format: > > 0.086, 0.4343, 0.4212, ...., class1 > > > 0.086, 0.4343, 0.4212, ...., class2 > > > 0.086, 0.4343, 0.4212, ...., class5 > > > Where, each row is a one-dimensional vector and the last column is the class in which that vector represents. We can see that a vect...
2017/04/03
[ "https://Stackoverflow.com/questions/43190221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6363322/" ]
This is a pretty straight forward setup. First thing to know: Your labels need to be in "one hot encoding" format. That means, if you have 5 classes, class 1 is represented by the vector [1,0,0,0,0], class 2 by the vector [0,1,0,0,0], and so on. This is standard. Second, you mention that you want multi-class classifi...
From what I understand you have a multi-label problem. Meaning that a sample can belong to more than one classes Take a look at [sigmoid\_cross\_entropy\_with\_logits](https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits) and use that as your loss function. You do not need to use one h...
16,189
69,262,618
So I just watched a tutorial that the author didn't need to `import sklearn` when using `predict` function of pickled model in anaconda environment (sklearn installed). I have tried to reproduce the minimal version of it in Google Colab. If you have a pickled-sklearn-model, the code below works in Colab (sklearn insta...
2021/09/21
[ "https://Stackoverflow.com/questions/69262618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147347/" ]
There's a few questions being asked here, so let's go through them one by one: > > So, how does it work? as far as I understand pickle doesn't depend on scikit-learn. > > > There is nothing particular to scikit-learn going on here. Pickle will exhibit this behaviour for any module. Here's an example with Numpy: ...
*When the model was first pickled*, you had sklearn installed. The pickle file depends on sklearn for its structure, as the class of the object it represents is a sklearn class, and `pickle` needs to know the details of that class’s structure in order to unpickle the object. When you try to unpickle the file without s...
16,190
42,913,788
I'm trying to ask a question on python, so that if the person gets it right, they can move onto the next question. If they get it wrong, they have 3 or so attempts at getting it right, before the quiz moves onto the next question. I thought I solved it with the below program, however this just asks the user make anothe...
2017/03/20
[ "https://Stackoverflow.com/questions/42913788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7735015/" ]
You're stuck in the loop. So put ``` counter = 3 ``` after ``` score += 1 ``` To get out of the loop. ``` score = 0 counter = 0 while counter<3: answer = input("Make your choice >>>> ") if answer == "c": print("Correct!") score += 1 counter = 3 else: print("That is...
You're stucked in the loop, a cleaner way of solving this is using the function break as in: ``` score = 0 counter = 0 while counter < 3: answer = input("Make your choice >>>> ") if answer == "c": print ("Correct!") score += 1 break else: print("That is incorrect. Try Again...
16,191
66,157,729
I have some info store in a MySQL database, something like: `AHmmgZq\n/+AH+G4` We get that using an API, so when I read it in my python I get: `AHmmgZq\\n/+AH+G4` The backslash is doubled! Now I need to put that into a JSON file, how can I remove the extra backslash? **EDIT:** let me show my full code: ``` json_dic...
2021/02/11
[ "https://Stackoverflow.com/questions/66157729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4663446/" ]
Turns out that the badge appears once you open a TeX file. I thought you'd first create a TeX project, then the file.
As you already figured out, the badge appears once you open a TeX file. Keep also in mind that you have to install LaTeX, or update LaTex. I say so because personally I was trying to use `\tableofcontents` but the table wouldn't be generated until the moment I installed texlive using homebrew (`brew install texlive`)
16,192
39,305,286
According to [documentation](https://docs.python.org/3.4/c-api/capsule.html?highlight=capsule), the third argument to `PyCapsule_New()` can specify a destructor, which I assume should be called when the capsule is destroyed. ``` void mapDestroy(PyObject *capsule) { lash_map_simple_t *map; fprintf(stderr, "Ent...
2016/09/03
[ "https://Stackoverflow.com/questions/39305286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333488/" ]
The code above has a reference leak: `pymap = PyCapsule_New()` returns a new object (its refcount is 1), but `Py_BuildValue("O", pymap)` creates a new reference to the same object, and its refcount is now 2. Just `return pymap;`.
`Py_BuildValue("O", thingy)` will just increment the refcount for `thingy` and return it – the docs say that it returns a “new reference” but that is not quite true when you pass it an existing `PyObject*`. If these functions of yours – the ones in your question, that is – are all defined in the same translation unit...
16,193
48,775,587
I am trying to learn python through some basic exercises with my own online store. I have a list of parts that are in-transit to us that we have already ordered, and I have a list of parts that we are currently out of stock of. I want to be able to send a list to the supplier of what we need - but I do not want to crea...
2018/02/13
[ "https://Stackoverflow.com/questions/48775587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6713690/" ]
``` for part in onorder: if (part in onorder) == False ... ``` This does not make sense. Since you are iterating over exactly every element of `onorder`, you will never get a `part` not in `onorder`. Therefore, it is not a miracle that the print statement is not being executed.
Doh! Appropriate code was ``` for part in outofstock: if (part not in onorder): print (part) ``` This way it prints my out of stock items which I need to order, unless they were already on order. I can't believe I overly complicated this for no good reason. Thank you so much for pointing out where I had gone w...
16,194
2,286,633
I have a basic grasp of XML and python and have been using minidom with some success. I have run into a situation where I am unable to get the values I want from an XML file. Here is the basic structure of the pre-existing file. ``` <localization> <b n="Stats"> <l k="SomeStat1"> <v>10</v> ...
2010/02/18
[ "https://Stackoverflow.com/questions/2286633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224476/" ]
``` #!/usr/bin/python from xml.dom.minidom import parseString xml = parseString("""<localization> <b n="Stats"> <l k="SomeStat1"> <v>10</v> </l> <l k="SomeStat2"> <v>6</v> </l> </b> <b n="Levels"> <l k="Level1"> <v>Beginner Level<...
``` level = "Level"+raw_input("Enter level number: ") content= open("xmlfile").read() data= content.split("</localization>") for item in data: if "localization" in item: s = item.split("</b>") for i in s: if """<b n="Levels">""" in i: for c in i.split("</l>"): ...
16,196
48,275,466
I was trying to install [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-install-macos.html) on mac but was facing some challenges as aws command was unable to parse the credential file. So I decided to re-install the whole stuff but facing some issues here again. I am trying `pip uninstall awscli` which...
2018/01/16
[ "https://Stackoverflow.com/questions/48275466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1471314/" ]
You run **pip3** `install awscli` but **pip** `uninstall awscli`. Shouldn't it be **pip3** `uninstall awscli`?
I had a similar issue. And I used the following command to fix it. ``` pip3 install --no-cache-dir awscli==1.14.39 ```
16,200
52,977,914
I'm trying to segment the numbers and/or characters of the following image then converting each individual num/char to text using ocr: [![enter image description here](https://i.stack.imgur.com/rWMEa.png)](https://i.stack.imgur.com/rWMEa.png) This is the code (in python) used: ``` new, contours, hierarchy = cv2.fin...
2018/10/24
[ "https://Stackoverflow.com/questions/52977914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1261829/" ]
As far as I know, most of OpenCV methods for binary images operate `white objects on the black background`. Src: [![enter image description here](https://i.stack.imgur.com/fc1Ld.png)](https://i.stack.imgur.com/fc1Ld.png) Threahold INV and morph-open: [![enter image description here](https://i.stack.imgur.com/oIktF...
Your image is a bit noisy, therefore binarizing it would do the trick. ``` cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY, gray) new, contours, hierarchy = cv2.findContours(gray, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) # cv2.drawContours(gray, contours, -1, 127, 5) digitCnts = [] final = gray.copy() # loop over ...
16,201
9,101,800
So I've been experimenting with numpy and matplotlib and have stumbled across some bug when running python from the emacs inferior shell. When I send the py file to the shell interpreter I can run commands after the code executed. The command prompt ">>>" appears fine. However, after I invoke a matplotlib show command...
2012/02/01
[ "https://Stackoverflow.com/questions/9101800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/752726/" ]
I think there are two ways to do it. 1. Use ipython. Then you can use `-pylab` option. I don't use Fabian Gallina's python.el, but I guess you will need something like this: ``` (setq python-shell-interpreter-args "-pylab") ``` Please read the documentation of python.el. 2. You can manually activate interactive mod...
I think that this might have something to do with the behavior of the show function: > > [matplotlib.pyplot.show(\*args, \*\*kw)](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.show) > > > When running in ipython with its pylab mode, display all figures and > return to the ipython prompt. ...
16,202
58,498,100
I have a complicated nested numpy array which contains list. I am trying to converted the elements to float32. However, it gives me following error: ``` ValueError Traceback (most recent call last) <ipython-input-225-22d2824961c2> in <module> ----> 1 x_train_single.astype(np.float32) Va...
2019/10/22
[ "https://Stackoverflow.com/questions/58498100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1584253/" ]
As your array contains lists of different sizes and nesting depths, I doubt that there is a simple or fast solution. Here is a "get-the-job-done-no-matter-what" approach. It comes in two flavors. One creates arrays for leaves, the other one lists. ``` >>> a array([[list([[[0, 0, 0, 0, 0, 0]], [-1.0], [0]]), l...
if number of columns is fixed then ``` np.array([l.astype(np.float) for l in x_train_single.squeeze()]) ``` But it will remove the redundant dimensions, convert everything into numpy array. Before: (1, 1, 1, 11, 6) After: (11,6)
16,209
18,662,264
from the documents, the urllib.unquote\_plus should replce plus signs by spaces. but when I tried the below code in IDLE for python 2.7, it did not. ``` >>s = 'http://stackoverflow.com/questions/?q1=xx%2Bxx%2Bxx' >>urllib.unquote_plus(s) >>'http://stackoverflow.com/questions/?q1=xx+xx+xx' ``` I also tried doing some...
2013/09/06
[ "https://Stackoverflow.com/questions/18662264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/251024/" ]
`%2B` is the escape code for a *literal* `+`; it is being unescaped entirely correctly. Don't confuse this with the *URL escaped* `+`, which is the escape character for spaces: ``` >>> s = 'http://stackoverflow.com/questions/?q1=xx+xx+xx' >>> urllib.parse.unquote_plus(s) 'http://stackoverflow.com/questions/?q1=xx xx ...
Those aren't spaces, those are actual pluses. A space is %20, which in that part of the URL is indeed equivalent to +, but %2B means a literal plus.
16,211
34,495,839
I saw the following coding gif, which depicts a user typing commands (e.g. `import`) and a pop up message would describe the usage for that command. How can I set up something similar?[![gif depicting python shell with automatic code usage](https://i.stack.imgur.com/7OUwv.gif)](https://i.stack.imgur.com/7OUwv.gif)
2015/12/28
[ "https://Stackoverflow.com/questions/34495839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2636317/" ]
According to the github issues in the repo of that gif, the video was taken using [bpython](http://bpython-interpreter.org) Source: <https://github.com/tqdm/tqdm/issues/67>
Code editors like [`vim`](http://www.vim.org/) (with [`jedi`](https://github.com/davidhalter/jedi-vim) or [`python-mode`](https://github.com/klen/python-mode.git)) or [`emacs`](https://www.gnu.org/software/emacs/) and integrated development environments like [`pycharm`](https://www.jetbrains.com/pycharm/) can offer the...
16,212
51,060,433
I coded a jQuery with flask where on-click it should perform an SQL search and export the dataframe as excel, the script is: ``` <script type=text/javascript> $(function () { $('a#export_to_excel').bind('click', function () { $.getJSON($SCRIPT_ROOT + ' /api/sanctionsSearch/download', { nm: $('...
2018/06/27
[ "https://Stackoverflow.com/questions/51060433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9979747/" ]
The solution is not ideal, but what I did is adding a window.open(url) command in the jquery which will call another function, this function will send\_file to the user.
You should use return statement ``` return send_file() ```
16,213
59,959,629
I've been stuck on this for the last week and I'm fairly lost as to what do for next steps. I have a Django application that uses a MySQL database. I've deployed it using AWS Elastic Beanstalk using the following tutorial : <https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html> It s...
2020/01/29
[ "https://Stackoverflow.com/questions/59959629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3310212/" ]
This should be sufficient to hide all but one sheet. ``` function hideAllSheetsExceptThisOne(sheetName) { var sheetName=sh||'Student Report';//default for testing var ss = SpreadsheetApp.getActive(); var sheets=ss.getSheets(); for(var i=0;i<sheets.length; i++){ if(sheets[i].getName()!=sheetName){ she...
I had to do something similar earlier this year, and this code proved to be very helpful. <https://gist.github.com/ixhd/3660885>
16,214
67,111,664
I created a little app with Python as backend and React as frontend. I receive some data from the frontend and I want to eliminate the first 20 words of the text I receive if a condition is satisfyed. ``` @app.route("/translate", methods=["GET", "POST"]) def translate(): prompt = request.json["prompt"] max_tokens...
2021/04/15
[ "https://Stackoverflow.com/questions/67111664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14880010/" ]
``` import pandas as pd ``` Use `to_datetime()` method and convert your date column from string to datetime: ``` df['Date']=pd.to_datetime(df['Date']) ``` Finally use `apply()` method: ``` df['comm0']=df['Date'].apply(lambda x:1 if x==pd.to_datetime('2021-01-07') else 0) ``` Or as suggested by @anky: Simply us...
It's a problem with types. df['Date'] is a string and not a datetime object, so when you compare each element with '2021-01-07' (another string) they differ because the time informations (00:00:00). as solution you can convert elements to datetime, as following: ``` def int_21(x): if x == pd.to_datetime('2021-01...
16,215
39,815,551
I am trying to make a program in python that will accept a user's input and check if it is a Kaprekar number. I'm still a beginner, and have been having a lot of issues, but my main issue now that I can't seem to solve is how I would add up all possibilities in a list, with only two variables. I'm probably not explaini...
2016/10/02
[ "https://Stackoverflow.com/questions/39815551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Say you start with ``` a = ['2', '0', '2', '5'] ``` Then you can run ``` >>> [(a[: i], a[i: ]) for i in range(1, len(a))] [(['2'], ['0', '2', '5']), (['2', '0'], ['2', '5']), (['2', '0', '2'], ['5'])] ``` to obtain all the possible contiguous splits. If you want to process it further, you can change it to numb...
Not a direct answer to your question, but you can write an expression to determine whether a number, N, is a Krapekar number more concisely. ``` >>> N=45 >>> digits=str(N**2) >>> Krapekar=any([N==int(digits[:_])+int(digits[_:]) for _ in range(1,len(digits))]) >>> Krapekar True ```
16,216
8,827,304
I'm using Plone v4.1.2, and I'd like to know if there a way to include more than one author in the by line of a page? I have two authors listed in ownership, but only one author is listed in the byline. I'd like the byline to look something like this: by First Author and Second Author — last modified Jan 11, 2012 01:...
2012/01/11
[ "https://Stackoverflow.com/questions/8827304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1144225/" ]
In order to browse more than one author you'll need a little bit of coding: That piece of page is called `viewlets`. That specific viewlet is called `plone.belowcontenttitle.documentbyline`. You can use [z3c.jbot](http://pypi.python.org/pypi/z3c.jbot) to override the viewlet template. Take a look at [this howto](htt...
you could use the contributors- instead of the owners-field. they are listed by default in the docByLine. hth, i
16,217
65,433,038
So I'm trying to run Django developing server on a container but I can't access it through my browser. I have 2 containers using the same docker network, one with postgress and the other is Django. I manage to ping both containers and successfully connect 2 of them together and run `./manage.py runserver` ok but can't ...
2020/12/24
[ "https://Stackoverflow.com/questions/65433038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11386561/" ]
Think of it this way: Your React application is the U-Haul truck that delivers **everything** from the Web Server (Back-End) to the Browser (Front-End) ![](https://i.imgur.com/tMRFrMkm.png) Now you say you want everything wrapped in a (native) Web Component: `<move-house></move-house>` It is do-able, but you as ...
It is possible in react using direflow. <https://direflow.io/>
16,218
19,037,928
I am using python + beautifulsoup to parse html. My problem is that I have a variable amount of text items. In this case, for example, I want to extract 'Text 1', 'Text 2', ... 'Text 4'. In other webpages, there may be only 'Text 1' or possibly two, etc. So it changes. If the 'Text x's were contained in a tag, it would...
2013/09/26
[ "https://Stackoverflow.com/questions/19037928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2049545/" ]
You might try something like this: ``` >>> test ="""<b>Header 1</b> <br/> Text 1 <br/> Text 2 <br/> Text 3 <br/> Text 4 <br/> <b>Header 2</b>""" >>> soup = BeautifulSoup(test) >>> test = soup.find('b') >>> desired_text = [x.strip() for x in str(test.parent).split('<br />')] ['<b>Header 1</b>', 'Text 1', 'Text 2', 'Te...
Here is a different solution. nextSibling can get parts of the structured document that follow a named tag. ``` from BeautifulSoup import BeautifulSoup text=""" <b>Header 1</b> <br/> Text 1 <br/> Text 2 <br/> Text 3 <br/> Text 4 <br/> <b>Header 2</b> """ soup = BeautifulSoup(text) for br in soup.findAll('br'): ...
16,219
10,899,197
``` #include <ext/hash_map> using namespace std; class hash_t : public __gnu_cxx::hash_map<const char*, list<time_t> > { }; hash_t hash; ... ``` I'm having some problems using this hash\_map. The const char\* im using as a key is always a 12 length number with this format 58412xxxxxxx. I know there are 483809 diff...
2012/06/05
[ "https://Stackoverflow.com/questions/10899197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430913/" ]
`const char*` is not good for a key, since you now have pointer comparison instead of string comparison (also, you probably have dangling pointers, the return value of `c_str()` is not usable long-term). Use `hash_map<std::string, list<time_t> >` instead.
If your key is `char*`, you are comparing no the strings, but pointers, which makes your hashmap work differently than what you expect. Consider using `const std::string` for the keys, so they are compared using lexicographical ordering
16,221
39,599,596
I´m writing a simple calculator program that will let a user add a list of integers together as a kind of entry to the syntax of python. I want the program to allow the user to add as many numbers together as they want. My error is: ``` Traceback (most recent call last): File "Calculator.py", line 17, in <module> ...
2016/09/20
[ "https://Stackoverflow.com/questions/39599596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6854420/" ]
[`raw_input`](https://docs.python.org/2/library/functions.html#raw_input) returns strings, not numbers. [`sum`](https://docs.python.org/2/library/functions.html#sum) operates only on numbers. You can convert each item to an int as you add it to the list: `inputs.append(int(value))`. If you use `float` rather than `int...
When using `raw_input()` you're storing a string in `value`. Convert it to an int before appending it to your list, e.g. ``` inputs.append( int( value ) ) ```
16,222
63,640,435
SSO is not enabled for bot on Teams channel. I develop a bot on Bot Framework and Azure Service, using python 3.7. I needed user authentication in the Microsoft system to use Graph API, etc. Previously successfully used the [example](https://github.com/microsoft/BotBuilder-Samples/tree/main/samples/python) 18.bot-aut...
2020/08/28
[ "https://Stackoverflow.com/questions/63640435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13382091/" ]
Please check the following articles: <https://learn.microsoft.com/en-us/power-virtual-agents/advanced-end-user-authentication> <https://learn.microsoft.com/en-us/power-virtual-agents/configuration-end-user-authentication> <https://learn.microsoft.com/en-us/power-virtual-agents/publication-add-bot-to-microsoft-teams> ...
Please refer to the Teams-Auth [sample](https://github.com/microsoft/BotBuilder-Samples/tree/main/samples/python/46.teams-auth) and the [documentation](https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/add-authentication?tabs=dotnet%2Cdotnet-sample) which helps you get started with au...
16,223
24,136,733
``` process_name = "CCC.exe" for proc in psutil.process_iter(): if proc.name == process_name: print ("have") else: print ("Dont have") ``` I know for the fact that CCC.exe is running. I tried this code with both 2.7 and 3.4 python I have imported psutil as well. However the process is there b...
2014/06/10
[ "https://Stackoverflow.com/questions/24136733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016977/" ]
Here is the modified version that worked for me on Windows 7 with python v2.7 You were doing it in a wrong way here `if proc.name == process_name:` in your code. Try to `print proc.name` and you'll notice why your code didn't work as you were expecting. Code: ``` import psutil process_name = "System" for proc in p...
I solved it by using WMI instead of psutil. <https://pypi.python.org/pypi/WMI/> install it on windows. `import wmi c = wmi.WMI () for process in c.Win32_Process (): if "a" in process.Name: print (process.ProcessId, process.Name)`
16,224
57,640,451
I'm trying to iterate each row in a Pandas dataframe named 'cd'. If a specific cell, e.g. [row,empl\_accept] in a row contains a substring, then updates the value of an other cell, e.g.[row,empl\_accept\_a] in the same dataframe. ```py for row in range(0,len(cd.index),1): if 'Master' in cd.at[row,empl_accept]: ...
2019/08/24
[ "https://Stackoverflow.com/questions/57640451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10609069/" ]
Please do *not* use loops for this. You can do this in bulk with: ``` cd['empl_accept_a'] = cd['empl_accept'].str.contains('Master').astype(int).astype(str) ``` This will store `'0`' and `'1'` in the column. That being said, I am not convinced if storing this as strings is a good idea. You can just store these as `bo...
You need to check in your dataframe what value is placed at [row,empl\_accept]. I'm sure there will be some numeric value at this location in your dataframe. Just print the value and you'll see the problem if any. ``` print (cd.at[row,empl_accept]) ```
16,227
52,338,706
I already split the data into test and training set into the different folder. Now I need to load the patient data. Each patient has 8 images. ```py def load_dataset(root_dir, split): """ load the data set numpy arrays saved by the preprocessing script :param root_dir: path to input data :param split: ...
2018/09/14
[ "https://Stackoverflow.com/questions/52338706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403249/" ]
It seems that `./data/preprocessed_data/train/Patient009969` is a directory, not a file. `os.listdir()` returns both files and directories. Maybe try using `os.walk()` instead. It treats files and directories separately, and can recurse inside the subdirectories to find more files in a iterative way: ``` data_paths ...
Do you have both files and directories inside your path? `os.listdir` will list both files and directories, so when you try to open a directory with `np.load` it will give that error. You can filter only files to avoid the error: ``` data_paths = [os.path.join(in_dir, f) for f in os.listdir(in_dir)] data_paths = [i fo...
16,228
57,690,881
Interested in the scala spark implementation of this [split-column-of-list-into-multiple-columns-in-the-same-pyspark-dataframe](https://stackoverflow.com/questions/49650907/split-column-of-list-into-multiple-columns-in-the-same-pyspark-dataframe) Given this Dataframe: ``` | X | Y| +------...
2019/08/28
[ "https://Stackoverflow.com/questions/57690881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2800939/" ]
I modified the loss functions and used the *metrics* in compile finction. ``` def recon_loss(inputs,outputs): reconstruction_loss = original_dim*binary_crossentropy(inputs,outputs) return K.mean(reconstruction_loss) def latent_loss(inputs,outputs): kl_loss = ...
Please check the type of each loss in your losses dictionary. ``` print (type(losses['recon_loss'])) ```
16,231
56,034,031
I am a new user of python and the neo4j. I just want to run the python file in Pycharm and connect to Neo4j. But the import of py2neo always does not work, I tried to use Virtualenv but still does not work. I have tried to put my py file inside env folder or outside and both don't work. I really install the py2neo and...
2019/05/08
[ "https://Stackoverflow.com/questions/56034031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11467790/" ]
check which python version is configured to run the project and make sure that module is installed for that version. here is how to: [Pycharm](https://www.jetbrains.com/help/idea/configuring-local-python-interpreters.html)
You need to install py2neo in virtual environment. if you haven't install. and Check you python version on your machine and project. ``` pip install py2neo ```
16,232
13,584,524
In the old world I had a pretty ideal development setup going to work together with a webdesigner. Keep in mind we mostly do small/fast projects, so this is how it worked: * I have a staging site on a server (Webfaction or other) * Designer accesses that site and edits templates and assets to his satisfaction * I SSH ...
2012/11/27
[ "https://Stackoverflow.com/questions/13584524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/102315/" ]
Reformat a string to display it as a MAC address: ``` var macadres = "0018103AB839"; var regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})"; var replace = "$1:$2:$3:$4:$5:$6"; var newformat = Regex.Replace(macadres, regex, replace); // newformat = "00:18:10:3A:B8:39" ``` If you want to validate the input string us...
Suppose that we have the Mac Address stored in a long. This is how to have it in a formatted string: ``` ulong lMacAddr = 0x0018103AB839L; string strMacAddr = String.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}", (lMacAddr >> (8 * 5)) & 0xff, (lMacAddr >> (8 * 4)) & 0xff, (lMacAddr >> (8 * 3)) & 0xff...
16,234
9,955,715
i'm trying to do some "post"/"lazy" evaluation of arguments on my strings. Suppose i've this: ``` s = "SELECT * FROM {table_name} WHERE {condition}" ``` I'd like to return the string with the `{table_name}` replaced, but not the `{condition}`, so, something like this: ``` s1 = s.format(table_name = "users") ``` ...
2012/03/31
[ "https://Stackoverflow.com/questions/9955715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198212/" ]
You can replace the condition with itself: ``` s.format(table_name='users', condition='{condition}') ``` which gives us: ``` SELECT * FROM users WHERE {condition} ``` You can use this string later to fill in the condition.
I have been using this function for some time now, which casts the `Dict` of inputted keyword arguments as a `SafeDict` object that subclasses `Dict`. ``` def safeformat(str, **kwargs): class SafeDict(dict): def __missing__(self, key): return '{' + key + '}' replacem...
16,236
39,689,012
i have written a code (python 2.7) that goes to a website [Cricket score](http://www.cricbuzz.com/live-cricket-scorecard/16822/ind-vs-nz-1st-test-new-zealand-tour-of-india-2016) and then takes out some data out of it to display just its score .It also periodically repeats and keeps running because the scores keep chang...
2016/09/25
[ "https://Stackoverflow.com/questions/39689012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6878406/" ]
i am sorry, i added a bit too many double-quotes in the above code. instead it should be this way: ``` asm (".section .drectve\n\t.ascii \" -export:DllInitialize=api.DllInitialize @2\""); ``` If you need to use it many times, consider putting it in a macro, e.g. ``` #ifdef _MSC_VER #define FORWARDED_EXPORT_WITH...
here is how you can do it: ``` #ifdef _MSC_VER #pragma comment (linker, "/export:DllInitialize=api.DllInitialize,@2") #endif #ifdef __GNUC__ asm (".section .drectve\n\t.ascii \" -export:\\\"DllInitialize=api.DllInitialize\\\" @2\""); #endif ``` Note that "drectve" is not a typo, thats how it must be written ...
16,246
71,940,988
I have trained a model based on YOLOv5 on a custom dataset which has two classes (for example human and car) I am using `detect.py` with the following command: ``` > python detect.py --weights best.pt --source video.mp4 ``` I want only car class to be detected without detecting humans, how it could be done?
2022/04/20
[ "https://Stackoverflow.com/questions/71940988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16637958/" ]
You can specify classes, which you want to detect **[--classes]** arguments will be used. **Example** ``` python detect.py --weights "your weights.pt" --source "video/image/stream" --classes 0,1,2 ``` In above command, 0,1,2 are classId, so when you will run it, only mentioned classes will be detect.
I think you can use the argument --classes of detect.py. Just use the index of the classes.
16,247
23,784,951
I have a string that looks like this: `POLYGON ((148210.445767647 172418.761192525, 148183.930888667 172366.054787545, 148183.866770629 172365.316772032, 148184.328078148 172364.737139913, 148220.543522168 172344.042601933, 148221.383518338 172343.971823159), (148221.97916844 172344.568316375, 148244.61381946 172406.6...
2014/05/21
[ "https://Stackoverflow.com/questions/23784951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1300454/" ]
The data structure you have defining your Polygon object looks very similar to a python tuple declaration. One option, albeit a bit hacky would be to use python's [AST parser](https://docs.python.org/2/library/ast.html#ast.literal_eval). You would have to strip off the POLYGON part and this solution may not work for o...
Lets say u have a string that looks like this my\_str = 'POLYGON ((148210.445767647 172418.761192525, 148183.930888667 172366.054787545, 148183.866770629 172365.316772032, 148184.328078148 172364.737139913, 148220.543522168 172344.042601933, 148221.383518338 172343.971823159), (148221.97916844 172344.568316375, 148244...
16,248
54,485,654
Simplified example of my code, please ignore syntax errors: ``` import numpy as np import pandas as pd import pymysql.cursors from datetime import date, datetime connection = pymysql.connect(host=, user=, password=, ...
2019/02/01
[ "https://Stackoverflow.com/questions/54485654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9637684/" ]
Have you seen the join command? This in combination with sort maybe what you are looking for. <https://shapeshed.com/unix-join/> for example: ``` $ cat a aaaa bbbb cccc dddd $ cat b aaaa eeee ffff gggg $ join a b aaaa bbbb eeee ``` If the values in the first column are not sorted, than you have to sort them...
There are different kinds and different tools to compare: * diff * cmp * comm * ... All commands have options to vary the comparison. For each command, you can specify filters. E.g. ``` # remove comments before comparison diff <( grep -v ^# file1) <( grep -v ^# file2) ``` Without concrete examples, it is impossib...
16,250
26,506,830
I have the expectation that `reduce(add,lst)` and `sum(lst)` should give me the same result, but ``` In [18]: class p(): def __init__(self, x, y): self.x=x ; self.y=y def __repr__(self): return "(%r,%r)"%(self.x,self.y) def __add__(self, P): return p(self.x+P.x, self.y+P.y) ....:...
2014/10/22
[ "https://Stackoverflow.com/questions/26506830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2749397/" ]
`reduce()` starts with `pts[0]` as the initial value (unless you give it an explicit starting value), but `sum()` defaults with `0`. From the [`sum()` function documentation](https://docs.python.org/2/library/functions.html#sum): > > `sum(iterable[, start])` > > Sums *start* and the items of an iterable from left...
If you define `__radd__` to special case if 0 is added to an instance of your object, then you can just use `sum()`. ``` ... rest of Point class defn ... def __radd__(self, other): if other == 0: return self raise TypeError("invalid type to add to point") print sum(pts) ``` will give `(0,5)`.
16,255