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
9,170,271
I am trying to flip a picture on its vertical axis, I am doing this in python, and using the Media module. like this: ![enter image description here](https://i.stack.imgur.com/j9woa.jpg) i try to find the relationship between the original and the flipped. since i can't go to negative coordinates in python, what i dec...
2012/02/07
[ "https://Stackoverflow.com/questions/9170271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1090782/" ]
Why not just use Python Imaging Library? Flipping an image horizontally is a one-liner, and much faster to boot. ``` from PIL import Image img = Image.open("AFLAC.jpg").transpose(Image.FLIP_LEFT_RIGHT) ```
Your arithmetic is incorrect. Try this instead... ``` new_pixel_0 = media.get_pixel(new_pic, width - x_org, y_org) ``` There is no need to treat the two halves of the image separately. This is essentially negating the *x*-co-ordinate, as your first diagram illustrates, but then slides (or translates) the flipped im...
236
39,030,546
Try to run Example 7-11 of **High Performance Python** **cython\_np.pyx** ``` #cython_np.pyx import numpy as np cimport numpy as np def calculate_z(int maxiter, double complex[:] zs, double complex[:] cs): cdef unsigned int i, n cdef double complex z, c cdef int[:] output = np.empty(len(zs), dtype = np.in...
2016/08/19
[ "https://Stackoverflow.com/questions/39030546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6536252/" ]
I can't see any obvious "faults" with your sql. However, if student 12345 is missing in any way data from (dcis, studentsdcid, guardianid, externalident, student\_number) or there are no matching data in any of the tables. Then no record will be returned since you are using inner joins. 2 suggestions: \*Try changing ...
That's probably cause no any record matches with those condition in place since it's `AND`. Try making that last condition to a `OR` condition and see like ``` WHERE pcs.SCHOOLID=9 AND pcs.FIELD_NAME='web_password' AND s.ENROLL_STATUS=0 OR s.STUDENT_NUMBER=12345 ```
239
9,434,205
The code below is streaming the twitter public timeline for a variable which output any tweets to the console. I'd like the save the same variables (status.text, status.author.screen\_name, status.created\_at, status.source) into an sqlite database. I'm getting an syntax error when my script sees a tweet and nothing is...
2012/02/24
[ "https://Stackoverflow.com/questions/9434205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039166/" ]
You are missing a closing parenthesis on the last line of the following code (lines 34–37 from what you posted): ``` cur.executemany("INSERT INTO TWEETS(?, ?, ?)", (status.text, status.author.screen_name, ...
``` import sqlite3 as lite con = lite.connect('test.db') cur = con.cursor() cur.execute("CREATE TABLE TWEETS(txt text, author text, created int, source text)") ``` then later: ``` cur.executemany("INSERT INTO TWEETS(?, ?, ?, ?)", (status.text, status.author.screen_name, ...
241
60,513,468
I read from python3 document, that python use hash table for dict(). So the search time complexity should be O(1) with O(N) as the worst case. However, recently as I took a course, the teacher says that happens only when you use int as the key. If you use a string of length L as keys the search time complexity is O(L)....
2020/03/03
[ "https://Stackoverflow.com/questions/60513468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7037749/" ]
Since a dictionary is a hashtable, and looking up a key in a hashtable requires computing the key's hash, then the time complexity of looking up the key in the dictionary cannot be less than the time complexity of the hash function. In current versions of CPython, a string of length L takes O(L) time to compute the ha...
> > only when you use int as the key. If you use a string of length L as keys the search time complexity is O(L) > > > Just to address a point not covered by kaya3's answer.... ### Why people often say a hash table insertion, lookup or erase is a O(1) operation. For many real-world applications of hash tables, t...
246
38,798,816
I have anaconda installed and also I have downloaded Spark 1.6.2. I am using the following instructions from this answer to configure spark for Jupyter [enter link description here](https://stackoverflow.com/questions/33064031/link-spark-with-ipython-notebook) I have downloaded and unzipped the spark directory as ``...
2016/08/05
[ "https://Stackoverflow.com/questions/38798816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2769240/" ]
1- You need to set `JAVA_HOME` and spark paths for the shell to find them. After setting them in your `.profile` you may want to ``` source ~/.profile ``` to activate the setting in the current session. From your comment I can see you're already having the `JAVA_HOME` issue. Note if you have `.bash_profile` or `.ba...
For anyone who came here during or after MacOS Catalina, make sure you're establishing/sourcing variables in **zshrc** and not **bash**. `$ nano ~/.zshrc` ``` # Set Spark Path export SPARK_HOME="YOUR_PATH/spark-3.0.1-bin-hadoop2.7" export PATH="$SPARK_HOME/bin:$PATH" # Set pyspark + jupyter commands export PYSPARK_S...
247
38,412,184
I'm trying to free memory allocated to a `CString`and passed to Python using ctypes. However, Python is crashing with a malloc error: ```none python(30068,0x7fff73f79000) malloc: *** error for object 0x103be2490: pointer being freed was not allocated ``` Here are the Rust functions I'm using to pass the pointer to ...
2016/07/16
[ "https://Stackoverflow.com/questions/38412184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/416626/" ]
Please try this command I have resolved it by this command ``` sudo apt-get install libfontconfig ```
Try add onError event to pipe ``` converter.image(req, { format: "png" , quality: 75 }).pipe(res).on('error', function(e){ console.log(e); }); ```
249
26,509,222
I have a list of python strings which are in a list. I want to call split method at each string in the list and store the results in another list without using loops because the list is very long. **EDIT1** Here is one example ``` input = ["a,the,an","b,b,c","people,downvoting,it,must,think,first"] output [[...
2014/10/22
[ "https://Stackoverflow.com/questions/26509222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/623300/" ]
``` [a.split(',') for a in list] Sample: ['a,c,b','1,2,3'] Result: [['a','c','b'],['1','2','3']] ``` If you wanted everything in one list, you could try this (not sure of how efficient it is) ``` output = sum([a.split(',') for a in list],[]) Sample: ['a,c,b','1,2,3'] Result: ['a','c','b','1','2','3'] ```
Use list comprehensions. ``` mystrings = ["hello world", "this is", "a list", "of interesting", "strings"] splitby = " " mysplits = [x.split(splitby) for x in mystrings] ``` No idea if it performs better than a `for` loop, but there you go.
250
27,580,550
I develop python app which connect to Prolog via pyswip. The following code is when I ask a question from prolog. ``` self.prolog = Prolog() self.prolog.consult("Checker.pl") self.prolog.query("playX") ``` This is the sample of my Prolog code ``` playX :- init(B), assert(min_to_move(x/_)),assert(max_...
2014/12/20
[ "https://Stackoverflow.com/questions/27580550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3050141/" ]
In your style.css add this code ``` #toggle-menu li { float: right; list-style-type: none; } ``` See [here](http://i.stack.imgur.com/aznP5.png) for an example of it in action. The reason that dot is there is that you're adding it as a list element -- it's not a full stop, necessarily, just the marker for a new ...
It's not a full stop, it's a list item bullet. You're using a list with `<li>` tags, and the default behaviour is to put a bullet in front of whatever is inside the `<li>` The real answer here though is that your code isn't very semantically correct. Why is an icon inside of an unordered list in the first place? Consi...
253
26,909,770
i am looking for a way to print all internal decimal places of a python decimal. has anyone an idea how to achieve following. The example code is written in Python. ``` from decimal import * bits = 32 precision = Decimal(1) / Decimal(2**bits) val = decimal(1078947848) ``` what happens now for following if i multiply...
2014/11/13
[ "https://Stackoverflow.com/questions/26909770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1446071/" ]
From the [documentation](https://docs.python.org/2/library/decimal.html): > > the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem > > > Your number is 29 digits long, so it's just a little too much for the default precision. Try increasin...
You could take your string representation & eliminate the trailing 0's; what is left are your "internal decimal places", which you can count.
256
27,183,163
Python 3.4 So maybe it's the turkey digesting, or maybe it's my lack of python wizardry, but my simplistic idea for initializing instances of a class with several members all set to None doesn't seem to be working. To wit: dataA.txt ``` # layername purpose stmLay stmDat topside copper 3 5 level...
2014/11/28
[ "https://Stackoverflow.com/questions/27183163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1201168/" ]
Finally, I was able to fix the problem. I am posting it for others sake. I used ssh **-f** user@server .... this solved my problem. ``` ssh -f root@${server} sh /home/administrator/bin/startServer.sh ```
I ran into a similar issue using the **Publish Over SSH Plugin**. For some reason Jenkins wasn't stopping after executing the remote script. Ticking the below configuration fixed the problem. SSH Publishers > Transfers > Advanced > Exec in pty Hope it helps someone else.
257
44,214,938
These are the versions that I am working with ``` $ python --version Python 2.7.10 $ pip --version pip 9.0.1 from /Library/Python/2.7/site-packages (python 2.7) ``` Ideally I should be able to install tweepy. But that is not happening. ``` $ pip install tweepy Collecting tweepy Using cached tweepy-3.5.0-py2.p...
2017/05/27
[ "https://Stackoverflow.com/questions/44214938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6193290/" ]
Install it with: ``` sudo pip install tweepy ``` Looks like a permission problem :)
I got the same problem. The way I solved it was to download python 2.7.13 from the official website and install it. After that, I installed pip with: ``` sudo easy_install pip ``` And after that: ``` pip install tweepy ``` Hope it is still relevant :)
259
32,531,858
Assume you have a list : ``` mylist=[[1,2,3,4],[2,3,4,5],[3,4,5,6]] ``` any pythonic(2.x) way to unpack the inner lists so that new list should look like ?: ``` mylist_n=[1,2,3,4,2,3,4,5,3,4,5,6] ```
2015/09/11
[ "https://Stackoverflow.com/questions/32531858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2516297/" ]
I think that due the fact that you are setting the text of the button as follows: ``` <asp:LinkButton ID="click_download" runat="server" OnClick="download"><%# Eval("title") %></asp:LinkButton> ``` The `Text` property is not being set correctly. Move the `<%# Eval("title") %>` into the declaration of link button an...
I don't see where you are setting the text property/attribute for the LinkButton. However, I do see where you have "<%# Eval("title") %>" floating in your tag. Should it say Text="<%# Eval("title") %>". I really don't understand how it is being viewed if it's not set. Are you setting it in the Page\_Load? Hopefully th...
260
19,325,907
I am working on my first Django website and am having a problem. Whenever I attempt to go on the admin page www.example.com/admin I encounter a 404 page. When I attempt to go on the admin site on my computer using `python manage.py runserver` it works. What info do you guys need to help me to fix my problem? `url.py` ...
2013/10/11
[ "https://Stackoverflow.com/questions/19325907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2366105/" ]
You must include the Django admin in your `INSTALLED_APPS` in the settings file (it's probably already there, but commented out). You will also need to configure the URLs for the admin site, which should be in your site-wide urls.py, again, probably commented out but there. If you have already done both of these th...
`python manage.py runserver` enables your application to run locally. You need to deploy your application using WSGI and Apache to access your page from other remove machines. Refer to the configuration details <https://docs.djangoproject.com/en/1.2/howto/deployment/modwsgi/>
261
34,092,850
I'm trying to apply the expert portion of the tutorial to my own data but I keep running into dimension errors. Here's the code leading up to the error. ``` def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.const...
2015/12/04
[ "https://Stackoverflow.com/questions/34092850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3849791/" ]
You have to shape the input so it is compatible with both the training tensor and the output. If you input is length 1, your output should be length 1 (length is substituted for dimension). When you're dealing with- ``` def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_poo...
The dimensions you are using for the filter are not matching the output of the hidden layer. Let me see if I understood you: your input is composed of 8 features, and you want to reshape it into a 2x4 matrix, right? The weights you created with `weight_variable([1, 8, 1, 4])` expect a 1x8 input, in one channel, and p...
262
22,767,444
I have the following xml file: ``` <root> <article_date>09/09/2013 <article_time>1 <article_name>aaa1</article_name> <article_link>1aaaaaaa</article_link> </article_time> <article_time>0 <article_name>aaa2</article_name> <article_link>2aaaaaaa</article_link> </articl...
2014/03/31
[ "https://Stackoverflow.com/questions/22767444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1146365/" ]
Here's the solution using `xml.etree.ElementTree` from python standard library. The idea is to gather items into `defaultdict(list)` per `article_time` text value: ``` from collections import defaultdict import xml.etree.ElementTree as ET data = """<root> <article_date>09/09/2013 <article_time>1 <art...
I'll write as much as I have time (and knowledge), but I'm making this a community wiki so other folks can help. I would suggest using [xml](https://docs.python.org/2/library/xml.etree.elementtree.html) or [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) libraries for this. I'll use BeautifulSoup...
263
60,959,871
**The problem**: I have a 3-D Numpy Array: `X` `X.shape: (1797, 2, 500)` ``` z=X[..., -1] print(len(z)) print(z.shape) count = 0 for bot in z: print(bot) count+=1 if count == 3: break ``` Above code yields following output: ``` 1797 (1797, 2) [23.293915 36.37388 ] [21.594519 32.874397] [27.29872 26....
2020/03/31
[ "https://Stackoverflow.com/questions/60959871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7890913/" ]
Here's a solution with sample data: ``` a,b,c = X.shape # in your case # a,b,c = 1797, 500 pd.DataFrame(X.transpose(1,2,0).reshape(2,-1).T, index=np.repeat(np.arange(c),a), columns=['X_coord','Y_coord'] ) ``` Output: ``` X_coord Y_coord 0 0 3 0 6 ...
Try this way: ``` index = np.concatenate([np.repeat([i], 1797) for i in range(500)]) df = pd.DataFrame(index=index) df['X-coordinate'] = X[:, 0, :].T.reshape((-1)) df['Y-coordinate'] = X[:, 1, :].T.reshape((-1)) ```
264
35,475,519
I am facing problem in returned image url, which is not proper. My return image url is `"http://127.0.0.1:8000/showimage/6/E%3A/workspace/tutorial_2/media/Capture1.PNG"` But i need ``` "http://127.0.0.1:8000/media/Capture1.PNG" ``` [![enter image description here](https://i.stack.imgur.com/wZSwF.png)](https://i.sta...
2016/02/18
[ "https://Stackoverflow.com/questions/35475519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3526079/" ]
You might want to try this in your settings: ``` MEDIA_URL = '/media/' MEDIA_ROOT=os.path.join(BASE_DIR, "media") urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^showimage/', include('showimage.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` And in your ...
Your code seems correct except one thing you have passed settings.MEDIA in uploads image. you don't need to pass settings.MEDIA in uploads. try this ``` image_url = models.ImageField(upload_to='Dir_name') ``` Dir\_name will create when you'll run script.
265
45,317,050
How do I find if a string has atleast 3 alpha numeric characters in python. I'm using regex as `"^.*[a-zA-Z0-9]{3, }.*$"`, but it throws error message everytime. My example string: a&b#cdg1. P lease let me know.
2017/07/26
[ "https://Stackoverflow.com/questions/45317050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8341662/" ]
like this ``` #include <stdio.h> #include <stdarg.h> typedef enum rule { first, total } Rule; int fund(Rule rule, int v1, ...){ switch(rule){ case total: { int total = v1, value; if(v1 == -1) return 0; va_list ap; va_start(ap, v1); valu...
You mentioned that the end of your arguments is marked by a `-1`. This means you can keep getting more arguments until you get a `-1`. Following is the way you can do it using `va_list` - ``` if(rule == TYPE) { int total = 0; va_list args; va_start(args, rule); int j; while(1){ j = va_arg...
268
51,411,655
So I'm trying to Dockerize my project which looks like this: ``` project/ main.go package1/ package2/ package3/ ``` And it also requires some outside packages such as github.com/gorilla/mux Note my project is internal on a github.company.com domain so I'm not sure if that matters. So here's my Dockerfile and...
2018/07/18
[ "https://Stackoverflow.com/questions/51411655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4062625/" ]
Wow, golang really is picky about paths! It was just that I had assigned my working directory to the wrong place. There was another file in the tree: ``` WORKDIR /go/src/github.company.com/COMPANY/project-repo/project ```
did you make(`mkdir`) the `WORKDIR` before setting its value?
269
29,988,923
What is the best way to downgrade icu4c from 55.1 to 54.1 on Mac OS X Mavericks. I tried `brew switch icu4c 54.1` and failed. **Reason to switch back to 54.1** I am trying to setup and use Mapnik. I was able to install Mapnik from homebrew - `brew install mapnik` But, I get the following error when I try to `impor...
2015/05/01
[ "https://Stackoverflow.com/questions/29988923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3983957/" ]
This was Homebrew's fault and should be fixed after `brew update && brew upgrade mapnik`; sorry!
I had the same problem but using Yosemite but I guess it should be fairly the same. I am not sure this is the best way to do it but it worked for me. I tried `brew switch icu4c 54.1` but failed since I did not have that package in the Cellar. My solution was getting ici4c 54.1 in the Cellar. First check if you hav...
270
5,681,330
I typically write both unittests and doctests in my modules. I'd like to automatically run all of my doctests when running the test suite. I think this is possible, but I'm having a hard time with the syntax. I have the test suite ``` import unittest class ts(unittest.TestCase): def test_null(self): self.assertTr...
2011/04/15
[ "https://Stackoverflow.com/questions/5681330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489588/" ]
An update to this old question: since Python version 2.7 there is the [load\_tests protocol](https://docs.python.org/2/library/unittest.html#load-tests-protocol) and there is no longer a need to write custom code. It allows you to add a function `load_tests()`, which a test loader will execute to update its collection ...
First I tried accepted answer from Andrey, but at least when running in Python 3.10 and `python -m unittest discover` it has led to running the test from unittest twice. Then I tried to simplify it and use `load_tests` and to my surprise it worked very well: So just write both `load_tests` and normal `unittest` tests ...
271
68,640,124
I'm super new to praat parselmouth in python and I am a big fan, as it enables analyzes without Praat. So my struggle is, that I need formants in a specific sampling rate but I cant change it here. If I change the time\_step (and also time window), length of the formant list is not changing. I am mainly using this code...
2021/08/03
[ "https://Stackoverflow.com/questions/68640124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11662481/" ]
In `base R`you can use `sub` and backreference `\\1`: ``` sub("(\\d+:\\d+:\\d+\\.\\d+).*", "\\1", x) [1] "13:30:00.827" "13:30:01.834" ``` or: ``` sub("(.*?)(: <-.*)", "\\1", x) ``` In both cases you divide the string into two capturing groups, the first of which you remember in `sub`s replacement argument. In `...
This is what you should use: ``` sub(': <- \\$HCHDG', '', dataframe$ColName) ```
281
1,780,618
Ok so I have the same python code locally and in the gae cloud. when I store an entity locally, the ListProperty field of set element type datetime.datetime looks like so in the Datastore Viewer: ``` 2009-01-01 00:00:00,2010-03-10 00:00:00 ``` when I store same on the cloud, the viewer displays: ``` [datetime.date...
2009/11/23
[ "https://Stackoverflow.com/questions/1780618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/178511/" ]
Ok long story short: it's now classed as a bug in the app engine dev server version and is no longer supported in the production cloud datastore. Filled out a further explanation in a [blog post](http://aleatory.clientsideweb.net/2009/11/28/google-app-engine-datastore-gotchas/), check out point 3.
The problem your see is clearly a conversion to string (calling `__str__` or `__unicode__`) in the local case, while the representation (repr) of your data is displayed on the cloud. But this difference in printing out the results should not be the cause of your failed query on the cloud. What is your exact query? **...
285
55,653,169
I am trying to write some code in python to retrieve some data from Infoblox. To do this i need to Import the Infoblox Module. Can anyone tell me how to do this ?
2019/04/12
[ "https://Stackoverflow.com/questions/55653169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11351903/" ]
Try this ``` path_to_directory="./" files = [arff for arff in os.listdir(path_to_directory) if arff.endswith(".arff")] def toCsv(content): data = False header = "" newContent = [] for line in content: if not data: if "@attribute" in line: attri = line.split() ...
Take a look at the error trace > > UnicodeEncodeError: 'ascii' codec can't encode character '\xf3' in position 4: ordinal not in range(128) > > > Your error suggests you have some encoding problem with the file. Consider first opening the file with the correct encoding and then loading it to the arff loader ``` ...
286
12,391,377
Python [supports chained comparisons](http://docs.python.org/reference/expressions.html#not-in): `1 < 2 < 3` translates to `(1 < 2) and (2 < 3)`. I am trying to make an SQL query using SQLAlchemy which looks like this: ``` results = session.query(Couple).filter(10 < Couple.NumOfResults < 20).all() ``` The results I...
2012/09/12
[ "https://Stackoverflow.com/questions/12391377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388334/" ]
The reason is that Python actually evaluates something akin to this: ``` _tmp = Couple.NumOfResults (10 < _tmp and _tmp < 20) ``` The `and` operator is unsupported in SQLAlchemy (one should use `and_` instead). And thus - chained comparisons are not allowed in SQLAlchemy. In the original example, one should write ...
SQLAlchemy won't support Python's chained comparisons. Here is the official reason why from author Michael Bayer: > > unfortunately this is likely impossible from a python perspective. The mechanism of "x < y < z" relies upon the return value of the two individual expressions. a SQLA expression such as "column < 5" r...
287
28,260,652
New to python, my assignment asks to ask user for input and then find and print the first letter of each word in the sentence so far all I have is ``` phrase = raw_input("Please enter a sentence of 3 or 4 words: ") ``` ^ That is all I have. So say the user enters the phrase "hey how are you" I am supposed to find a...
2015/02/01
[ "https://Stackoverflow.com/questions/28260652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4516441/" ]
This does everything that [Ming](https://stackoverflow.com/users/904117/ming) said in a single line. You can very well understand this code if you read his explanation. ``` phrase = raw_input("Please enter a sentence of 3 or 4 words: ") output = ''.join([x[0] for x in phrase.split()]) print output ``` Update...
Here are a rough outline of the steps you can take. Since this is an assignment, I will leave actually assembling them into a working program up to you. 1. `raw_input` will produce a string. 2. If you have two strings, one in `foo` and one in `bar`, then you can call [`string.split`](https://docs.python.org/2/library/...
288
44,180,066
I am asking if it's possible to create an attribute DictField with DictField in django restframework. If yes! Is it possible to populate it as a normal dictionary in python. I want to use it as a foreign key to store data.
2017/05/25
[ "https://Stackoverflow.com/questions/44180066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8002200/" ]
The best way that i know is to use [momentjs](https://momentjs.com/). I have used it with angular 1.x.x with no problems. It's pretty easy to use, check this out. You can add the following row: ``` nm.pick = moment(nm.pick).format('DD-MM-YYYY'); ``` This should solve your problem,
For `type="date"` binding ```js var app = angular.module("MyApp", []).controller("MyCtrl", function($scope, $filter) { $scope.nm = {}; $scope.nm.pick = new Date($filter('date')(new Date(), "yyyy-MM-dd")); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></scrip...
290
1,183,420
I am a .Net / SQL Server developer via my daytime job, and on the side I do some objective C development for the iPhone. I would like to develop a web service and since dreamhost supports mySql, python, ruby on rails and PHP5, I would like to create it using one of those languages. If you had no experience in either py...
2009/07/26
[ "https://Stackoverflow.com/questions/1183420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77393/" ]
Ruby-on-rails, Python and PHP would all be excellent choices for developing a web service in. All the languages are capable (with of course Ruby being the language that Ruby on Rails is written in), have strong frameworks if that is your fancy (Django being a good python example, and something like Drupal or CakePHP be...
I have developed in Python and PHP and my personal preference would be Python. Django is a great, easy to understand, light-weight framework for Python. [Django Site](http://www.djangoproject.com/) If you went the PHP route, I would recommend Kohana. [Kohana Site](http://www.kohanaphp.com/)
291
49,496,096
I'm learning python and I'm not sure why the output of the below code is only "False" and not many "false" if I created a loop and the list of dict have 5 elements. I was expect an ouput like "False" "False" "False" "False" ``` "False" movies = [{ "name": "Usual Suspects" }, { "name": "Hitman", ...
2018/03/26
[ "https://Stackoverflow.com/questions/49496096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5544653/" ]
Try using the Remote VSCode plugin as explained here: [Using Remote VSCode](https://spin.atomicobject.com/2017/12/18/remote-vscode-file-editing/) This discussion is exactly about your problem: [VSCode 13643 issue Github](https://github.com/Microsoft/vscode/issues/13643) EDIT: I have recently found a new VSCode plugin...
The [SSH.NET nuget Package](https://www.nuget.org/packages/SSH.NET) can be used quite nicly to copy files and folders. Here is an example: ``` var host = "YourServerIpAddress"; var port = 22; var user = "root"; // TODO: fix var yourPathToAPrivateKeyFile = @"C:\Users\Bob\mykey"; // Use certificate for login var authMet...
301
637,399
I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary. So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/...
2009/03/12
[ "https://Stackoverflow.com/questions/637399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9908/" ]
Just make sure Avahi / Bonjour's running, then type *hostname*.local (or also try *hostname*.localdomain) - it resolves using mDNS, so you don't have to care what your IP is or rigging /etc/hosts.
You could also use **arp-scan** (a Debian package of the name exists, not sure about other distributions) to scan your whole network. Have a script parse its output and you'll be all set.
303
52,331,595
I took a look at [this question](https://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python) but it doesn't exactly answer my question. As an example, I've taken a simple method to print my name. ``` def call_me_by_name(first_name): print("Your name is {}".format(first_name)) ``` Later on, I ...
2018/09/14
[ "https://Stackoverflow.com/questions/52331595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4020238/" ]
You have two separate questions with two separate pythonic ways of answering those questions. 1- Your first concern was that you don't want to keep adding new lines the more arguments you start supporting when formatting a string. The way to work around that is using a `defaultdict` so you're able to return an empty s...
You can simplify it by: ``` middle_name = kwargs.get('middle_name', '') ```
308
12,830,838
Hello I have what I hope is an easy problem to solve. I am attempting to read a csv file and write a portion into a list. I need to determine the index and the value in each row and then summarize. so the row will have 32 values...each value is a classification (class 0, class 1, etc.) with a number associated with it...
2012/10/11
[ "https://Stackoverflow.com/questions/12830838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736554/" ]
I find your use case a bit difficult to understand, but does this list comprehension give you some new ideas about how to solve your problem? ``` >>> classes = [' ', '1234', '645', '9897'], [' ', '76541', ' ', '8888'] >>> [sum(int(n) for n in x if n != ' ') for x in zip(*classes)] [0, 77775, 645, 18785] ```
``` >>> classes = [[' ', '1234', '645', '9897'], [' ', '76541', ' ', '8888']] >>> my_int = lambda s: int(s) if s.isdigit() else 0 >>> class_groups = dict(zip(range(32), zip(*classes))) >>> class_groups[1] ('1234', '76541') >>> class_sums = {} >>> for class_ in class_groups: ... group_sum = sum(map(my_int, class_gr...
318
3,484,976
I'm trying to write a Python client for a a WSDL service. I'm using the [Suds](https://fedorahosted.org/suds/wiki/Documentation) library to handle the SOAP messages. When I try to call the service, I get a Suds exception: `<rval />` not mapped to message part. If I set the `retxml` Suds option I get XML which looks OK...
2010/08/14
[ "https://Stackoverflow.com/questions/3484976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4697/" ]
Possible dup of [What does suds mean by "<faultcode/> not mapped to message part"?](https://stackoverflow.com/questions/2963094/what-does-suds-mean-by-faultcode-not-mapped-to-message-part/18948575#18948575) Here is my answer from that question: I had a similar issue where the call was successful, and Suds crashed on ...
This exception actually means that the answer from SOAP-service contains tag `<rval>`, which doesn't exist in the WSDL-scheme of the service. Keep in mind that the Suds library caches the WSDL-scheme, that is why the problem may occur if the WSDL-scheme was changed recently. Then the answers match the new scheme, but ...
320
35,122,185
I have a Profiles app that has a model called profile, i use that model to extend the django built in user model without subclassing it. **models.py** ``` class BaseProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='owner',primary_key=True) supervisor = models.ForeignKe...
2016/02/01
[ "https://Stackoverflow.com/questions/35122185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031794/" ]
You need to use multiple inline admin. When you have a model with multiple ForeignKeys to the same parent model, you'll need specify the `fk_name` attribute in your inline admin: ``` class UserProfileInline(admin.StackedInline): model = Profile fk_name = "user" class SupervisorProfileInline(admin.StackedInli...
Here is an example that I have just tested to be working ``` class Task(models.Model): owner = models.ForeignKey(User, related_name='task_owner') assignee = models.ForeignKey(User, related_name='task_assigned_to') ``` In admin.py ``` class TaskInLine(admin.TabularInLine): model = User @admin.register(T...
321
15,351,081
For example let's say I have a file called myscript.py This file contains the following code. ``` foo(var): return var ``` How would I call the function foo with argument var on command line. I know that I can go to the directory myscript.py is placed in and type. ``` >>> python myscript.py ``` Which will ru...
2013/03/12
[ "https://Stackoverflow.com/questions/15351081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2158898/" ]
You don't get any output because you don't generate any. Try calling [`print`](http://docs.python.org/3/library/functions.html#print): ``` def foo(var): print(var) if __name__ == '__main__': foo('Hello, world') ```
You have to use the `sys` module to pass arguments from the command line. You can do this: ``` import sys def foo(var): return var if __name__ == '__main__': # arguments check if len(sys.argv) != 2: print "USAGE: %s <value>" % sys.argv[0] sys.exit(1) # get the agument so as to use it to the function...
322
22,214,463
The title is self explanatory. What is going on here? How can I get this not to happen? Do I really have to change all of my units (it's a physics problem) just so that I can get a big enough answer that python doesn't round 1-x to 1? code: ``` import numpy as np import math vel=np.array([5e-30,5e-30,5e-30]) c=9.71...
2014/03/06
[ "https://Stackoverflow.com/questions/22214463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347826/" ]
In python [decimal](http://docs.python.org/library/decimal.html#module-decimal) may work and maybe [mpmath](https://code.google.com/p/mpmath/). as is discussed in this SO [article](https://stackoverflow.com/questions/11522933/python-floating-point-arbitrary-precision-available) If you are willing to use Java (instead...
I think you won't get the result you are expecting because you are dealing with computer math limits. The thing about this kind of calculations is that nobody can avoid this error, unless you make/find some models that has infinite (theoretically) decimals and you can operate with them. If that is too much for the prob...
323
73,007,506
Hi I want to clean up my code where I am converting a list of items to integers whenever possible in the python programming language. ``` example_list = ["4", "string1", "9", "string2", "10", "string3"] ``` So my goal (which is probably very simple) is to convert all items in the list from integers to integers and k...
2022/07/16
[ "https://Stackoverflow.com/questions/73007506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13840524/" ]
Perhaps add this somewhere: ``` <style> div { max-width: 306px !important; } </style> ```
u can try and use max width set to 306px for that part
324
61,412,481
I am trying to access Google Sheet (read only mode) from Python (runs in GKE). I am able to get application default creds, but getting scopes issue (as I am missing `https://www.googleapis.com/auth/spreadsheets.readonly` scope). See code below: ``` from googleapiclient.discovery import build from oauth2client import ...
2020/04/24
[ "https://Stackoverflow.com/questions/61412481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408628/" ]
You need to separate tick values and tick labels. ``` ax.set_xticks([]) # values ax.set_xticklabels([]) # labels ```
Just change it to: ``` self.ax.set_xticks([]) self.ax.set_yticks([]) ``` The error says that the second parameter cannot be given positionally, meaning that you need to explicitly give the parameter name minor=False for the second parameter or remove the second parameter in your case.
325
17,713,692
I am trying to simplify an expression using z3py but am unable to find any documentation on what different tactics do. The best resource I have found is a [stack overflow question](https://stackoverflow.com/questions/16167088/z3-tactics-are-not-available-via-online-interface) that lists all the tactics by name. Is so...
2013/07/18
[ "https://Stackoverflow.com/questions/17713692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016669/" ]
What's going on is that you're returning right after the first line of the file doesn't match the id you're looking for. You have to do this: ``` def query(id): for line in file: table = {} (table["ID"],table["name"],table["city"]) = line.split(";") if id == int(table["ID"]): f...
I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary. \*\*Note have used Python 2.7 so some minor modification might be required for Python 3+ ``` class a: global d d={}...
326
73,381,445
I need to have bash shell commands run through python in order to be universal with pc and mac/linux. `./bin/production` doesn't work in powershell and putting 'bash' in front would give an error that it doesn't recognize 'docker' command ./bin/production contents: ``` #!/bin/bash docker run --rm -it \ --volume $...
2022/08/16
[ "https://Stackoverflow.com/questions/73381445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19779700/" ]
### Modification points: * In your showing script, it seems that `payload` is not used. * When `getValue()` is used in a loop, the process cost becomes high. [Ref](https://gist.github.com/tanaikech/d102c9600ba12a162c667287d2f20fe4) When these points are reflected in a sample script for achieving your goal, it becomes...
Your code creates separate objects in each iteration. Create an empty object for every Person, then add the properties you need. This should look something like this: ```js for(var i=2; i<=LastRow; i++){ var payload = {} for(var j=1; j<=LastCol; j++){ payload[arr[j-1]] = ss.getRange(i,j).getValue()}; ...
332
6,499,839
> > **Possible Duplicate:** > > [Flatten (an irregular) list of lists in Python](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python) > > > I have the following list -- ``` [1,[2,3],4,[5,[6,7]]] ``` And I need to make it flat -- ``` [1,2,3,4,5,6,7] ``` To do this, I a...
2011/06/27
[ "https://Stackoverflow.com/questions/6499839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/651174/" ]
Hauled from [webhelpers.misc.flatten](http://sluggo.scrapping.cc/python/WebHelpers/modules/misc.html?highlight=flatten#webhelpers.misc.flatten) ``` def flatten(iterable): """Recursively iterate lists and tuples. """ for elm in iterable: if isinstance(elm, (list, tuple)): for relm in fla...
Try this: ``` def flat(mlist): result = [] for i in mlist: if type(i) is list: result.extend(flat(i)) else: result.append(i) return result ```
333
72,081,872
Hi I trying to make RBM Model code using pytorch module but got a issue in visible layer to hidden layer. Here is the problem part code. ```py h_bias = (self.h_bias.clone()).expand(10) v = v.clone().expand(10) p_h = F.sigmoid( F.linear(v, self.W, bias=h_bias) ) sam...
2022/05/02
[ "https://Stackoverflow.com/questions/72081872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9713429/" ]
If you look at the pytorch functional.linear documentation it shows the weight parameter can be either 1D or 2D: "Weight: (out\_features, in\_features) or (in\_features)". Since your weight is 2D ([1, 10]) it indicates that you are trying to create an output of size "1" with an input size of "10". The linear transform ...
I solved with torch.repeat() function. As mandias said... > > you are trying to create an output of size "1" with an input size of "10". The linear transform does not know how to change your inputs of size 10 into an output of size 1. > > > That was a my problem. So I changed weight input like this. ```py w = se...
334
49,259,985
I am reading data from a python dictionary and trying to add more book elements in the below tree. Below is just an examplke, i need to copy an element with it's child(s) but replace the content, in this case i need to copy the book element but replace title and author. ``` <store> <bookstore> <book> ...
2018/03/13
[ "https://Stackoverflow.com/questions/49259985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4977702/" ]
You changing the same object. You need to actual copy the object with copy.deepcopy Example: ``` import xml.etree.ElementTree as et import copy root = et.parse('Template.xml').getroot() bookstore = root.find('bookstore') book = root.find('bookstore').find('book') bks = ["book_title_1", "book_title_2", "book_title_...
I'm guessing instead of `books.append(book)` you mean `bookstore.append(book)`. Basically here you have a structure: ``` - store - bookstore - book - book infos ``` with `book = root.find('bookstore').find('book')` you are actually getting a reference to the (only) one you already have, and in the loop ...
335
2,741,986
I'm developing a small python like language using flex, byacc (for lexical and parsing) and C++, but i have a few questions regarding scope control. just as python it uses white spaces (or tabs) for indentation, not only that but i want to implement index breaking like for instance if you type "break 2" inside a while...
2010/04/30
[ "https://Stackoverflow.com/questions/2741986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208153/" ]
I am currently implementing a programming language rather similar to this (including the multilevel break oddly enough). My solution was to have the tokenizer emit indent and dedent tokens based on indentation. Eg: ``` while 1: # colons help :) print('foo') break 1 ``` becomes: ``` ["while", "1", ":", i...
Very interesting exercise. Can't you use the `end` keyword to check when the scope ends? On a different note, I have never seen a language that allows you to break out of several nested loops at once. There may be a good reason for that...
336
53,882,241
I've seen a few similar questions on SO regarding detecting changes to a dictionary and calling a function when the dictionary changes, such as: * [How to trigger function on value change?](https://stackoverflow.com/questions/6190468/how-to-trigger-function-on-value-change) * [python detect if any element in a diction...
2018/12/21
[ "https://Stackoverflow.com/questions/53882241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/512965/" ]
Building on the answer given in [here](https://stackoverflow.com/questions/26189090/python-detect-if-any-element-in-a-dictionary-changes), just do the following: ``` class MyDict(dict): def __setitem__(self, item, value): print("You are changing the value of {} to {}!!".format(item, value)) super(M...
Complete solution borrowing from the [this](https://stackoverflow.com/questions/26189090/python-detect-if-any-element-in-a-dictionary-changes) link(the second one given by OP) ``` class MyDict(dict): def __setitem__(self, item, value): print("You are changing the value of {key} to {value}!!".format(key=ite...
337
8,662,887
I've read that subprocess should be used but all the examples i've seen on it shows that it runs only command-line commands. I want my program to run a python command along with another command. The command i want to run is to send an email to a user while a user plays a game i created. i have to have the python comman...
2011/12/29
[ "https://Stackoverflow.com/questions/8662887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1082837/" ]
It sounds like you are looking for threading, which is a relatively deep topic, but this should help you get started: <http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/>
Threading is talked about in another answer, but you can get basically what you want by using subprocess's Popen command: <http://docs.python.org/library/subprocess.html#subprocess.Popen> What you'll basically want is this (assuming proc is initialized somewhere in the game loop): ``` #...game code here... args = [c...
339
23,434,748
I hate Recursive right now. Any way does any one know how to find square root using recursive solution on python. Or at least break it down to simple problems. All examples I found are linear only using one argument in the function. My function needs square Root(Number, low Guess, high Guess, Accuracy) I think the accu...
2014/05/02
[ "https://Stackoverflow.com/questions/23434748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597291/" ]
Remove the timeout setting: ``` rm config/initializers/timeout.rb ``` Heroku times-out all requests at 30 seconds but the process will continue running in the background. If you want to avoid that, re-add the line above but [put rack-timeout in your Gemfile](https://github.com/heroku/rack-timeout).
I would suggest trying the following: ``` heroku labs:enable user-env-compile ``` If this fails, you could always precompile your production assets, add them to your codebase and push them to heroku yourself. ``` RAILS_ENV=production rake assets:precompile git add . git commit -m 'serving up my precompiled assets'...
340
28,551,263
``` import pygame import time pygame.mixer.init() pygame.mixer.music.load('/home/bahara.mp3') time.sleep(2) pygame.mixer.music.play() ``` While compiling this code from terminal, no error is thrown, but I am unable to hear any music. But when executed line by line, the code is working fine. Can you suggest a wa...
2015/02/16
[ "https://Stackoverflow.com/questions/28551263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4573517/" ]
Pygame requires an active display which you have not initialized. I suggest you try installing and using `mpg123` command line tool. Install: ``` $ sudo apt-get install mpg123 ``` Program: ``` import os, time os.system('mpg123 /home/bahara.mp3') ```
I'm going to post my earlier comment as an answer because I think it's worth trying if you want to retain pygame's ability to control the music player. I suspect you're getting no sound because pygame is exiting as your script ends, whereas when you run line by line in a python terminal session pygame remains active. ...
342
40,739,504
My project consists of a python script(.py file) which has following dependencies : 1) numpy 2) scipy 3) sklearn 4) opencv (cv2) 5) dlib 6) torch and many more ... That is , the python script imports all of the above. In order to run this script I need to manually install all of the dependencies by running 'pip instal...
2016/11/22
[ "https://Stackoverflow.com/questions/40739504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6864242/" ]
I know that this Response may be a bit late. However, even if you can't benefit from this information now, perhaps someone else who may be looking for a similar answer will stumble onto this posting one day. You can use [py2exe](https://pypi.org/project/py2exe/) or [pyinstaller](https://pypi.org/project/PyInstaller/)...
In case of only python dependencies, use [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/). In case of others, write a shell script which has all the installation commands.
343
15,161,843
i noticed some seemingly strange behaviour when trying to import a python module named rmod2 in different ways. if i start python from the directory where the *rmod2.py* file is located, it works fine. however, if i move the file to another folder where other modules are locate, it doesn't work as expected anymore. the...
2013/03/01
[ "https://Stackoverflow.com/questions/15161843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2124120/" ]
APK will be generated under \bin\ folder once you run your app for the first time. Connect your Android device to dev machine via USB cable (assuming you got Android SDK etc installed), right click on Android project and do Run as->Android app. The app will be installed and started on Android device. APK will be gener...
You can also do an export on the android application project. This is what you would do if you are looking at doing some key signing. This is the way you would want to export it if you are uploading to Google play or an enterprise app store. Keep in mind, Worklight doesn't build your .ipa, .apk, or etc. It builds you ...
344
44,204,937
I am trying to change the behavior of python's `int` class, but I'm not sure if it can be done using pure python. Here is what I tried so far: ``` import builtins class int_new(builtins.int): def __eq__(self, other): return True int = int_new print(5 == 6) # the result is False, but I'm anticipating True ...
2017/05/26
[ "https://Stackoverflow.com/questions/44204937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7416363/" ]
You should replace last line with: ``` print(int(5) == int(6)) ``` to force/ask Python to use your new class for integer numbers.
A year later I finally learned what I was wondering. When I was learning Python, I was not exposed to the idea of what a primitive type is. After learning C++ I realized that I was actually wondering if it is possible to replace primitive type with other custom types. The answer is obviously no.
345
38,909,362
I'm working with International Phonetic Alphabet (IPA) symbols in my Python program, a rather strange set of characters whose UTF-8 codes can range anywhere from 1 to 3 bytes long. [This thread](https://stackoverflow.com/questions/7291120/python-and-unicode-code-point-extraction) from several years ago basically asked ...
2016/08/12
[ "https://Stackoverflow.com/questions/38909362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6707199/" ]
> > With that no longer an option, is there any way in Python 2.7 to find the Unicode code point of a given character? (And does that character then have to be a unicode type?) I don't mean by just manually looking it up on a Unicode table, either. > > > You can only find the unicode code point of a unicode object...
``` >>> u'ɨ' u'\u0268' >>> u'i' u'i' >>> 'ɨ'.decode('utf-8') u'\u0268' ```
346
61,902,162
I am working with Python version 2.7 and boto3 , but cannot import boto3 library . My Python path is ``` /Library/Frameworks/Python.framework/Versions/2.7/bin/python ``` When I look under ``` /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages ``` I see boto3 installed . But I keep ge...
2020/05/19
[ "https://Stackoverflow.com/questions/61902162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3987161/" ]
You may be more familiar and comfortable with the `map` function from its common use in `Iterator`s but using `map` to work with `Result`s and `Option`s is also considered idiomatic in Rust. If you'd like to make your code more concise you can use [`map_or`](https://doc.rust-lang.org/std/result/enum.Result.html#method....
Alternatively, if you find the `map` unclear, you could use an `if` or `match` to be more explicit (and verbose): ``` let is_dir = if let Ok(file_type) = entry.file_type() { file_type.is_dir() } else { false }; ``` or ``` let is_dir = match entry.file_type() { Ok(file_type) => file_type.is_dir(), _ ...
349
72,289,828
I have source of truth stored in yaml file sot-inventory.yaml ``` - Hostname: NY-SW1 IP mgmt address: 10.1.1.1 OS: IOS Operational status: Install Role of work: Switch Site: New_York - Hostname: MI-SW1 IP mgmt address: 11.1.1.1 OS: NX-OS Operational status: Install Role of work: Switch Site: Maiami...
2022/05/18
[ "https://Stackoverflow.com/questions/72289828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19145073/" ]
The **X.509 Client Certificate** option which is part of the docker plugin, has recently changed its name as it used to be named **Docker Certificate Directory** (the behavior itself has not changed), therefore is it is tricky to find it in the `withCredentials` [Documentation](https://www.jenkins.io/doc/pipeline/steps...
On my Jenkins, it's ``` withCredentials([certificate(aliasVariable: 'ALIAS_VAR', credentialsId: 'myClientCert', keystoreVariable: 'KEYSTORE_VAR', passwordVariable: 'PASSWORD_VAR')]) { ... } ``` Hint: If you add `/pipeline-syntax/` to your Jenkins URL, it will take you to a snippet generator that wil...
350
57,218,302
I have a an excel sheet with one column, the header is Name and the row below it says Jerry. All i want to do is append to this using python with the header: Age then a row below that saying e.g. 14. How do i do this? ``` with open('simpleexcel.csv', 'r') as f_input: # Declared variable f_input to open and read th...
2019/07/26
[ "https://Stackoverflow.com/questions/57218302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6714667/" ]
Use `next(input_reader)` to get the header and then append the new column name and write it back to csv. **Ex:** ``` with open('simpleexcel.csv', 'r') as f_input: # Declared variable f_input to open and read the input file input_reader = csv.reader(f_input) # this will iterate ober lines from input file w...
I don't know what you are trying to accomplish here but for your sample case this can be used. ``` import csv with open('simpleexcel.csv', 'r') as f_input: input_reader = list(csv.reader(f_input)) input_reader[0].append('Age') for row in input_reader[1:]: row.append(14) with open('Outputfile.csv', "w", newl...
351
66,948,944
I managed to find python code that defines a LinkedList class and all the defacto methods in it but quite can't figure out what each line of code does...Can someone comment on it explaining what each line does so i can grasp a better understanding of LinkedLists in python? ``` class Node:#what is the significance of a...
2021/04/05
[ "https://Stackoverflow.com/questions/66948944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Usually people use macros to append `__LINE__` to the declaration to allow for multiple declarations in one scope block. Prior to C++20 this was impossible without macros. C++20 and later, with a little work, can use [`std::source_location`](https://en.cppreference.com/w/cpp/utility/source_location). Jason Turner has...
I was initially not sure to grasp the advantage of that macro, apart hiding the timer instance name (and cause possible conflicts). But I think that the intent could be to have the possibility to do this: ``` #ifdef _DEBUG #define SCOPED_TIMER(slot) ScopedTimer __scopedTimer( slot ); #else #define SCOPED_TIMER(slo...
352
7,456,630
I have a python REST API server running on my laptop. I am trying to write a rest client in Android (using Eclipse ADT etc) to contact it using Apache's client (org.apache.http.client) libraries. The code is really simple, and basically does the following - ``` HttpGet httpget = new HttpGet(new URI("http://10.0.2.2...
2011/09/17
[ "https://Stackoverflow.com/questions/7456630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/856919/" ]
I was gonna post this code sample: ``` Process rsyncProc = Runtime.exec ("rsync"); OutputStreanm rsyncStdIn = rsyncProv.getOutputStream (); rsyncStdIn.write ("password".getBytes ()); ``` But [Vineet Reynolds](https://stackoverflow.com/users/3916/vineet-reynolds) was ahead of me. As Vineet Reynolds pointed out using...
You can write to the output stream of the `Process`, to pass in any inputs. However, this will require you to have knowledge of `rsync`'s behavior, for you must write the password to the outputstream only when the password prompt is detected (by reading the input stream of the `Process`). You may however, create a non...
353
10,971,649
> > **Possible Duplicate:** > > [How to read specific characters from lines in a text file using python?](https://stackoverflow.com/questions/10968973/how-to-read-specific-characters-from-lines-in-a-text-file-using-python) > > > I have a .txt file with lines looking like this > > Water 16:-30.4674 1:-30.4759...
2012/06/10
[ "https://Stackoverflow.com/questions/10971649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1447337/" ]
If the format is always the same you could do this for each line: ``` items = line.split()[1:] items = [item.split(':')[0] for item in items] ``` And then if you want them as integers: ``` items = map(int, items) ``` As for storing them, create a list before iterating over each line `rows = []` and then you can a...
Use split method and append it to your array: ``` myArray=line.split(':-') ```
358
14,574,595
What I'm trying to do is make a gaussian function graph. then pick random numbers anywhere in a space say y=[0,1] (because its normalized) & x=[0,200]. Then, I want it to ignore all values above the curve and only keep the values underneath it. ``` import numpy import random import math import matplotlib....
2013/01/29
[ "https://Stackoverflow.com/questions/14574595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1884319/" ]
The immediate cause of the error you're seeing is presumably this line (which should be identified by the full traceback -- it's generally quite helpful to post that): ``` Lower = numpy.where(foos[Upper]>(method[Upper])) ``` because the confusingly-named variable `method` is actually a `set`, as returned by your fun...
It's hard to read your code.. Anyway, you can't access a set using `[]`, that is, `foos[Upper]`, `method[Upper]`, etc are all illegal. I don't see why you convert `foo`, `x` into set. In addition, for a point produced by `method2`, say (x0, y0), it is very likely that x0 is not present in `x`. I'm not familiar with nu...
361
64,155,517
I am trying to create a CSS grid, but it gets scattered when using width. I want 3 posts on a row. I believe the problem might be with my border box. Only the desktop view is affected, mobile view looks perfectly normal. I am using `width: 33.333%` to achieve the grid. What is wrong with the CSS code? ```css /*----...
2020/10/01
[ "https://Stackoverflow.com/questions/64155517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6499765/" ]
You are better off using `flex-box` or `grid` for this. There are a few things with your code that needed to be changed: 1. You have `float` and `width` set on your inner `li` item. That doesn't work when it's a child element, so, the `li` was floating in relation to its parent `ul`. 2. You can move the padding on the...
I don't get why using that HTML strucure, it looks unnecessarily complicated! Your problem is that the divs(.cont.contt) have a height and interacts with each other misaliging everything else, I don't think is a correct approach. A partial solution might be to forse a height to 0 but is not clean at all. I'd suggest ...
362
18,519,217
When creating a string out of many substrings what is more pythonic - + or %? ``` big_string = string1 + string2 + ... + stringN big_string = '' for i in range(n): big_string+=str(i) ``` or ``` big_string = "%s%s...%s" % (string1, string2, ... , stringN) big_string = '' for i in range(n): big_string = "%s...
2013/08/29
[ "https://Stackoverflow.com/questions/18519217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1445070/" ]
``` big_string = ''.join([string1, string2, ..., stringN]) ```
`big_string = reduce(lambda x, y: x + y, [string1, string2, ..., stringN], "")`
363
37,002,134
I have just started to use Tensorflow and I have done "hello world" with my test.py file. Moving on to next step, I started to do tutorial(<https://www.tensorflow.org/versions/master/tutorials/mnist/beginners/index.html>). This is what I have done > > $ git clone <https://github.com/tensorflow/tensorflow> > > > a...
2016/05/03
[ "https://Stackoverflow.com/questions/37002134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6285272/" ]
You were pretty close with the `drop` function, but I suggest you take a look at its documentation. It drops the given number of elements from the beginning of the list. What you actually want is `take` the first one and `takeRight` the last one: ``` mp.mapValues(list => list.take(1) ++ list.takeRight(1)) ``` This ...
It looks like your map has lists of tuples, not lists of strings. Something like this should work: ``` m.mapValues { case List((a,b,c)) => (a,c) } ``` or ``` m.mapValues { case List((a,b,c)) => List((a,c)) } ``` or ``` m.mapValues { case List((a,b,c)) => List(a,c) } ``` ... depending on what type of ou...
364
10,713,966
I am trying to migrate over to Python from Matlab and can't figure out how to get interactive(?) plotting working within the Spyder IDE. My test code is shown below. With the .ion() nothing happens, I get a quick flash of a figure being drawn then the window instantly closes and spits out my Hello. Without the .ion() t...
2012/05/23
[ "https://Stackoverflow.com/questions/10713966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1411736/" ]
The run configuration should be set to *Execute in current Python or IPython interpreter* which by default allows for interactive plotting. If the interpreter is set to *Execute in a new dedicated Python interpreter* then *Interact with the Python interpreter after execution* must be selected.
in my case, these were the default settings in spyder however it still didn't show the plot until I typed: **%matplotlib inline** Not sure if this is helpful but thought of sharing here.
365
25,858,331
Is there a meaningful difference between ``` if self.pk is not None: ``` and ``` if self.pk: ``` when checking a model field in python django? Other languages have all kinds of differing 'correct' ways to check for a variable being null, empty, nonexistant, whatever. a) I don't know how python handles the che...
2014/09/15
[ "https://Stackoverflow.com/questions/25858331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3539965/" ]
The first check is checking that the primary key is not [`None`](https://docs.python.org/3/library/constants.html#None). The second is checking that the primary key is [truthy](https://docs.python.org/3/library/stdtypes.html#truth-value-testing). So yes, there is a difference.
`Pk` is a [property](https://github.com/django/django/blob/1.7/django/db/models/base.py#L515) that usually resolves to `id`. There is no magic other than that. So the only difference between the two statements is how Python treats them. The first one explicitely tests if `pk` is None, whereas the second one will pass ...
366
4,290,399
In other languages ``` for(i=0; i<10; i++){ if(...){ i = 4; } } ``` the loop will go up, but in python,it doesn't work ``` for i in range(1, 11): if ...: i = 4 ``` So can I go up in a loop with 'for'?
2010/11/27
[ "https://Stackoverflow.com/questions/4290399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522057/" ]
The problem here is that `range(1, 11)` returns a list and `for...in` iterates over the list elements hence changing `i` to something else doesn't work as expected. Using a `while` loop should solve your problem.
Just some food for thought. The for loop loops over an iterable. Create your own iterable that you can move forward yourself. ``` iterator = iter(range(11)) for i in iterator: print 'for i = ', i try: print 'next()', iterator.next() except StopIteration: continue >>> foo() for i = 0 next...
367
53,158,284
While trying to input my API key python is giving me a line too long code ``` E501: line too long ``` What I have is ``` notifications_client = NotificationsAPIClient(aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-11111aaa1a1a-aa11a1a1-0aa1-11a1-1111-1aa111a0a111) ``` For obvious reasons I have changed the API key to h...
2018/11/05
[ "https://Stackoverflow.com/questions/53158284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5348714/" ]
E501 is a linter error, not a Python interpreter error. Your code, in theory, should work just fine. If you want to prevent this error, simply break the value up (assuming it's a string ... you don't make that clear): ``` my_key = ('aaaaaaa_aaaaaaaa-11aa1a1a-aa11-111a-aaaa-' '11111aaa1a1a-aa11a1a1-0aa1-11a1-...
Use \ to break your line. Like; notifications\_client = NotificationsAPIClient(aaaaaaa\_aaaaaaaa-11aa1a1a-\ aa11-111a-aaaa-11111aaa1a1a-\ aa11a1a1-0aa1-11a1-1111-1aa111a0a111)
377
43,519,906
I wrote a program that does the job, however it is not very pythonic, not pythonic and definitly not beautiful. The program must concatenate two numpy arrays in the following manner: As an example list0 and list1 are the input ``` list0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] list1 = [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 1...
2017/04/20
[ "https://Stackoverflow.com/questions/43519906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6786718/" ]
Being NumPy tagged, here's one with it - ``` np.vstack((list0, list1)).ravel('F').tolist() ``` [`ravel()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html) here flattens in `fortran` order with the `F` specifier. A shorter version with [`np.c_`](https://docs.scipy.org/doc/numpy/reference/gener...
Nice one liner with itertools ``` from itertools import chain chain(*zip(list0, list1)) [0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6, 8, 7, 9, 8, 10, 9, 11] ```
382
11,400,590
I have a python dictionary consisting of JSON results. The dictionary contains a nested dictionary, which contains a nested list which contains a nested dictionary. Still with me? Here's an example: ``` {'hits':{'results':[{'key1':'value1', 'key2':'value2', 'key3':{'sub_key':'...
2012/07/09
[ "https://Stackoverflow.com/questions/11400590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1046501/" ]
The most appropriate way is to override the `clean` method of your model: ``` from django.template import defaultfilters class Article(models.Model): ... def clean(self): if self.slug.strip() == '': self.slug = defaultfilters.slugify(self.title) super(Article, self).clean() ``` ...
I would build it into the input form and use a ModelAdmin or ModelForm. Admin Form: ``` from django.contrib import admin class ArticleAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title', )} ``` ModelForm: ``` class ArticleForm(forms.ModelForm): class Meta: model = Article def c...
384
11,928,277
I cant seem to install Rpy2 for python. Initially I ran across the problem where it displayed the following error. ``` Tried to guess R's HOME but no R command in the PATH. ``` But then I followed instructions in the following thread: [trouble installing rpy2 on win7 (R 2.12, Python 2.5)](https://stackoverflow.com/q...
2012/08/13
[ "https://Stackoverflow.com/questions/11928277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1610626/" ]
Me too, I had many difficulties getting rpy2 up and running, even after following the crucial link in the answer from lgauthier. But, the final help came from one of the replies on that mailing list. Summarized, these were the 4 steps needed to get rpy2 up and running on my Windows7 computer: 1. Install rpy2 from thi...
Check the [rpy-mailing list](http://www.mail-archive.com/rpy-list@lists.sourceforge.net/msg03340.html) on July 18th. There is slight progress on the Windows front for rpy2, and people are reporting some success running it.
387
62,686,320
How do I stop from printing an extra input line? I'm new with python/coding ``` class1 = "Math" class2 = "English" class3 = "PE" class4 = "Science" class5 = "Art" def get_input(className): classInput = raw_input("Enter the score you received for " + className + ": ") while int(classInput) >= 101 or int(classInput...
2020/07/01
[ "https://Stackoverflow.com/questions/62686320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13850019/" ]
Inside your print, you call `get_input()` method twice: ``` print "Your " + class1 + " score is " + str(get_input(class1)) + ", you got a " + get_letter_grade(get_input(class1)) ``` What you need to do is store your score by calling `get_input()` method once and use the stored value in print method: ``` score = ge...
I would separate out your calls to `get_input` from your print statement, not just here, but generally. ``` score = str(get_input(class1)) print "Your " + class1 + " score is " + score + ", you got a " + get_letter_grade(score) ``` As a rule of thumb, any user input should almost always be immediately stored in a v...
390
48,326,721
I'm trying to mock **elasticsearch.Elasticsearch.indices.exists** function in my Python test case, but I'm getting the following import error. However, mock just **elasticsearch.Elasticsearch** was working fine. ``` @ddt class TestElasticSearchConnector(unittest.TestCase): @patch('elasticsearch.Elasticsearch.ind...
2018/01/18
[ "https://Stackoverflow.com/questions/48326721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1187968/" ]
This is legitimately an error. When specifying an attribute/method to mock, it must exist on the object (in this case a class). Perhaps you were expecting this attribute to exist, but it only present on the instantiated object. ``` In [1]: from elasticsearch import Elasticsearch In [2]: Elasticsearch.indices ---------...
The Elasticserch library generates the `indices` attribute when you instantiante an `Elasticsearch()` object. And it does so using a class of the library called `IndicesClient`, and it is that class who has the `exists` method. Therefore, if you mock the response of that method of the `IndicesClient` class, you test sh...
391
13,617,019
I have a code with heavy symbolic calculations (many multiple symbolic integrals). Also I have access to both an 8-core cpu computer (with 18 GB RAM) and a small 32 cpu cluster. I prefer to remain on my professor's 8-core pc rather than to go to another professor's lab using his cluster in a more limited time, however,...
2012/11/29
[ "https://Stackoverflow.com/questions/13617019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1631618/" ]
I would look in to `multiprocessing` [(doc)](http://docs.python.org/2/library/multiprocessing.html) which provides a bunch of nice tools for spawning and working with sub-processes. To quote the documentation: > > multiprocessing is a package that supports spawning processes using an > API similar to the threading...
I recently ran into a similar problem. However, the following solution is only valid if (1) you wish to run the python script individually on a group of files, AND (2) each invocation of the script is independent of the others. If the above applies to you, the simplest solution is to write a wrapper in bash along the ...
392
31,961,754
I've got a python script that uses the **ansible** package to ping some remote servers. When executed manually (*python devmanager.py*) it works ok, but when the script is managed with **supervisor** it raises the following error: ``` Could not make dir /$HOME/.ansible/cp: [Errno 13] Permission denied: '/$HOME ``` T...
2015/08/12
[ "https://Stackoverflow.com/questions/31961754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315521/" ]
You may give a try by altering the parameter "remote\_tmp" in ansible.cfg. Default:-`$HOME/.ansible/tmp` Update:-`/tmp/.ansible/tmp` On this case who ever the user try to run the playbook will have enough permission to create necessary temporary files in /tmp directory.
Yes, it seems that it doesn't escape the `$HOME` variable and tries to write under `/$HOME`.
395
72,815,781
I am getting below error when using geopandas and shapely ``` AttributeError: 'DataFrame' object has no attribute 'crs' ``` Below is the code: ``` #geometry = [Point(xy) for xy in zip(complete_major_accidents['longitude'], complete_major_accidents['latitude'])] #crs='none' geometry = gpd.points_from_xy(complete_non...
2022/06/30
[ "https://Stackoverflow.com/questions/72815781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10908274/" ]
I am finally able to resolve it by changing this below piece of code ``` gdf = GeoDataFrame(complete_major_accidents, geometry) ``` to ``` gdf = GeoDataFrame(complete_nonmajor_accidents, geometry = geometry) ```
I got the same error after updating Geopandas from an older version. Following fix did the trick. `self.ax = gpd.GeoDataFrame().plot(figsize=(18, 12))` to `self.ax = gpd.GeoDataFrame(geometry=[]).plot(figsize=(18, 12))`
396
64,886,214
I'm a new python developer and I watched a few tutorials on YouTube explaining the functions and the uses for this module, but I cannot get it to work. I installed the module via pip so I don't think that is the issue. ``` import urllib.request x = urllib.request.urlopen('https://www.google.com') print(x.read()) ``...
2020/11/18
[ "https://Stackoverflow.com/questions/64886214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14558709/" ]
I gave the answer to this in the previous question you asked.You do not make any effort and do not follow the answers to the questions you ask.This is probably your homework or part of homework and you just wait for a solution.I hope you will share your works and then ask questions, this can be better for your improvem...
You should not use `from` as a variable since it's a reserved keyword in python. Maybe that's what causing your problem.
397
31,969,540
My python scripts often contain "executable code" (functions, classes, &c) in the first part of the file and "test code" (interactive experiments) at the end. I want `python`, `py_compile`, `pylint` &c to completely ignore the experimental stuff at the end. I am looking for something like `#if 0` for `cpp`. **How ca...
2015/08/12
[ "https://Stackoverflow.com/questions/31969540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/850781/" ]
Use `ipython` rather than `python` for your REPL It has better code completion and introspection and when you paste indented code it can automatically "de-indent" the pasted code. Thus you can put your experimental code in a test function and then paste in parts without worrying and having to de-indent your code. If ...
I suggest you use a proper version control system to keep the "real" and the "experimental" parts separated. For example, using Git, you could only include the real code without the experimental parts in your commits (using [`add -p`](https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging#Staging-Patches)), and ...
399
19,167,550
My code goes through a number of files reading them into lists with the command: ``` data = np.loadtxt(myfile, unpack=True) ``` Some of these files are empty (I can't control that) and when that happens I get this warning printed on screen: ``` /usr/local/lib/python2.7/dist-packages/numpy/lib/npyio.py:795: UserWarn...
2013/10/03
[ "https://Stackoverflow.com/questions/19167550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1391441/" ]
You will have to wrap the line with `catch_warnings`, then call the `simplefilter` method to suppress those warnings. For example: ``` import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") data = np.loadtxt(myfile, unpack=True) ``` Should do it.
One obvious possibility is to pre-check the files: ``` if os.fstat(myfile.fileno()).st_size: data = np.loadtxt(myfile, unpack=True) else: # whatever you want to do for empty files ```
409
22,345,798
I currently have a working python code in command line. How can I convert this into a GUI program. I know how to design a GUI(make buttons,callback function, create text field, label widget...). My question is how should be the GUI connected to the existing program. *should I make a python file called gui.py and impor...
2014/03/12
[ "https://Stackoverflow.com/questions/22345798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2332665/" ]
As the GUI is the user front-end, and because your function already exists, the easiest is to make GUI class to import the function. On event, the GUI would call the function and handle the display to the user. In fact, it's exactly what you have done with a Command-Line Interface (CLI) in your example code :)
I would say the answer strongly depends on your choice of GUI-framework to use. For a small piece of code like the one you posted you probably may want to rely on "batteries included" tkinter. In this case I agree to the comment of shaktimaan to simply include the tkinter commands in your existing code. But you have ma...
410
63,580,623
Right now I'm sitting on a blank file which consists only of the following: ``` import os import sys import shlex import subprocess import signal from time import monotonic as timer ``` I get this error when I try to run my file: ImportError: Cannot import name monotonic If it matters, I am on linux and my python v...
2020/08/25
[ "https://Stackoverflow.com/questions/63580623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10847907/" ]
You'll need to use regular Producer and execute the serialization functions yourself ``` from confluent_kafka import avro from confluent_kafka.avro import CachedSchemaRegistryClient from confluent_kafka.avro.serializer.message_serializer import MessageSerializer as AvroSerializer avro_serializer = AvroSerializer(sche...
`AvroProducer` assumes that both keys and values are encoded with the schema registry, prepending a magic byte and the schema id to the payload of both the key and the value. If you want to use a custom serialization for the key, you could use a `Producer` instead of an `AvroProducer`. But it will be your responsibili...
411
69,833,702
I keep running into this use and I haven't found a good solution. I am asking for a solution in python, but a solution in R would also be helpful. I've been getting data that looks something like this: ``` import pandas as pd data = {'Col1': ['Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex...
2021/11/04
[ "https://Stackoverflow.com/questions/69833702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14167846/" ]
In `R`, ``` data <- data.frame( Col1 = c('Bob', '101', 'First Street', '', 'Sue', '102', 'Second Street', '', 'Alex' , '200', 'Third Street', '') ) k<-which(grepl("Street", data$Col1) == TRUE) j <- k-1 i <- k-2 data.frame( Name = data[i,], Adress = data[j,], Street = data[k,] ) Name Adress Street 1 ...
### Python3 In Python 3, you can convert your DataFrame into an array and then reshape it. ```py n = df.shape[0] df2 = pd.DataFrame( data=df.to_numpy().reshape((n//4, 4), order='C'), columns=['Name', 'Address', 'Street', 'Empty']) ``` This produces for your sample data this: ``` Name Address Str...
412
56,746,773
I had a college exercise which contains a question which asked to write a function which returns how many times a particular key repeats in an object in python. after researching on dictionaries I know that python automatically ignores duplicate keys only keeping the last one. I tried to loop over each key the conventi...
2019/06/25
[ "https://Stackoverflow.com/questions/56746773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9096030/" ]
Just to mention other options note that you can use the `filter` function here: ``` julia> filter(row -> row.a == 2, df) 1×2 DataFrame │ Row │ a │ b │ │ │ Int64 │ String │ ├─────┼───────┼────────┤ │ 1 │ 2 │ y │ ``` or ``` julia> df[filter(==(2), df.a), :] 1×2 DataFrame │ Row │ a │ b ...
Fortunately, you only need to add one character: `.`. The `.` character enables broadcasting on any Julia function, even ones like `==`. Therefore, your code would be as follows: ``` df = DataFrame(a=[1,2,3], b=["x", "y", "z"]) df2 = df[df.a .== 2, :] ``` Without the broadcast, the clause `df.a == 2` returns `false`...
419
38,212,340
I am trying to extract all those tags whose class name fits the regex pattern frag-0-0, frag-1-0, etc. from [this link](http://de.vroniplag.wikia.com/wiki/Aak/002) I am trying to retrieve it using the following code ``` driver = webdriver.Chrome(chromedriver) for frg in frgs: driver.get(URL + frg[1:])...
2016/07/05
[ "https://Stackoverflow.com/questions/38212340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6213939/" ]
Try to remove DownloadCachePluginBootstrap.cs and FilePluginBootstrap.cs just leave manual setup inside InitializeLastChance(). It seems that there is a problem with loading order.
As @Piotr mentioned: > > Try to remove DownloadCachePluginBootstrap.cs and FilePluginBootstrap.cs just > leave manual setup inside InitializeLastChance(). It seems that there is a > problem with loading order. > > > That fixed the issue for me as well. I just want to share my code in the Setup.cs of the iOS...
420
44,206,346
How can I stop pgadmin 4 process? I ran pgadmin 4 next method: `python3 /usr/local/pgAdmin4.py` My idea using Ctrl-c.
2017/05/26
[ "https://Stackoverflow.com/questions/44206346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8071434/" ]
If you are using pgAdmin 4 on mac OS or Ubuntu, you can use system tool bar (at the top of the screen) icon for this. After you start pgAdmin server the icon with elephant head should appear. If you click it you will have an option `Shut down server`.
You can shut down the server[![enter image description here](https://i.stack.imgur.com/qzpud.png)](https://i.stack.imgur.com/qzpud.png) from the top menu as shown. Just click the Shutdown server and it will work.
421
74,495,864
I have a huge list of sublists, each sublist consisting of a tuple and an int. Example: ``` [[(1, 1), 46], [(1, 2), 25.0], [(1, 1), 25.0], [(1, 3), 19.5], [(1, 2), 19.5], [(1, 4), 4.5], [(1, 3), 4.5], [(1, 5), 17.5], [(1, 4), 17.5], [(1, 6), 9.5], [(1, 5), 9.5]] ``` I want to create a unique list of those tuples cor...
2022/11/18
[ "https://Stackoverflow.com/questions/74495864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20543467/" ]
From the helpfile you can read: > > If there is a header and the first row contains one fewer field than the number of columns, the first column in the input is used for the row names. Otherwise if **row.names is missing, the rows are numbered**. > > > That explains the same behavior when you set row.names=NULL o...
The first two executions are functionally the same, when you don't use row.names parameter of read.table, it's assumed that its value is NULL. The third one fails because `1` is interpreted as being a vector with length equal to the number of rows filled with the value 1. Hence the error affirming you can't have two r...
422
10,104,805
I have installed python 32 package to the > > C:\python32 > > > I have also set the paths: > > PYTHONPATH | C:\Python32\Lib;C:\Python32\DLLs;C:\Python32\Lib\lib-tk; > > > PATH ;C:\Python32; > > > I would like to use the "2to3" tool, but CMD does not recognize it. ``` CMD: c:\test\python> 2to3 test.py `...
2012/04/11
[ "https://Stackoverflow.com/questions/10104805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1318239/" ]
2to3 is actually a Python script found in the Tools/scripts folder of your Python install. So you should run it like this: ``` python.exe C:\Python32\Tools\scripts\2to3.py your-script-here.py ``` See this for more details: <http://docs.python.org/library/2to3.html>
You can set up 2to3.py to run as a command when you type 2to3 by creating a batch file in the same directory as your python.exe file (assuming that directory is already on your windows path - it doesn't have to be this directory it just is a convenient, relatively logical spot). Lets assume you have python installed i...
423
8,576,104
Just for fun, I've been using `python` and `gstreamer` to create simple Linux audio players. The first one was a command-line procedural script that used gst-launch-0.10 playbin to play a webstream. The second version was again procedural but had a GUI and used playbin2 to create the gstreamer pipeline. Now I'm trying ...
2011/12/20
[ "https://Stackoverflow.com/questions/8576104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1106979/" ]
If you use this, you will pass the element value as param. ``` javascript:checkStatus('{$k->bus_company_name}','{$k->bus_id}','{$k->bus_time}',document.getElementById('dt').value) ``` But you also can get inside the function checkStatus.
Since you're looping through a list of items, I would recommend using the current index at each iteration to create a unique date ID. You can then pass this to your script and get the element's value by ID there: ``` {foreach name = feach key = i item = k from = $allBuses} {$k->bus_company_name}<br /> ...
426
29,476,054
I have a list of things I want to filter out of a csv, and I'm trying to figure out a pythonic way to do it. EG, this is what I'm doing: ``` with open('output.csv', 'wb') as outf: with open('input.csv', 'rbU') as inf: read = csv.reader(inf) outwriter = csv.writer(outf) notstrings = ['and...
2015/04/06
[ "https://Stackoverflow.com/questions/29476054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2898989/" ]
You can use the [`any()` function](https://docs.python.org/2/library/functions.html#any) to test each of the words in your list against a column: ``` if not any(w in row[3] for w in notstrings): # none of the strings are found, write the row ``` This will be true if *none* of those strings appear in `row[3]`. It...
You can use sets. In this code, I transform your list into a set. I transform your `row[3]` into a set of words and I check the intersection between the two sets. If there is not intersection, that means none of the words in notstrings are in `row[3]`. Using sets, you make sure that you match only words and not parts ...
427
62,514,068
I am trying to develop a AWS lambda to make a `rollout restart deployment` using the python client. I cannot find any implementation in the github repo or references. Using the -v in the `kubectl rollout restart` is not giving me enough hints to continue with the development. Anyways, it is more related to the python ...
2020/06/22
[ "https://Stackoverflow.com/questions/62514068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13791762/" ]
The python client interacts directly with the Kubernetes API. Similar to what `kubectl` does. However, `kubectl` added some utility commands which contain logic that is not contained in the Kubernetes API. Rollout is one of those utilities. In this case that means you have two approaches. You could reverse engineer th...
@Andre Pires, it can be done like this way : ``` data := fmt.Sprintf(`{"spec":{"template":{"metadata":{"annotations":{"kubectl.kubernetes.io/restartedAt":"%s"}}}},"strategy":{"type":"RollingUpdate","rollingUpdate":{"maxUnavailable":"%s","maxSurge": "%s"}}}`, time.Now().String(), "25%", "25%") newDeployment, err := cli...
428
51,314,875
Seems fairly straight forward but whenever I try to merely import the module I get this: ``` from pptx.util import Inches from pptx import Presentation --------------------------------------------------------------------------- ImportError Traceback (most recent call last) ~\AppData\...
2018/07/12
[ "https://Stackoverflow.com/questions/51314875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9459261/" ]
I've finally figured it out by creating a small app and trying to reproduce it. As Dmitry and Paulo have pointed out, it should work. However, it should work for any new project and in my case the project is 10 years old and has lots of legacy configurations. **TL;DR:** The `async`/`await` keywords do not work very we...
For retrieving files in `ASP.NET Core` try using [`IFileProvider`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.fileproviders.ifileprovider) instead of `HttpContext` - see [File Providers in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/file-providers) documentation for m...
429
35,796,968
I have a python GUI application. And now I need to know what all libraries the application links to. So that I can check the license compatibility of all the libraries. I have tried using strace, but strace seems to report all the packages even if they are not used by the application. And, I tried python ModuleFinder...
2016/03/04
[ "https://Stackoverflow.com/questions/35796968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2109788/" ]
You can give a try to the library <https://github.com/bndr/pipreqs> found following the guide <https://www.fullstackpython.com/application-dependencies.html> --- The library `pipreqs` is pip installable and automatically generates the file `requirements.txt`. It contains all the imports libraries with versions you a...
Install yolk for python2 with: ``` pip install yolk ``` Or install yolk for python3 with: ``` pip install yolk3k ``` Call the following to get the list of eggs in your environment: ``` yolk -l ``` Alternatively, you can use [snakefood](http://furius.ca/snakefood/) for graphing your dependencies, as answered in...
430
36,075,407
I'm developing python flask app. I have a problem mysqldb. If I type 'import MySQLdb' on python console. It show "ImportError: No module named 'MySQLdb' " On my computer MySQL-python installed and running on <http://127.0.0.1:5000/> How can I solve this problem?
2016/03/18
[ "https://Stackoverflow.com/questions/36075407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5736099/" ]
If you are using Python **2.x**, one of the following command will install `mysqldb` on your machine: ``` pip install mysql-python ``` or ``` easy_install mysql-python ```
**for python 3.x install** pip install mysqlclient
433
37,691,320
Im very new to `c` and am trying to make a `while` loop that checks if the parameter is less than or equal to a certain number but also if it is greater than or equal to a different number as well. I usually code in `python` and this is example of what I'm looking to do in `c`: `while(8 <= x <= 600)`
2016/06/08
[ "https://Stackoverflow.com/questions/37691320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5355216/" ]
``` while (x >= 8 && x <= 600){ } ```
The relational and equality operators (`<`, `<=`, `>`, `>=`, `==`, and `!=`) don't work like that in C. The expression `a <= b` will evaluate to 1 if the condition is true, 0 otherwise. The operator is *left-associative*, so `8 <= x <= 600` will be evaluated as `(8 <= x) <= 600`. `8 <= x` will evaluate to 0 or 1, both ...
435
69,090,032
Using Python. I have two data frames df1: ``` email timezone country_app_web 0 nhvfstdfg@vxc.com Europe/Paris NaN 1 taifoor096@gmail.com NaN FR 2 nivo1996@gmail.com US/Eastern NaN 3 jorgehersan90@gmail.com NaN UK 4 s...
2021/09/07
[ "https://Stackoverflow.com/questions/69090032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16677735/" ]
if you want to remove all object in `products` use this ``` db.collection.update({}, { $set: { products: {} } }) ``` <https://mongoplayground.net/p/aBSnpRhblxt> if you want to delete specific key (gCx5qSTLvdWeel8E2Yo7m) from product use this ``` db.collection.update({}, { $unset: { "products.gCx5qSTL...
Thank you for your answer Mohammad but I think this works for MongoDB, but in mongoose, we need to set the value as 1 to remove the item with unset. Here is my working example ```js const { ids } = req.body; try { const order = await Order.findById(req.params.id).populate('user', 'name').exec(); if (!order)...
438
61,746,984
I have a script which has been simplified to provide me with a sequence of numbers. I have run this under windows 10, using both Python3.6 and Python3.8 If the script is run with the line the line : pal\_gen.send(10 \*\* (digits)) commented out, I get what I expected. But I want to change the sequence when num % 10 = ...
2020/05/12
[ "https://Stackoverflow.com/questions/61746984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5467308/" ]
I don't know why you expect result `0, 10, 20, 20, 20` if you send `10`, `100`, `1000`, `10000` In second version you have to send ``` i = pal_gen.send(10*(digits-1)) ``` but it will gives endless `20` so if you expect other values then it will need totally different code. --- ``` def infinite_pal(): num = ...
Many thanks for the above comments. In case anyone else is new to generators in Python, I make the following comments. The first example came from a web site (2 sites in fact) that supposedly explained Python generators. I appreciate there was an error in the .send parameter, but my real concern was why the first appro...
439
45,851,791
I am running the docker image for snappydata v0.9. From inside that image, I can run queries against the database. However, I cannot do so from a second server on my machine. I copied the python files from snappydata to the installed pyspark (editing snappysession to SnappySession in the imports) and (based on the ans...
2017/08/24
[ "https://Stackoverflow.com/questions/45851791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/767565/" ]
Try this: ``` from random import randint print( "You rolled " + ",".join(str(randint(1,6)) for j in range(6)) ) ```
If you're using python 3, which it appears you are, you could very simply print like that printing "you rolled" and then the numbers one at a time with the print argument 'end' set to a blank string ``` print("You rolled ", end='') for i in range(6): print(str(random.randint(1,6)), end='') if i < 5: ...
440
10,656,147
I figured out how to run my Django application via `sudo python /home/david/myproject/manage.py runserver 68.164.125.221:80`. However, after I quit terminal, the server stops running. I tried to run this process in the background, but the server just shuts down quickly after I execute `sudo python /home/david/myprojec...
2012/05/18
[ "https://Stackoverflow.com/questions/10656147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/795319/" ]
Meet [screen](http://www.gnu.org/software/screen/). Connect through ssh, start screen. This open a virtual console emulator on top of the one provided by ssh. Start your server there. Then press Ctrl-a, then d. This detach the screen session, keeping it running in the background. To [R]e-attach to it, use screen -r....
Use `screen` to create a new virtual window, and run the server there. ``` $ screen $ python manage.py runserver ``` You will see that Django server has started running. Now press `Ctrl+A` and then press the `D` key to detach from that screen. It will say: ``` $ [detached from ###.pts-0.hostname] ``` You can no...
442
34,086,062
today I'm updated the elastic search from 1.6 to 2.1, because 1.6 is vulnerable version, after this update my website not working, give this error : ``` Traceback (most recent call last): File "manage.py", line 8, in <module> from app import app, db File "/opt/project/app/__init__.py", line 30, in <module> ...
2015/12/04
[ "https://Stackoverflow.com/questions/34086062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5544303/" ]
`jeuResultats.next();` moves your result to the next row. You start with 0th row, i.e. when you call `.next()` it reads the first row, then when you call it again, it tries to read the 2nd row, which does not exist. *Some additional hints, not directly related to the question:* 1. Java Docs are a good place to star...
Make the below changes in you code. Currently the next() method is shifting result list to fetch the data at 1st index, whereas the data is at the 0th Index: ``` boolean result = false; try{ result = jeuResultats.next(); } catch (SQLException e) { e.printStackTrace(); } if (!result) { loadJSP("/...
445
48,074,568
as part of Unity's ML Agents images fed to a reinforcement learning agent can be converted to greyscale like so: ``` def _process_pixels(image_bytes=None, bw=False): s = bytearray(image_bytes) image = Image.open(io.BytesIO(s)) s = np.array(image) / 255.0 if bw: s = np.mean(s, axis=2) s ...
2018/01/03
[ "https://Stackoverflow.com/questions/48074568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3515869/" ]
Won't just doing this work? ``` plt.imshow(s[..., 0]) plt.show() ``` Explanation `plt.imshow` expects either a 2-D array with shape `(x, y)`, and treats it like grayscale, or dimensions `(x, y, 3)` (treated like RGB) or `(x, y, 4)` (treated as RGBA). The array you had was `(x, y, 1)`. To get rid of the last dimensi...
It looks like the grayscale version has an extra single dimension at the end. To plot, you just need to collapse it, e.g. with [`np.squeeze`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.squeeze.html): ``` plt.imshow(np.squeeze(s)) ```
448
38,510,140
What is the difference between a list & a stack in python? I have read its explanation in the python documentation but there both the things seems to be same? ``` >>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> sta...
2016/07/21
[ "https://Stackoverflow.com/questions/38510140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621144/" ]
A stack is a *data structure concept*. The documentation uses a Python `list` object to implement one. That's why that section of the tutorial is named *Using Lists as Stacks*. Stacks are just things you add stuff to, and when you take stuff away from a stack again, you do so in reverse order, first in, last out style...
A "stack" is a specific application of `list`, with operations limited to appending (pushing) to and popping (pulling) from the end.
449
18,971,162
I am trying to create a simple python calculator for an assignment. The basic idea of it is simple and documented all over online, but I am trying to create one where the user actually inputs the operators. So instead of printing 1: addition, 2: subtraction, etc, the user would select + for addition, - for subtraction,...
2013/09/24
[ "https://Stackoverflow.com/questions/18971162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2809161/" ]
First off, you don't need to assign `choice` to zero Second, you have your code right, but you need to put quotes around the operators in your if statements like this ``` if choice == '+': ``` to show that you are checking for a string make your loop like this: ``` while 1: #or while True: #do stuff elif...
You should try replacing `if choice == +` by `if choice == "+"`. What you're getting from the input is actually a string, which means it can contain any character, even one that represents an operator.
454