title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to use correclty pyprind with scikit-learn?
38,473,538
<p>Currently I am using <a href="https://github.com/rasbt/pyprind" rel="nofollow">pyprind</a>, a library that implements a progress bar:</p> <pre><code>#Compute training time elapsed pbar = pyprind.ProgBar(45, width=120, bar_char='█') for _ in range(45): #Fiting clf = SVC().fit(X_train, y_train) pbar.upd...
3
2016-07-20T06:10:59Z
38,474,143
<p>I haven't used <code>pyprind</code> but I have used <code>progressbar</code>. Just install it using-</p> <pre><code>pip install progressbar </code></pre> <p>And then -</p> <pre><code>from progressbar import ProgressBar pbar = ProgressBar() for x in pbar(range(45)): clf = SVC().fit(X_train, y_train) </code></p...
1
2016-07-20T06:47:29Z
[ "python", "python-2.7", "python-3.x", "scikit-learn" ]
How to use correclty pyprind with scikit-learn?
38,473,538
<p>Currently I am using <a href="https://github.com/rasbt/pyprind" rel="nofollow">pyprind</a>, a library that implements a progress bar:</p> <pre><code>#Compute training time elapsed pbar = pyprind.ProgBar(45, width=120, bar_char='█') for _ in range(45): #Fiting clf = SVC().fit(X_train, y_train) pbar.upd...
3
2016-07-20T06:10:59Z
38,474,642
<p>Note that if you want more information regarding the learning process you can use <code>vebose</code> flag for that:</p> <pre><code>X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) y = np.array([1, 1, 2, 2]) clf = SVC(verbose =True) clf.fit(X, y) </code></pre> <p>Output:</p> <pre><code>optimization finished, #i...
1
2016-07-20T07:13:10Z
[ "python", "python-2.7", "python-3.x", "scikit-learn" ]
django search autocomplete not working
38,473,541
<p>I am trying to use autocomplete for search but I am getting this error "Uncaught TypeError: $(...).autocomplete is not a function".I have already included jquery library</p> <pre><code>&lt;head&gt; &lt;link rel="stylesheet" href="{% static 'styles.css' %}"&gt; &lt;link href="http://code.jquery.com/ui/1.10.4...
0
2016-07-20T06:11:14Z
38,473,636
<p>For autocomplete to work, you need to have have jQuery UI library included in your head. You can download it from here -> <a href="https://jqueryui.com/download/all/" rel="nofollow">https://jqueryui.com/download/all/</a></p>
0
2016-07-20T06:17:43Z
[ "python", "django" ]
django search autocomplete not working
38,473,541
<p>I am trying to use autocomplete for search but I am getting this error "Uncaught TypeError: $(...).autocomplete is not a function".I have already included jquery library</p> <pre><code>&lt;head&gt; &lt;link rel="stylesheet" href="{% static 'styles.css' %}"&gt; &lt;link href="http://code.jquery.com/ui/1.10.4...
0
2016-07-20T06:11:14Z
38,929,915
<p>Actually I think you are using two jquery remove this one</p> <p><code>&lt;script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"&gt;&lt;/script&gt;</code></p>
0
2016-08-13T06:30:17Z
[ "python", "django" ]
How to get string from a django.utils.safestring.SafeText
38,473,545
<p>I'm getting a django.utils.safestring.SafeText in my unit test:</p> <pre><code>ipdb&gt; mail.outbox[0].body u'Dear John Doe,&lt;br&gt;\n&lt;p&gt;\nYou have received a .. ipdb&gt; type(mail.outbox[0].body) &lt;class 'django.utils.safestring.SafeText'&gt; </code></pre> <p>I would like to convert the above into a st...
0
2016-07-20T06:11:24Z
38,474,051
<p>Create new string based on SafeText</p> <pre><code>str(mail.outbox[0].body) </code></pre>
1
2016-07-20T06:42:16Z
[ "python", "django", "python-2.7" ]
How to get string from a django.utils.safestring.SafeText
38,473,545
<p>I'm getting a django.utils.safestring.SafeText in my unit test:</p> <pre><code>ipdb&gt; mail.outbox[0].body u'Dear John Doe,&lt;br&gt;\n&lt;p&gt;\nYou have received a .. ipdb&gt; type(mail.outbox[0].body) &lt;class 'django.utils.safestring.SafeText'&gt; </code></pre> <p>I would like to convert the above into a st...
0
2016-07-20T06:11:24Z
38,477,425
<p>You can do the things you want to do with <code>django.utils.safestring.SafeText</code> object.You can apply almost every method as string on SafeText object. Available methods are </p> <pre><code>'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'i...
0
2016-07-20T09:27:39Z
[ "python", "django", "python-2.7" ]
Removing quotes from mysql query in Python
38,473,598
<p>I know that this question has been asked in the past, but thorough searching hasn't seemed to fix my issue. I'm probably just missing something simple, as I'm new to the Python-mysql connector supplied by mysql. </p> <p>I have a Python script which accesses a mysql database, but I'm having issues with removing quot...
0
2016-07-20T06:15:23Z
38,475,321
<h2>I personally believe this code is correct and safe, but you should be <em>extremely skeptical</em> of using code like this without carefully reviewing it yourself or (better yet) with the help of a security expert. I am not qualified to be such an expert.</h2> <p>Two important things I changed:</p> <ol> <li>I cha...
0
2016-07-20T07:46:12Z
[ "python", "mysql" ]
Django Templates: How best can the output of executing python code in a Django template be suppressed?
38,473,656
<p>Someone has probably encountered this before, and perhaps even the docs provide a solution already, but I couldn't find it yet. My situation is this:</p> <p>Just to illustrate the REAL PROBLEM: Assuming I have a list that I pass to the template, and which list I iterate over, with a <code>{% for...</code> in one in...
1
2016-07-20T06:19:14Z
38,473,766
<p>If you only need the top five elements, then I think the right way is to <strong>send a list</strong> of only top 5 elements from your views to your your html templates in the very first place.</p> <p>Also, if for some reason, you are not able to do that, then you should there is a thing in Django known as <strong>...
0
2016-07-20T06:26:17Z
[ "python", "django", "django-templates" ]
Django Templates: How best can the output of executing python code in a Django template be suppressed?
38,473,656
<p>Someone has probably encountered this before, and perhaps even the docs provide a solution already, but I couldn't find it yet. My situation is this:</p> <p>Just to illustrate the REAL PROBLEM: Assuming I have a list that I pass to the template, and which list I iterate over, with a <code>{% for...</code> in one in...
1
2016-07-20T06:19:14Z
38,475,317
<p>This is a bit of a hack, but it would solve your problem:</p> <pre><code>{{ Counter.increment|yesno:"," }} </code></pre> <p>(See the <a href="https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#yesno" rel="nofollow">documentation</a> on the <code>yesno</code> filter)</p>
1
2016-07-20T07:45:56Z
[ "python", "django", "django-templates" ]
Django Templates: How best can the output of executing python code in a Django template be suppressed?
38,473,656
<p>Someone has probably encountered this before, and perhaps even the docs provide a solution already, but I couldn't find it yet. My situation is this:</p> <p>Just to illustrate the REAL PROBLEM: Assuming I have a list that I pass to the template, and which list I iterate over, with a <code>{% for...</code> in one in...
1
2016-07-20T06:19:14Z
38,475,363
<p>Also you can use <code>with</code> tag and ignore variable:</p> <pre><code>{% with ignorevar=Counter.increment %}{% endwith %} </code></pre>
1
2016-07-20T07:49:03Z
[ "python", "django", "django-templates" ]
write on newline in a text file on each iteration using python
38,473,691
<p>want to write in newline in each iteration but it does not work out. i read random string using function getUser() and getFriends() from abc.txt. And write in text file new_file.txt but it writes in first line in each iteration</p> <p>output:['Larina'] ['Oormi', 'Palky']['Kavia'] ['Chakradhari', 'Chunni']</p> <p>...
1
2016-07-20T06:22:01Z
38,473,792
<p>You don't have to close <code>source</code> because <code>with</code> statement does it for you.</p> <p>Try this code:</p> <pre><code>with open("new_file.txt", "wb") as sink: for i in range(0,2): sink.write("%s %s\n" % (str(getUser()), str(getFriends()))) def getUser(): with open("abc.txt"...
0
2016-07-20T06:27:13Z
[ "python", "file-io" ]
Apache Spark- Error initializing SparkContext. java.io.FileNotFoundException
38,473,736
<p>I am able to run simple Hello World program through Spark on standalone machine. But when I run a word count program using Spark Context and run it using pyspark I get the following error. ERROR SparkContext: Error initializing SparkContext. java.io.FileNotFoundException: Added file file:/Users/tanyagupta/Docu...
0
2016-07-20T06:24:16Z
38,647,228
<p>Adding [underscore][underscore]init[underscore][underscore].py file in my folder worked for me!</p> <p>Thanks!</p>
1
2016-07-28T21:43:23Z
[ "python", "osx", "apache-spark", "pyspark" ]
How to save board game? Python
38,473,754
<p>I have programmed Connect 4 using python, and I wanted to make a Save option although I'm unsure how I would save all of the users inputs. Which would be mainly all the counters that have been placed on the board. The board is a multidimensional array:</p> <pre><code>board = [] for row in range(6): board.append...
1
2016-07-20T06:25:40Z
38,473,850
<p>If you only care about reading this file with Python, then <a href="https://docs.python.org/3/library/pickle.html" rel="nofollow">pickle</a> it!</p> <pre><code>import pickle fp = '/path/to/saved/file.pkl' with open(fp, 'wb') as f: pickle.dump(board, f) </code></pre>
4
2016-07-20T06:30:32Z
[ "python", "python-3.x", "save", "pygame" ]
How to save board game? Python
38,473,754
<p>I have programmed Connect 4 using python, and I wanted to make a Save option although I'm unsure how I would save all of the users inputs. Which would be mainly all the counters that have been placed on the board. The board is a multidimensional array:</p> <pre><code>board = [] for row in range(6): board.append...
1
2016-07-20T06:25:40Z
38,477,715
<p>If your game state gets saved in a simple object, like a list of list of integers, like this:</p> <pre><code>WIDTH = 7 HEIGHT = 6 board = [[0 for column in range(WIDTH)] for row in range(HEIGHT)] </code></pre> <p>then you can also use JSON instead of pickle to store this object in a file, like this:</p> <pre><cod...
1
2016-07-20T09:42:39Z
[ "python", "python-3.x", "save", "pygame" ]
Find location of image inside bigger image
38,473,952
<p>So i have an image lets say <code>small.png</code> and a bigger image <code>big.png</code> .The small image occurs 2 times in the bigger image and i wish to find its location.</p> <p>I tried using numpy and Image but got error </p> <p><code>'JpegImageFile' object has no attribute '__getitem__'</code>.I had <code>p...
5
2016-07-20T06:37:20Z
38,474,539
<p>The following code works for me:</p> <pre><code>import numpy from PIL import Image here = Image.open(r"eye.png") big = Image.open(r"lenna.png") herear = numpy.asarray(here) bigar = numpy.asarray(big) hereary, herearx = herear.shape[:2] bigary, bigarx = bigar.shape[:2] stopx = bigarx - herearx + 1 stopy = bi...
3
2016-07-20T07:08:06Z
[ "python", "numpy", "image-processing" ]
How to count numbers between l and r divisible by k
38,473,954
<pre><code># Taking inputs l=input() r=input() k=input() count = 0 # For loop for i in range(l,r): if(i%k)==0: count+=1 </code></pre>
-4
2016-07-20T06:37:23Z
38,474,090
<p>If you want to check if r is divisable by k you would need to use <code>range(l,r+1)</code>. See <a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow">https://docs.python.org/2/library/functions.html#range</a></p> <p>Otherwise your code is ok.</p>
0
2016-07-20T06:44:34Z
[ "python" ]
python object instance variable looks like a class variable?
38,474,138
<p>I'm using <code>SQLAlchemy</code> in Python 3 and am confused why the following code works - it looks to me like what should be an object level variable is acting as a class variable. I have seen <a href="http://stackoverflow.com/questions/13144433/why-is-instance-variable-behaving-like-a-class-variable-in-python">W...
1
2016-07-20T06:47:10Z
38,474,364
<p>You put the <code>query</code> property on the parent class earlier:</p> <pre><code>Base.query = session_factory.query_property() # make the query_property available in models for querying </code></pre> <p>So <code>query</code> is most definitely a member of <em>a</em> class (<code>Base</code>). And since <code>...
0
2016-07-20T06:59:32Z
[ "python", "sqlalchemy" ]
How to delete a file with invalid name using python?
38,474,210
<p>I've got a <code>file</code> named <code>umengchannel_316_豌豆荚</code> I want to delete this file.. I tried the following: <code>os.remove()</code>, <code>os.unlink()</code> , <code>shutil.move()</code> but nothing seems to work.. Are there any other approaches to this problem?</p>
0
2016-07-20T06:50:48Z
38,478,589
<p>I'm using Unix OS, have been able to create a blank file with the name you specified and delete it with <code>os.remove()</code> in python intepreter.</p> <pre><code>$ cd ~ $ touch "umengchannel_316_豌豆荚.txt" $ python &gt;&gt;&gt; import os &gt;&gt;&gt; os.remove("/home/neko/umengchannel_316_豌豆荚.txt") <...
0
2016-07-20T10:20:42Z
[ "python", "python-2.7", "python-3.x", "subprocess" ]
How to delete a file with invalid name using python?
38,474,210
<p>I've got a <code>file</code> named <code>umengchannel_316_豌豆荚</code> I want to delete this file.. I tried the following: <code>os.remove()</code>, <code>os.unlink()</code> , <code>shutil.move()</code> but nothing seems to work.. Are there any other approaches to this problem?</p>
0
2016-07-20T06:50:48Z
38,478,933
<p>This worked for me:</p> <p><code>os.system("rm umengchannel_316_豌豆荚")</code></p>
0
2016-07-20T10:36:26Z
[ "python", "python-2.7", "python-3.x", "subprocess" ]
Django: Inheriting from a class that has djangofsm field and not able to call the transition
38,474,219
<p>I have a abstract django model </p> <pre><code>from django_fsm import FSMField, transition from django.db.models import Model, NullBooleanField, TextField class ApprovalMixin(Model): status = FSMField(default='new') is_approved = NullBooleanField(blank=True, null=True) class Meta: """Meta Attributes""...
-1
2016-07-20T06:51:16Z
38,475,054
<p>From django-fsm docs:</p> <pre><code> The field parameter accepts both a string attribute name or an actual field instance. </code></pre>
1
2016-07-20T07:33:36Z
[ "python", "django", "django-models" ]
Value Error: Extra Data error when importing json file using python
38,474,277
<p>I'm trying to build a python script that imports json files into a MongoDB. This part of my script keeps jumping to the <code>except ValueError</code> for larger json files. I think it has something to do with parsing the json file line by line because very small json files seem to work.</p> <pre><code>def read(jso...
0
2016-07-20T06:54:57Z
38,475,616
<p>Look at this example:</p> <pre><code>s = """{ "data": { "one":1 } },{ "1": { "two":2 } }""" json.load( s ) </code></pre> <p>It will produce the "Extra data" error like in your json file:</p> <blockquote> <p>ValueError: Extra data: line 1 column 24 - line 1 column 45 (char 23 - 44)</p> </blockquote> <p>This is ...
0
2016-07-20T08:00:59Z
[ "python", "json", "mongodb", "pymongo" ]
Value Error: Extra Data error when importing json file using python
38,474,277
<p>I'm trying to build a python script that imports json files into a MongoDB. This part of my script keeps jumping to the <code>except ValueError</code> for larger json files. I think it has something to do with parsing the json file line by line because very small json files seem to work.</p> <pre><code>def read(jso...
0
2016-07-20T06:54:57Z
38,491,554
<p>Figured it out. Looks like breaking it up into lines was the mistake. Here's what the final code looks like.</p> <pre><code>counter = 0 for jsonFile in jsonFiles: with open(jsonFile) as f: data = f.read() jsondata = json.loads(data) try: db[args.collection].insert(jsondata) counter += 1 ...
0
2016-07-20T21:58:36Z
[ "python", "json", "mongodb", "pymongo" ]
How to use my own classifier in ensemble python
38,474,294
<p>The main aim is to add a deep learning classification method like <a href="https://github.com/Newmu/Theano-Tutorials/blob/master/5_convolutional_net.py" rel="nofollow">CNN</a> as an individual in ensemble in python.<br> The following code works fine:</p> <pre><code> clf1=CNN() eclf1=VotingClassifier(estimat...
0
2016-07-20T06:55:41Z
39,400,224
<p>Can you elaborate better what you did and which error you came across?</p> <p>By your question only I can assume you tried to call 'predic_proba' after the line <code>eclf1=eclf1.predict(XTest)</code>. And of course this will turn on an error because the <code>eclf1.predict(XTest)</code> returns an array, which doe...
0
2016-09-08T21:07:39Z
[ "python", "classification", "ensemble-learning", "sklearn-pandas" ]
Splitting a string using re module of python
38,474,353
<p>I have a string</p> <pre class="lang-py prettyprint-override"><code>s = 'count_EVENT_GENRE in [1,2,3,4,5]' #I have to capture only the field 'count_EVENT_GENRE' field = re.split(r'[(==)(&gt;=)(&lt;=)(in)(like)]', s)[0].strip() #o/p is 'cou' # for s = 'sum_EVENT_GENRE in [1,2,3,4,5]' o/p = 'sum_EVENT_GENRE' </cod...
1
2016-07-20T06:58:54Z
38,474,549
<p>Answering your question, the <code>[(==)(&gt;=)(&lt;=)(in)(like)]</code> is a character class matching single characters you defined inside the class. To match sequences of characters, you need to remove <code>[</code> and <code>]</code> and use alternation:</p> <pre><code>r'==?|&gt;=?|&lt;=?|\b(?:in|like)\b' </cod...
1
2016-07-20T07:08:42Z
[ "python", "regex", "string" ]
Splitting a string using re module of python
38,474,353
<p>I have a string</p> <pre class="lang-py prettyprint-override"><code>s = 'count_EVENT_GENRE in [1,2,3,4,5]' #I have to capture only the field 'count_EVENT_GENRE' field = re.split(r'[(==)(&gt;=)(&lt;=)(in)(like)]', s)[0].strip() #o/p is 'cou' # for s = 'sum_EVENT_GENRE in [1,2,3,4,5]' o/p = 'sum_EVENT_GENRE' </cod...
1
2016-07-20T06:58:54Z
38,474,551
<p>If you want only the first word of your string, then this should do the job:</p> <pre><code>import re s = 'count_EVENT_GENRE in [1,2,3,4,5]' field = re.split(r'\W', s)[0] # count_EVENT_GENRE </code></pre>
1
2016-07-20T07:08:47Z
[ "python", "regex", "string" ]
Splitting a string using re module of python
38,474,353
<p>I have a string</p> <pre class="lang-py prettyprint-override"><code>s = 'count_EVENT_GENRE in [1,2,3,4,5]' #I have to capture only the field 'count_EVENT_GENRE' field = re.split(r'[(==)(&gt;=)(&lt;=)(in)(like)]', s)[0].strip() #o/p is 'cou' # for s = 'sum_EVENT_GENRE in [1,2,3,4,5]' o/p = 'sum_EVENT_GENRE' </cod...
1
2016-07-20T06:58:54Z
38,474,941
<p>Is there anything wrong with using <code>split</code>? </p> <pre><code>&gt;&gt;&gt; s = 'count_EVENT_GENRE in [1,2,3,4,5]' &gt;&gt;&gt; s.split(' ')[0] 'count_EVENT_GENRE' &gt;&gt;&gt; s = 'coint_EVENT_GENRE = "ROMANCE"' &gt;&gt;&gt; s.split(' ')[0] 'coint_EVENT_GENRE' &gt;&gt;&gt; </code></pre>
1
2016-07-20T07:28:57Z
[ "python", "regex", "string" ]
MemoryError in Python 2.7 when iterating over a large file word by word
38,474,476
<p>I need to read a large file multiple times and need access to the total number of words in the file. I've implemented a wrapper class that contains an iterator, a copy of the iterator (to reset the iterator) and its length:</p> <pre><code>Class DataWrapper(object): def __init__(self, data): self.data, self.co...
0
2016-07-20T07:05:28Z
38,475,097
<p>The problem here is that if the data is only read once, and must be iterated multiple times, it has to been kept in memory. If the file is large enough to exhaust the memory you will end with a MemoryError. Here the <code>itertool.tee</code> is indeed the culprit, even if IMHO it is not to blame for it because it ha...
2
2016-07-20T07:36:01Z
[ "python", "iterator", "out-of-memory" ]
How to pass argument to subprocess using gksudo?
38,474,496
<p><strong>Data of FirstFile.py<br></strong></p> <pre><code>a=raw_input("Anything") p=subprocess.Popen(['gksudo','python','file1.py'],stdin=subprocess.PIPE).communicate(a)&lt;br&gt; #some related codes </code></pre> <p><strong>Data of file1.py<br></strong></p> <pre><code>pro=sys.stdin.read()&lt;br&gt; sys.stdout.wri...
0
2016-07-20T07:06:09Z
38,474,641
<p>Because,</p> <p><code>gksudo</code> is used to run graphical (GUI) applications as root and <code>sudo</code> is used to run command line applications as root. Here you using command line application. So you have to use <code>sudo</code>. </p>
0
2016-07-20T07:13:09Z
[ "python", "subprocess" ]
Elementtree and xsd sequences
38,474,565
<p>I'm currently writing a code generator that produces <a href="http://www.plcopen.org/pages/tc6_xml/" rel="nofollow">PLCOpen XML files</a>. The Schema uses sequences in some places. The code generator uses <code>ElementTree</code> because of its simple interface. However, I can't find a way to make <code>ElementTree<...
0
2016-07-20T07:09:21Z
38,474,917
<p>The method <code>ElementTree.append</code> that I used does not seem to keep the elements ordered. Using <code>ElementTree.insert</code>, however, solved the issue.</p>
0
2016-07-20T07:28:05Z
[ "python", "xml", "xsd", "elementtree" ]
Error:not all arguments converted during string formatting
38,474,576
<p>I have this signup page and when i am submitting the form i am getting this error:not all arguments converted during string formatting</p> <pre><code>class RegistrationForm(Form): email = StringField('Email address') password = PasswordField('password') name = StringField('Name') @app.route('/register/', methods=[...
1
2016-07-20T07:09:59Z
38,474,692
<p><code>x = cur.execute("SELECT * FROM user WHERE username = (%s)",(thwart(email)))</code> </p> <p>The second argument of <code>execute</code> should be a tuple, you are missing a <code>,</code>: </p> <p><code>cur.execute("SELECT * FROM user WHERE username = (%s)",(thwart(email),))</code></p> <p>I guess that you al...
1
2016-07-20T07:16:18Z
[ "python", "mysql", "mysql-python" ]
How to replace letters with numbers and re-convert at anytime
38,474,628
<p>I've been coding this for almost 2 days now but cant get it. I've coded two different bits trying to find it.</p> <p>Code #1 So this one will list the letters but wont change it to the numbers (a->1, b->2, ect)</p> <pre><code>import re text = input('Write Something- ') word = '{}'.format(text) for letter in word: ...
-1
2016-07-20T07:12:26Z
38,474,895
<p>Just use <code>dictionary</code>:</p> <pre><code> letters = {'a': 1, 'b': 2, ... } </code></pre> <p>And in the loop:</p> <pre><code>for letter in word: print(letters[letter]) </code></pre>
0
2016-07-20T07:26:38Z
[ "python", "python-3.x" ]
How to replace letters with numbers and re-convert at anytime
38,474,628
<p>I've been coding this for almost 2 days now but cant get it. I've coded two different bits trying to find it.</p> <p>Code #1 So this one will list the letters but wont change it to the numbers (a->1, b->2, ect)</p> <pre><code>import re text = input('Write Something- ') word = '{}'.format(text) for letter in word: ...
-1
2016-07-20T07:12:26Z
38,474,943
<p>What youre trying to achieve here is called "caesar encryption".</p> <p>You for example say normally you would have: A=1, a=2, B=3, B=4, etc...</p> <p>then you would have a "key" which "shifts" the letters. Lets say the key is "3", so you would shift all letters 3 numbers up and you would end up with: A=4, a=5, B=...
0
2016-07-20T07:29:01Z
[ "python", "python-3.x" ]
How to replace letters with numbers and re-convert at anytime
38,474,628
<p>I've been coding this for almost 2 days now but cant get it. I've coded two different bits trying to find it.</p> <p>Code #1 So this one will list the letters but wont change it to the numbers (a->1, b->2, ect)</p> <pre><code>import re text = input('Write Something- ') word = '{}'.format(text) for letter in word: ...
-1
2016-07-20T07:12:26Z
38,474,998
<p>To convert to symbol codes and back to characters:</p> <pre><code>text = input('Write Something') for t in text: d = ord(t) n = chr(d) print(t,d,n) </code></pre> <p>To write into file:</p> <pre><code>f = open("a.txt", "w") f.write("someline\n") f.close() </code></pre> <p>To read lines from file:</p>...
0
2016-07-20T07:31:28Z
[ "python", "python-3.x" ]
How to replace letters with numbers and re-convert at anytime
38,474,628
<p>I've been coding this for almost 2 days now but cant get it. I've coded two different bits trying to find it.</p> <p>Code #1 So this one will list the letters but wont change it to the numbers (a->1, b->2, ect)</p> <pre><code>import re text = input('Write Something- ') word = '{}'.format(text) for letter in word: ...
-1
2016-07-20T07:12:26Z
38,476,458
<p>Here are a couple of examples. My method involves mapping the character to the string representation of an integer padded with zeros so it's 3 characters long using <code>str.zfill</code>.</p> <p>Eg <code>0 -&gt; '000', 42 -&gt; '042', 125 -&gt; '125'</code></p> <p>This makes it much easier to convert a string of ...
0
2016-07-20T08:44:55Z
[ "python", "python-3.x" ]
Sqlalchemy - how to fix '_sa_instance_state'
38,474,742
<p>I have a folder containing over 200 000 json files. Each json object is a Tweet (twitter). I'm getting an error while saving a tweet into the db</p> <pre><code>#sqlalchemy_insert.py def create_new_tweet(data, new_user): """ insert new tweet into db """ #tweet tweet_id = data.get('id') langua...
0
2016-07-20T07:18:20Z
38,475,220
<p><code>create_new_user</code> returns <code>Query</code> object if user exists</p> <pre><code>new_user = session.query(User).filter(User.id == user_id) # it's a query </code></pre> <p>but you need to pass <code>User</code> object to <code>create_new_tweet</code>.</p> <p>You can do something like this</p> <pre><co...
1
2016-07-20T07:41:27Z
[ "python", "twitter", "sqlalchemy" ]
Pandas dataframe pivoting
38,474,807
<p>I have the following <code>pandas DataFrame</code>:</p> <pre><code> id quantity cost type 2016-06-18 1700057817 2 2383 A 2016-06-18 1700057817 1 744 B 2016-06-19 1700057817 5 934 A </code></pre> <p>Here, the dates are the <code>index</cod...
3
2016-07-20T07:22:22Z
38,475,903
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> to preserve dates.</p> <pre><code>df.index.name = 'date' df = df.reset_index().pivot_table(index=['date', 'id'], columns=['type']) df = df.sort_index(axis=1, leve...
1
2016-07-20T08:16:10Z
[ "python", "pandas", "dataframe" ]
Pandas dataframe pivoting
38,474,807
<p>I have the following <code>pandas DataFrame</code>:</p> <pre><code> id quantity cost type 2016-06-18 1700057817 2 2383 A 2016-06-18 1700057817 1 744 B 2016-06-19 1700057817 5 934 A </code></pre> <p>Here, the dates are the <code>index</cod...
3
2016-07-20T07:22:22Z
38,476,062
<p>You could <code>set_index</code> with <code>append=True</code> followed by <code>unstack</code> and keep the <code>MultiIndex</code>:</p> <pre><code>df.set_index(['id', 'type'], append=True).unstack() </code></pre> <p><a href="http://i.stack.imgur.com/0uM8c.png" rel="nofollow"><img src="http://i.stack.imgur.com/0u...
3
2016-07-20T08:24:55Z
[ "python", "pandas", "dataframe" ]
Making Matplotlib and GTK3 work on python3 windows
38,475,134
<p>I'm trying to make GTK3 and Python3 work under windows to my project.</p> <p>I have an continuum anaconda setup with a 32-bit python 3.4 and Matplotib via conda install matplotlib.</p> <p>I've installed PyGobject(<a href="https://sourceforge.net/projects/pygobjectwin32/" rel="nofollow">https://sourceforge.net/proj...
0
2016-07-20T07:37:32Z
38,484,297
<p>I've had my share of problems using <code>matplotlib</code> in <code>Python3 + Gtk3</code>. I found <a href="http://gtk3-matplotlib-cookbook.readthedocs.io/en/latest/hello-plot.html#embedding-matplotlib" rel="nofollow">this cookbook page</a> with working examples. Try to run the examples in the cookbook - particular...
0
2016-07-20T14:38:21Z
[ "python", "matplotlib", "networkx", "gtk3", "cairo" ]
creating a string character as a default parameter for function
38,475,158
<p>Good morning,</p> <p>At the moment I am trying to create a histogram for class. I am now developing my skill as I have only been doing this for 2 months, and as I do know this is a website for professionals, and please you to excuse my lack of understanding.</p> <pre><code>def histo_print(times, dicerand, symbol='...
0
2016-07-20T07:38:46Z
38,475,490
<p>To answer your first question, yes. Yes, you can absolutely use a string value to pass off as a "default" in your function. For starters, take a quick read here to avoid common gotchas ==> <a href="http://docs.python-guide.org/en/latest/writing/gotchas/" rel="nofollow">http://docs.python-guide.org/en/latest/writin...
1
2016-07-20T07:55:09Z
[ "python", "python-3.x" ]
Cannot pip install the python module tables
38,475,159
<p>I am trying to install tables so an existing python script does not complain when it tries to 'import tables'</p> <pre><code>pip install tables </code></pre> <p>Here is the output:</p> <pre><code>Collecting tables Using cached tables-3.2.3.1.tar.gz Requirement already satisfied (use --upgrade to upgrade): numpy...
0
2016-07-20T07:38:46Z
38,475,337
<p>Your log explicitly tell what's wrong:</p> <blockquote> <p>WARNING:: Could not find the HDF5 runtime.</p> </blockquote> <p>Try this:</p> <pre><code>sudo python setup.py build_ext --inplace --hdf5=/opt/local --lzo=/opt/local --bzip2==opt/local sudo python setup.py install --hdf5=/opt/local --lzo=/opt/local --bz...
0
2016-07-20T07:47:23Z
[ "python", "pytables" ]
Cannot pip install the python module tables
38,475,159
<p>I am trying to install tables so an existing python script does not complain when it tries to 'import tables'</p> <pre><code>pip install tables </code></pre> <p>Here is the output:</p> <pre><code>Collecting tables Using cached tables-3.2.3.1.tar.gz Requirement already satisfied (use --upgrade to upgrade): numpy...
0
2016-07-20T07:38:46Z
38,475,382
<p><a href="http://www.pytables.org/usersguide/installation.html" rel="nofollow">Take a look at the project site page</a>. You can download manually the dependeces (<a href="http://blosc.org/" rel="nofollow">blosc</a>), maybe the issue is given by a network problem, or can not be satisfy automatically.If you already ha...
0
2016-07-20T07:49:55Z
[ "python", "pytables" ]
give a root privilege to a python GUI application to run a command in ubuntu
38,475,185
<p>Now, i have a python GUI app which need to run a command with sudo privilege like this below:</p> <pre><code>import commands iStat, askpassPath = commands.getstatusoutput("which ssh-askpass") cmd = "export SUDO_ASKPASS=%s;sudo -A mkdir -p /usr/lib/test"%(askpassPath) commands.getstatusoutput(cmd) </code></pre> <p>...
2
2016-07-20T07:39:42Z
38,476,502
<p>Since you're for "another way for me to get a sudo privilege". You can, and probably should, not run the application with elevated privileges.</p> <p>An option I see is to install a helper binary and store it with a <a href="https://en.wikipedia.org/wiki/Setuid" rel="nofollow">SUID-bit</a>. You can then call this b...
0
2016-07-20T08:46:56Z
[ "python", "linux", "user-interface", "ubuntu", "pyqt" ]
Configuring Python project in eclipse
38,475,209
<p>Actually I'm trying to use a python framework in Eclipse (with PyDev plugin) - the framework was designed in PyCharm IDE where we do some configuration as in the screenshot below:</p> <p><a href="http://i.stack.imgur.com/Nz536.png" rel="nofollow"><img src="http://i.stack.imgur.com/Nz536.png" alt="enter image descri...
0
2016-07-20T07:40:50Z
38,619,861
<p>Humm, can you update your pytest version and retry that? Which pytest version are you using?</p> <p>I.e. it seems PyDev is now requiring pytest 2.7 onwards (hookwrapper: executing around other hooks is New in version 2.7 from: <a href="http://docs.pytest.org/en/latest/writing_plugins.html" rel="nofollow">http://doc...
1
2016-07-27T17:44:24Z
[ "python", "eclipse", "pycharm", "pydev" ]
Heatmap from List
38,475,268
<p>I have a list <code>x</code> which contains intensities in the range 0 to 1. I want to create a heatmap with a squared grid.</p> <p>For example:</p> <pre><code>x = [0, 0.1, 0, 0.5, ..., 0.5] n = len(x) dim = math.sqrt(n) + 1 </code></pre> <p>But how can I create an array with <code>dim × dim</code> (the not ...
0
2016-07-20T07:43:39Z
38,475,969
<p>As mentioned in the comment, you could use numpy, and plot with the help of seaborn:</p> <pre><code>import numpy as np import math import matplotlib.pyplot as plt import seaborn as sns x_list = np.random.rand(100).tolist() x = np.array((x_list)) x_res=x.reshape(math.sqrt(len(x)),math.sqrt(len(x))) fig, ax = plt.s...
1
2016-07-20T08:19:28Z
[ "python", "matplotlib" ]
How can I sort my list by name/age separately?
38,475,389
<p>Additionally, if I wanted to sort them by their age, how could I do so? I tried myFile.sort(), but it crashes the code saying "Object has no attribute 'sort' "</p> <pre><code>fileName = "GuestList.csv" ACCESSMODE = "w" name = " " nbrGuest = " " myFile = open(fileName, ACCESSMODE) nbrGuest = input("How many guests ...
-3
2016-07-20T07:50:23Z
38,475,480
<p>Duplicate question : <a href="http://stackoverflow.com/questions/2100353/sort-csv-by-column">sort-csv-by-column</a></p> <pre><code>import operator sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True) or use lambda sortedlist = sorted(reader, key=lambda row: row[3], reverse=True) </code></pre> <p>...
-1
2016-07-20T07:54:48Z
[ "python", "sorting" ]
How can I sort my list by name/age separately?
38,475,389
<p>Additionally, if I wanted to sort them by their age, how could I do so? I tried myFile.sort(), but it crashes the code saying "Object has no attribute 'sort' "</p> <pre><code>fileName = "GuestList.csv" ACCESSMODE = "w" name = " " nbrGuest = " " myFile = open(fileName, ACCESSMODE) nbrGuest = input("How many guests ...
-3
2016-07-20T07:50:23Z
38,475,534
<p>So the code is now split into two parts.</p> <pre><code>fileName = "GuestList.csv" ACCESSMODE = "w" name = " " nbrGuest = " " nbrGuest = input("How many guests do you have? ") guest_list = [] for index in range(int(nbrGuest)): name = input("Enter guest name:\t").capitalize() age = input("Enter guest age:\...
1
2016-07-20T07:57:18Z
[ "python", "sorting" ]
reading compressed data gives different results
38,475,464
<p>I am using genfromtxt in order to read data.</p> <p>genfromtxt must work also for .gz files but it seems it doesn't.</p> <p>Using simple data ( not .gz files )</p> <pre><code>f = open('file', 'r') con = np.genfromtxt(f,dtype=str) print con print type(con) </code></pre> <p>file contents is:</p> <pre><code> @HWI...
0
2016-07-20T07:54:00Z
38,475,710
<p>From the documentation:</p> <pre><code>genfromtxt(fname, dtype=&lt;class 'float'&gt;, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=None, replace_space='_', autostrip=False, case_sensitiv...
2
2016-07-20T08:05:55Z
[ "python", "numpy" ]
reading compressed data gives different results
38,475,464
<p>I am using genfromtxt in order to read data.</p> <p>genfromtxt must work also for .gz files but it seems it doesn't.</p> <p>Using simple data ( not .gz files )</p> <pre><code>f = open('file', 'r') con = np.genfromtxt(f,dtype=str) print con print type(con) </code></pre> <p>file contents is:</p> <pre><code> @HWI...
0
2016-07-20T07:54:00Z
38,476,165
<p>Why don't you use <code>genfromtxt</code> with the file object from <code>gzip.open()</code>?</p> <pre><code>with gzip.open('file.gz') as f: print(numpy.genfromtxt(f, dtype=str)) </code></pre> <p><strong>EDIT</strong></p> <p><code>numpy</code> uses predefined file openers for <code>.gz</code> and <code>.bz2</...
1
2016-07-20T08:29:43Z
[ "python", "numpy" ]
How to format output to create space between two variables in python when printing?
38,475,578
<p>I'm trying to create an output that would look something like this:</p> <p><a href="http://i.stack.imgur.com/Ndu4b.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ndu4b.png" alt="enter image description here"></a> </p> <p>As can be seeing in here, the left column spaces are lined up to the left and the righ...
0
2016-07-20T07:59:20Z
38,475,721
<p>You can use this one.</p> <pre><code>print("Kilograms Pounds") for kg in range(0, 100): kg += 1 lb = 2.2 lb = kg * lb space_filler = " " * 10 print("%3d %s %.2f" % (kg, space_filler, lb)) </code></pre> <p>The value 3 can also be made dynamic by use <code>format</code> which is more fl...
1
2016-07-20T08:06:21Z
[ "python", "python-3.x", "spacing" ]
How to format output to create space between two variables in python when printing?
38,475,578
<p>I'm trying to create an output that would look something like this:</p> <p><a href="http://i.stack.imgur.com/Ndu4b.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ndu4b.png" alt="enter image description here"></a> </p> <p>As can be seeing in here, the left column spaces are lined up to the left and the righ...
0
2016-07-20T07:59:20Z
38,475,761
<p>Give this a try:</p> <pre><code>between = ' '*4 print('Kilograms{between}Pounds'.format(between=between)) for kg in range(199): kg += 1 lb = 2.2 lb = kg * lb lb = round(lb, 2) print('{kg:&lt;{kg_width}}{between}{lb:&gt;{lb_width}}'.format( kg=kg, kg_width=len('Kilograms'), ...
2
2016-07-20T08:08:12Z
[ "python", "python-3.x", "spacing" ]
How to format output to create space between two variables in python when printing?
38,475,578
<p>I'm trying to create an output that would look something like this:</p> <p><a href="http://i.stack.imgur.com/Ndu4b.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ndu4b.png" alt="enter image description here"></a> </p> <p>As can be seeing in here, the left column spaces are lined up to the left and the righ...
0
2016-07-20T07:59:20Z
38,475,765
<p>Check out <a href="https://docs.python.org/3.1/library/string.html#string.Formatter.vformat" rel="nofollow">The Docs</a> Section 7.1.3.1</p> <p>You can pass <code>format()</code> a <code>width</code> as int, which should take care of your whitespace problem.</p> <p>From the Documentation Example:</p> <pre><code>&...
1
2016-07-20T08:08:35Z
[ "python", "python-3.x", "spacing" ]
How to convert a list into a 1 item dictionary list
38,475,614
<p>I have a list like</p> <pre><code>a=[('policy', 871), ('insurance', 382), ('life', 357), ('request', 270), ('call', 260)] </code></pre> <p>Now, I want to convert it to a list of one item <code>dict</code>:</p> <pre><code>[{'call': 260},{'insurance': 382},{'life': 357}, {'policy': 871}, {'request': 270}] </cod...
-3
2016-07-20T08:00:58Z
38,475,641
<p>You can convert a list of tuples to a dict simply by converting it to a dict:</p> <pre><code>&gt;&gt;&gt; a = [('policy', 871), ('insurance', 382), ('life', 357), ('request', 270), ('call', 260)] &gt;&gt;&gt; dict(a) </code></pre> <p>will result in</p> <pre><code>{'policy': 871, 'call': 260, 'life': 357, 'request...
6
2016-07-20T08:02:14Z
[ "python", "list" ]
How to convert a list into a 1 item dictionary list
38,475,614
<p>I have a list like</p> <pre><code>a=[('policy', 871), ('insurance', 382), ('life', 357), ('request', 270), ('call', 260)] </code></pre> <p>Now, I want to convert it to a list of one item <code>dict</code>:</p> <pre><code>[{'call': 260},{'insurance': 382},{'life': 357}, {'policy': 871}, {'request': 270}] </cod...
-3
2016-07-20T08:00:58Z
38,475,808
<p>I think you wanted a list of dictionaries, so here is one way:</p> <pre><code>&gt;&gt;&gt; [{k:v} for (k,v) in a] [{'policy': 871}, {'insurance': 382}, {'life': 357}, {'request': 270}, {'call': 260}] </code></pre>
4
2016-07-20T08:11:23Z
[ "python", "list" ]
How to convert a list into a 1 item dictionary list
38,475,614
<p>I have a list like</p> <pre><code>a=[('policy', 871), ('insurance', 382), ('life', 357), ('request', 270), ('call', 260)] </code></pre> <p>Now, I want to convert it to a list of one item <code>dict</code>:</p> <pre><code>[{'call': 260},{'insurance': 382},{'life': 357}, {'policy': 871}, {'request': 270}] </cod...
-3
2016-07-20T08:00:58Z
38,477,774
<p>My version</p> <pre><code>def convert_to_dict(a): return [{i[0]: i[1]} for i in a] </code></pre> <p>Hope this helps :)</p>
0
2016-07-20T09:45:37Z
[ "python", "list" ]
not printing inside celery task
38,475,717
<p>In my celery I tried printing inside a task, but I cant seem to output the data even in console.</p> <p>Here is my structure:</p> <pre><code>/app.py @app.route('//create', methods = ['POST']) def create_file(): request.form ....... callback = build_file.s(name, address) header = [ send_param.s( id, key ) for key i...
-1
2016-07-20T08:06:07Z
38,482,557
<p>The most straightforward solution will be to:</p> <p>1) Configure a Logger instance which will capture all output from <code>logger.info()</code> (and other log levels) and put it into a local file or just <code>stdout</code></p> <p>2) While configuring, set </p> <pre><code>app.conf.update(CELERYD_HIJACK_ROOT_LOG...
0
2016-07-20T13:23:05Z
[ "python", "flask", "celery" ]
'pip install -r requirements.txt' fails when using Chef
38,475,795
<p>I have a script which is copied to a Chef node; it activates a python virtual environment and then installs requirements from a requirements file:</p> <pre><code>#!/bin/bash source venv/bin/activate pip install -v -r requirements.txt &gt;&gt; scripts/scripts.out </code></pre> <p>When I run it locally, all is well....
0
2016-07-20T08:10:24Z
38,476,019
<p>Looks like Chef's bash block doesn't set the home directory for the user it is representing. As a result pip couldn't find/use the cache directory. Explicitly stating it in the script fixed the problem:</p> <pre><code>#!/bin/bash source venv/bin/activate pip install -v -r requirements.txt --cache-dir /home/app-us...
0
2016-07-20T08:22:12Z
[ "python", "pip", "chef" ]
'pip install -r requirements.txt' fails when using Chef
38,475,795
<p>I have a script which is copied to a Chef node; it activates a python virtual environment and then installs requirements from a requirements file:</p> <pre><code>#!/bin/bash source venv/bin/activate pip install -v -r requirements.txt &gt;&gt; scripts/scripts.out </code></pre> <p>When I run it locally, all is well....
0
2016-07-20T08:10:24Z
38,483,393
<p>You could also use the <code>pip_requirements</code> resource from the <code>poise-python</code> cookbook, which does all this for you.</p>
1
2016-07-20T13:59:23Z
[ "python", "pip", "chef" ]
Save NumPy array / vector to CSV
38,475,824
<p>I have some numeric numbers ( about 550,000) and I tried to save them in a CSV file. My values can only be 1 or 2. But it is saved as:</p> <pre><code>['2.000000000000000000e+00'] ['1.000000000000000000e+00'] ['2.000000000000000000e+00'] ['2.000000000000000000e+00'] ... </code></pre> <p>My code is:</p> <pre><code>...
0
2016-07-20T08:12:16Z
38,475,978
<p>First thing to point out, assuming <code>My_Labels</code> is a list as you suggest, the indicated section of your code is superfluous:</p> <pre><code>def save_in_scv_format(My_Labels): import numpy as np K = [] # &lt;-- for i in range(len(My_Labels)): # &lt;-- ...
0
2016-07-20T08:19:54Z
[ "python", "csv" ]
Save NumPy array / vector to CSV
38,475,824
<p>I have some numeric numbers ( about 550,000) and I tried to save them in a CSV file. My values can only be 1 or 2. But it is saved as:</p> <pre><code>['2.000000000000000000e+00'] ['1.000000000000000000e+00'] ['2.000000000000000000e+00'] ['2.000000000000000000e+00'] ... </code></pre> <p>My code is:</p> <pre><code>...
0
2016-07-20T08:12:16Z
38,476,566
<p>You can change the formatting of numeric values in the output. From the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" rel="nofollow">manual</a>:</p> <blockquote> <p><strong>fmt</strong> : <code>str or sequence of strs, optional</code></p> <pre><code> A single format (%10.5f)...
0
2016-07-20T08:50:03Z
[ "python", "csv" ]
What is the $project (aggregation) API for Pymongo?
38,475,908
<p>I'm rather new to MongoDB, I can find some commands in shell to execute my query, however, I can not find a proper function in PyMongo API manual. </p> <p>For example, I would like to project some of the fields of the document to a new document. I suppose the $project could do it, but there is no such support in Py...
-1
2016-07-20T08:16:22Z
38,476,605
<p>For projecting you may use the query as</p> <pre><code>db.books.aggregate([{'$project':{ 'title':'$title', 'author':'$author'}}]) </code></pre>
0
2016-07-20T08:51:53Z
[ "python", "mongodb" ]
Referencing a variable from a different thread/class in python?
38,475,987
<p>What I'm trying to achieve is quite simple.</p> <p>So basically, I have a thread that loops continuously, grabbing data from the same url and updating a variable called "data", with text each time. The variable is stored locally within the class.</p> <p>Then I have a second class which is the mainframe. It should ...
0
2016-07-20T08:20:32Z
38,476,128
<p>Try to declare the data variable outside of the while loop and the run method. Then you can call that static variable using <strong>httpReq.data</strong> </p> <p>For reference : <a href="https://stackoverflow.com/questions/68645/static-class-variables-in-python?rq=1">Static class variables in Python</a></p>
0
2016-07-20T08:27:54Z
[ "python", "multithreading" ]
Referencing a variable from a different thread/class in python?
38,475,987
<p>What I'm trying to achieve is quite simple.</p> <p>So basically, I have a thread that loops continuously, grabbing data from the same url and updating a variable called "data", with text each time. The variable is stored locally within the class.</p> <p>Then I have a second class which is the mainframe. It should ...
0
2016-07-20T08:20:32Z
38,631,873
<p>It turns out that there are various ways of doing this. For my purposes however, (since only one thread writes to the variable, and the others read-only) I have found that using a global variable does the job.</p> <p>First declare and set the variable to none, outside the thread. Then within each thread, declare th...
0
2016-07-28T09:09:48Z
[ "python", "multithreading" ]
Concatenating all Possible Column Values of Other Unique Column
38,476,096
<p><strong>Problem Setting</strong></p> <p>Suppose I am given the following data frame.</p> <pre><code>ID category 223 MMO 223 Game 444 Finance 360 Reading 360 Book </code></pre> <p>This data frame has an <code>ID</code> column and it's associated <code>category</code>. Notice that the same <code>I...
2
2016-07-20T08:26:24Z
38,476,116
<p>You can <code>groupby</code> on ID and then apply a <code>join</code> with your desired separator:</p> <pre><code>In [142]: df.groupby('ID')['category'].apply('_'.join) Out[142]: ID 223 MMO_Game 360 Reading_Book 444 Finance Name: category, dtype: object </code></pre> <p>To get the exact desired ...
4
2016-07-20T08:27:28Z
[ "python", "pandas" ]
JSON and MySQL UPDATE query
38,476,206
<p>I'm trying to get info from a JSON msg out of ZeroMQ into MySQL by Python. This is the piece of code I'm attempting to run:</p> <pre><code>for i in json_msg["PropertyInfoMsg"]: db2 = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="db") cursor2 = db2.cursor() sql = """UPDATE settings SE...
1
2016-07-20T08:32:13Z
38,476,346
<p>I would do the query this way :</p> <pre><code>cursor2.execute("UPDATE settings SET value = %s WHERE name = %s",(i["PropertyType"].lower(), i["PropertyValue"].lower())) </code></pre>
2
2016-07-20T08:40:31Z
[ "python", "mysql", "json" ]
JSON and MySQL UPDATE query
38,476,206
<p>I'm trying to get info from a JSON msg out of ZeroMQ into MySQL by Python. This is the piece of code I'm attempting to run:</p> <pre><code>for i in json_msg["PropertyInfoMsg"]: db2 = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="db") cursor2 = db2.cursor() sql = """UPDATE settings SE...
1
2016-07-20T08:32:13Z
38,476,364
<p>You should wrap your parameters with single quote:</p> <pre><code>sql = """UPDATE settings SET value='%s' WHERE name='%s'""" % (i["PropertyType"].lower(), i["PropertyValue"].lower()) </code></pre> <p>Also you must confirm your json data is correct.</p>
2
2016-07-20T08:41:02Z
[ "python", "mysql", "json" ]
sort dataframe by a subset of levels in a multiindex
38,476,260
<p>I have following dataframe:</p> <pre><code>data = {'year': [2010, 2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012, 2013], 'store_number': ['1944', '1945', '1946', '1947', '1948', '1949', '1947', '1948', '1949', '1947'], 'retailer_name': ['Walmart', 'Walmart', 'CRV', 'CRV', 'CRV', 'Wal...
2
2016-07-20T08:35:54Z
38,476,312
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a> by specific index levels and specify whether the ordering should be ascending or not:</p> <pre><code>In [148]: stores.sort_index(level=['year','month'], ascending=F...
3
2016-07-20T08:38:36Z
[ "python", "pandas", "dataframe" ]
How to write csv file into sql database with python
38,476,268
<p>I have csv file that include some information about computer as like ostype, ram, cpu value and ı have sql database that already has same information and ı want to updated that database table with by python script. database table and csv file has uniqe "id" parameters. </p> <pre><code>import csv with open("Hyper...
0
2016-07-20T08:36:09Z
38,477,003
<p>Depending on what type of database, there will be some slight adjustments to make to the code.<br> For this example, I'll use <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> with the <a href="https://github.com/PyMySQL/PyMySQL" rel="nofollow">pymysql</a> driver. To find out what the first part of ...
0
2016-07-20T09:10:17Z
[ "python", "sql" ]
How to distribute values within a certain range (0 - 1.0)
38,476,292
<p>In Python I have a dictionary of values with a sum of 1.0.</p> <pre><code>weights = {u'obj_1': 0.018564743024138134, u'obj_2': 0.012814665648003992, u'obj_3': 0.38978992409415425, u'obj_4': 0.0594938403597285, u'obj_5': 0.41613932145700294, u'obj_6': 0.10319750541697208} </code></pre> <p>I ...
0
2016-07-20T08:37:32Z
38,476,928
<p>It depends a lot on the kind of algorithm you want to implement. If setting the values that become negative in your implementation to zero and distribute the rest of over the remaining ones would work for you, try something like this</p> <pre><code>def updateDict(oldDict, key, val): assert(val &lt;= 1.0) as...
3
2016-07-20T09:07:27Z
[ "python", "sum", "distribution" ]
How to distribute values within a certain range (0 - 1.0)
38,476,292
<p>In Python I have a dictionary of values with a sum of 1.0.</p> <pre><code>weights = {u'obj_1': 0.018564743024138134, u'obj_2': 0.012814665648003992, u'obj_3': 0.38978992409415425, u'obj_4': 0.0594938403597285, u'obj_5': 0.41613932145700294, u'obj_6': 0.10319750541697208} </code></pre> <p>I ...
0
2016-07-20T08:37:32Z
38,477,286
<p>It does not quite sum up to 1 (I blame float accuracy), but I think you want to do it like this?</p> <pre><code>weights = {u'obj_1': 0.018564743024138134, u'obj_2': 0.012814665648003992, u'obj_3': 0.38978992409415425, u'obj_4': 0.0594938403597285, u'obj_5': 0.41613932145700294, u'obj_6': 0.103...
0
2016-07-20T09:22:03Z
[ "python", "sum", "distribution" ]
How to distribute values within a certain range (0 - 1.0)
38,476,292
<p>In Python I have a dictionary of values with a sum of 1.0.</p> <pre><code>weights = {u'obj_1': 0.018564743024138134, u'obj_2': 0.012814665648003992, u'obj_3': 0.38978992409415425, u'obj_4': 0.0594938403597285, u'obj_5': 0.41613932145700294, u'obj_6': 0.10319750541697208} </code></pre> <p>I ...
0
2016-07-20T08:37:32Z
38,501,616
<p>This seems to work the way I was expecting.</p> <pre><code>weights = [0.2, 0.4, 0.3, 0.1] def update_value(index, new_value): dif = (1.0-new_value) / (1.0-weights[index]) for i in range(len(weights)): if i == index: weights[i] = new_value else: weights[i] *= dif </c...
0
2016-07-21T10:23:04Z
[ "python", "sum", "distribution" ]
FFT on image with Python
38,476,359
<p>I have a problem with FFT implementation in Python. I have completely strange results. Ok so, I want to open image, get value of every pixel in RGB, then I need to use fft on it, and convert to image again.</p> <p>My steps:</p> <p>1) I'm opening image with PIL library in Python like this</p> <pre><code>from PIL ...
2
2016-07-20T08:40:54Z
38,483,382
<p>There are several issues here.</p> <p><strong>1)</strong> Manual conversion to grayscale isn't good. Use <code>Image.open("test.png").convert('L')</code></p> <p><strong>2)</strong> Most likely there is an issue with types. You shouldn't pass <code>np.ndarray</code> from <code>fft2</code> to a PIL image without bei...
0
2016-07-20T13:58:29Z
[ "python", "image", "fft", "dft" ]
FFT on image with Python
38,476,359
<p>I have a problem with FFT implementation in Python. I have completely strange results. Ok so, I want to open image, get value of every pixel in RGB, then I need to use fft on it, and convert to image again.</p> <p>My steps:</p> <p>1) I'm opening image with PIL library in Python like this</p> <pre><code>from PIL ...
2
2016-07-20T08:40:54Z
38,507,628
<p>Great question. I’ve never heard of it but the <a href="http://registry.gimp.org/node/19596" rel="nofollow">Gimp Fourier</a> plugin seems really neat: </p> <blockquote> <p>A simple plug-in to do fourier transform on you image. The major advantage of this plugin is to be able to work with the transformed image i...
1
2016-07-21T14:55:46Z
[ "python", "image", "fft", "dft" ]
Python Matplotlib - imshow but with hexagons
38,476,373
<p>Code is:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import colors example_data = np.random.randint(4, size=(40,44)) cmap = colors.ListedColormap(['black', 'green', 'red', 'blue']) bounds = [0,1,2,3,4] norm = colors.BoundaryNorm(bounds, cmap.N) img = plt.imshow(example_data, ...
0
2016-07-20T08:41:33Z
38,477,407
<p>You could use a scatter plot with coloured hexagons,</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import colors nx = 40 ny = 44 example_data = np.random.randint(4, size=(nx,ny)) cmap = colors.ListedColormap(['black', 'green', 'red', 'blue']) bounds = [0,1,2,3,4] norm = colors.B...
0
2016-07-20T09:26:32Z
[ "python", "matplotlib", "imshow" ]
BSON object size of document retrieved from DB
38,476,377
<p>Mongo shell have <a href="https://docs.mongodb.com/v3.2/reference/mongo-shell/#miscellaneous" rel="nofollow">the bsonsize() method</a> to get BSON size of a given document retrieved from DB.</p> <p>Is there any way of getting the same using PyMongo driver? I have found the <a href="http://api.mongodb.com/python/cur...
-1
2016-07-20T08:41:45Z
38,488,713
<p>Based on @SSDMS suggestion (thanks!) the following can be used:</p> <pre><code>len(bson.BSON.encode(document)) </code></pre> <p>I have tested with a couple of documents in my DB, comparing the result at mongo shell and with the above Python method and getting the same result:</p> <p>At mongo shell:</p> <pre><cod...
0
2016-07-20T18:57:50Z
[ "python", "mongodb", "pymongo", "bson" ]
How can I get IntelliJ to index libraries in my Python Conda environment?
38,476,379
<p>I am using Python with Conda to manage my environment and libraries. Does anyone know how to get IntelliJ (with the Python plugin) or PyCharm to add the libraries in my Conda environment to my project?</p> <p>It only pulls in site packages even when I select ~/anaconda/bin/python as my Python Interpreter.</p>
0
2016-07-20T08:41:47Z
38,732,023
<p>You ned to change your <code>Project Interpreter</code> to point to <code>$CONDA_PREFIX/bin/python</code> where <code>$CONDA_PREFIX</code> is the <em>location</em> of your conda env. The <code>$CONDA_PREFIX</code> environment location you're looking for should be in the second column of the output from <code>conda ...
1
2016-08-02T23:28:10Z
[ "python", "intellij-idea", "pycharm", "conda" ]
Detecting events in a pandas data frame
38,476,501
<p>I have a pandas dataframe consisting of 0,1,-1's.</p> <pre><code>import pandas as pd df=pd.DataFrame({'indicator':[0, 0, 0, -1,0,0,1,0,-1,1,0,-1,0,1]}) </code></pre> <p>and I wan't to find the indices of every -1 and 1 such that the -1 is followed by some or none zeros and a +1. For exapmle in the above example ...
6
2016-07-20T08:46:55Z
38,476,905
<pre><code>s = pd.DataFrame({'indicator':[0, 0, 0, -1, 0, 0, 1, 0, -1, 1, 0, -1, 0, 1]}).squeeze() # reduce it to non-zeros s1 = s[s!=0] # must be -1 and next one be 1, grab index idx = s1.loc[(s1 == -1) &amp; (s1 != s1.shift(-1))].index # grab s1 index and...
6
2016-07-20T09:06:21Z
[ "python", "pandas" ]
Why do I get False when using issubclass in this way?
38,476,523
<pre><code># structure package/ m1.py m2.py # m1.py class A: pass if __name__ == '__main__': from m2 import B print(issubclass(B, A)) # m2.py from m1 import A class B(A): pass </code></pre> <p>I don't now why I get false while I think it's obviously true when I run m1.py. My python ver...
0
2016-07-20T08:47:37Z
38,476,700
<p>You have to derive class <code>A</code> from <code>object</code> to get <code>issubclass</code> do its job:</p> <p><a href="http://stackoverflow.com/questions/8107313/isinstance-and-issubclass-behavior-differently">isinstance() and issubclass() behavior differently</a></p> <pre><code>class A(object): ... </code></...
2
2016-07-20T08:56:08Z
[ "python", "python-3.x" ]
Why do I get False when using issubclass in this way?
38,476,523
<pre><code># structure package/ m1.py m2.py # m1.py class A: pass if __name__ == '__main__': from m2 import B print(issubclass(B, A)) # m2.py from m1 import A class B(A): pass </code></pre> <p>I don't now why I get false while I think it's obviously true when I run m1.py. My python ver...
0
2016-07-20T08:47:37Z
38,476,782
<p>You create 2 class objects, derived from the same class. That is: the class code is executed twice and thus results in 2 objects. And those are not the same. Example: see the output of the <code>print</code> statements below</p> <pre><code># m2.py from m1 import A class B(A): pass print(A) # m1.py class A: ...
1
2016-07-20T09:00:06Z
[ "python", "python-3.x" ]
Why do I get False when using issubclass in this way?
38,476,523
<pre><code># structure package/ m1.py m2.py # m1.py class A: pass if __name__ == '__main__': from m2 import B print(issubclass(B, A)) # m2.py from m1 import A class B(A): pass </code></pre> <p>I don't now why I get false while I think it's obviously true when I run m1.py. My python ver...
0
2016-07-20T08:47:37Z
38,477,315
<p>Wellcome to the world of modules and namespaces!</p> <p>Here is what happens:</p> <p>In module m2, you import A from module m1. So you create a class <code>m2.A</code> as a reference to class <code>m1.A</code>. It happens to have the same definition as <code>__main__.A</code>, but they are different objects, becau...
1
2016-07-20T09:23:12Z
[ "python", "python-3.x" ]
Debugger doesn't work out of a sudden in PyCharm
38,476,563
<p>I'm using:<br></p> <pre><code>PyCharm 2016.1.4 Build #PY-145.1504, built on May 25, 2016 JRE: 1.8.0_76-release-b198 x86_64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o </code></pre> <p>On a mac:</p> <pre><code>OSX El Capitan Version 10.11.4 </code></pre> <p>Without having made any changes to my code, I haven...
0
2016-07-20T08:50:01Z
38,481,440
<p>Disregard. I found the issue, there was a difference in which order stuff was loaded with debug and run, and therefore helper_evalifnotquoted couldn't be resolved.</p>
0
2016-07-20T12:33:04Z
[ "python", "django", "osx", "debugging", "pycharm" ]
Python requests call with URL using parameters
38,476,648
<p>I am trying to make a call to the import.io API. This call needs to have the following structure:</p> <blockquote> <p>'<a href="https://extraction.import.io/query/extractor/" rel="nofollow">https://extraction.import.io/query/extractor/</a>{{crawler_id}}?_apikey=xxx&amp;url=<a href="http://www.example.co.uk/items....
2
2016-07-20T08:53:28Z
38,477,032
<p>you will need to <a href="http://www.w3schools.com/tags/ref_urlencode.asp">URL encode</a> the URL you are sending to the API.</p> <p>The reason for this is that the ampersands are interpretted by the server as markers for parameters for the URL <a href="https://extraction.import.io/query/extractor/XXX">https://extr...
5
2016-07-20T09:11:19Z
[ "python", "python-requests", "import.io" ]
Django middleware 'module' object is not callable
38,476,711
<p>I have problem with middleware I found a lot of questions about it but nothing help in my case.</p> <p>I use middleware to get current_user to use in my model to save modified user in save method without write this in view.</p> <p>Here is <a href="http://stackoverflow.com/questions/862522/django-populate-user-id-w...
-2
2016-07-20T08:56:41Z
38,477,514
<p>You must give the full path of your middleware <strong>class</strong>. Not the module containing the middleware.</p> <pre><code>MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'dj...
2
2016-07-20T09:32:27Z
[ "python", "django", "django-middleware" ]
Pandas.read_excel: Accessing the home directory
38,476,733
<p><strong>[Solution Found]</strong></p> <p>I have encountered some unexpected behavior when trying to access my home directory using <code>pandas.read_excel</code>.</p> <p>The file I want to access can be found at</p> <pre><code>/users/isys/orsheridanmeth </code></pre> <p>which is where <code>cd ~/</code> takes me...
2
2016-07-20T08:57:33Z
38,476,908
<p>I believe <code>~</code> is expanded by the shell - in which case your code is literally trying to open a path starting with <code>~</code>. Oddly enough this doesn't work. :-)</p> <p>Try running the path through <code>os.path.expanduser()</code> first - that should work to expand the <code>~</code> variable to the...
4
2016-07-20T09:06:29Z
[ "python", "pandas", "path" ]
Finding all possible paths between two nodes in a large graph
38,476,795
<p>I'm using the following python code for finding all possible paths between two nodes but it return any thing, just waits for running.</p> <pre><code>def find_all_paths(graph, start, end, path=[]): path = path + [start] if start == end: return [] if start not in graph: return [] paths...
-1
2016-07-20T09:00:52Z
38,477,060
<p>One solution is using dynamic programming which I don't know how to use that</p>
0
2016-07-20T09:12:47Z
[ "python", "graph", "path", "dfs" ]
Printing neutron ports
38,476,799
<p>When I do this: <code>neutron.list_ports()</code></p> <p>It gives me : </p> <blockquote> <p>{'ports': [{u'status': u'DOWN', u'name': u'', u'allowed_address_pairs': [], u'admin_state_up': True, u'network_id': u'-xxxx-84f2-e881c29879e2', u'dns_name': u'', xxxx': [], u'dns_assignment': [{u'hostname': u'host-134-xxx...
-1
2016-07-20T09:01:05Z
38,476,858
<p>It seems like there could be multiple ports but if you just need the first ip you should be able to do:</p> <pre><code>neutron.list_ports()["ports"][0]["dns_assignment"][0]["ip_addess"] </code></pre> <p>this will return the first ip you should probably check if any of this is null first though</p>
0
2016-07-20T09:04:41Z
[ "python", "django", "openstack" ]
Python: Expanding the scope of the iterator variable in the any() function
38,476,877
<p>I wrote some structurally equivalent real world code, where I anticipated the result for <code>firstAdjective</code> would be <code>quick</code>. But the result shows that <code>word</code> is out of scope. What is a neat solution that will overcome this but still retain the 'linguistic' style of what I want to do? ...
3
2016-07-20T09:05:19Z
38,476,971
<p>You can use <code>next</code> on a <em>generator expression</em>:</p> <pre><code>firstAdjective = next((word for word in adjectives if word in text), None) if firstAdjective: ... </code></pre> <p>A default value of <code>None</code> is returned when the word is not found (credit @Bakuriu)</p> <p><strong>Tri...
1
2016-07-20T09:09:00Z
[ "python", "scope", "any" ]
Python: Expanding the scope of the iterator variable in the any() function
38,476,877
<p>I wrote some structurally equivalent real world code, where I anticipated the result for <code>firstAdjective</code> would be <code>quick</code>. But the result shows that <code>word</code> is out of scope. What is a neat solution that will overcome this but still retain the 'linguistic' style of what I want to do? ...
3
2016-07-20T09:05:19Z
38,477,096
<p>Would something like</p> <pre><code>for word in filter(lambda x: x in adjectives, text.split()): print word </code></pre> <p>work?</p>
0
2016-07-20T09:14:12Z
[ "python", "scope", "any" ]
Python: Expanding the scope of the iterator variable in the any() function
38,476,877
<p>I wrote some structurally equivalent real world code, where I anticipated the result for <code>firstAdjective</code> would be <code>quick</code>. But the result shows that <code>word</code> is out of scope. What is a neat solution that will overcome this but still retain the 'linguistic' style of what I want to do? ...
3
2016-07-20T09:05:19Z
38,477,305
<p>Your example does not work because the <code>word</code> variable only exists during the evaluation of the condition. Once it is done finding whether the condition is true or false, the variable goes out of scope and does not exist anymore. </p> <p>Even declaring it first doesn't help, as it doesn't affect the exis...
0
2016-07-20T09:22:52Z
[ "python", "scope", "any" ]
Python: Expanding the scope of the iterator variable in the any() function
38,476,877
<p>I wrote some structurally equivalent real world code, where I anticipated the result for <code>firstAdjective</code> would be <code>quick</code>. But the result shows that <code>word</code> is out of scope. What is a neat solution that will overcome this but still retain the 'linguistic' style of what I want to do? ...
3
2016-07-20T09:05:19Z
38,478,069
<pre><code>&gt;&gt;&gt; text = 'the quick brown fox jumps over the lazy dog' &gt;&gt;&gt; &gt;&gt;&gt; # 1. Case with no match among the adjectives: Result None as expected &gt;&gt;&gt; adjectives = ['slow', 'crippled'] &gt;&gt;&gt; firstAdjective = next((word for word in adjectives if word in text), None) &gt;&gt;&gt;...
-1
2016-07-20T09:58:05Z
[ "python", "scope", "any" ]
How to extract a certain string using RegEx (Python 3.5)
38,476,906
<p>I'm using Python to scrape some data in a website.I got the scraping part done but I need to extract the data I need. </p> <p>Here's a sample of the results I got:</p> <pre><code>{ 'thisversionrun': 'Mon Jul 18 2016 10:36:16 GMT+0000 (UTC)', 'lastrunstatus': 'success', 'name': 'Rudolph1', 'version': 3, '...
-3
2016-07-20T09:06:28Z
38,477,581
<p>Try this :</p> <pre><code>data = re.findall(r'(?is)property1\':\s*\'(.*?)\'\}',str(input_text)) print(data) </code></pre>
3
2016-07-20T09:35:57Z
[ "python", "regex", "python-3.x" ]
How to extract a certain string using RegEx (Python 3.5)
38,476,906
<p>I'm using Python to scrape some data in a website.I got the scraping part done but I need to extract the data I need. </p> <p>Here's a sample of the results I got:</p> <pre><code>{ 'thisversionrun': 'Mon Jul 18 2016 10:36:16 GMT+0000 (UTC)', 'lastrunstatus': 'success', 'name': 'Rudolph1', 'version': 3, '...
-3
2016-07-20T09:06:28Z
38,477,737
<p>Try this:</p> <pre><code># encoding: utf-8 import re scrappedString = """{'thisversionrun': 'Mon Jul 18 2016 10:36:16 GMT+0000 (UTC)', 'lastrunstatus': 'success', 'name': 'Rudolph1', 'version': 3, 'count': 30, 'newdata': True, 'thisversionstatus': 'success', 'results': {'collection1': [{'property1': "Ano ang 'Margi...
1
2016-07-20T09:43:35Z
[ "python", "regex", "python-3.x" ]
Handle multiprocess in python
38,476,912
<p>My code is processing some parallel perforce tasks while showing a progress bar and letting user to terminate the job whenever he wants, the problem is when user clicks the <code>close</code> button the thread function is not being killed but the lock is released and the main UI thread is being unlocked. The <code>p...
1
2016-07-20T09:06:47Z
38,565,511
<p>The only solution I could give is to pass p4 object to calling thread as argument so that p4 server connection can disconnect when user wants to cancel the job.</p> <pre><code>def P4SyncLibrary(p4, args, que): syncType = args[0] view = args[1] try: p4.run_sync(view) except P4Exception: ...
0
2016-07-25T10:37:32Z
[ "python", "multithreading", "perforce" ]
How can I convert a list of hex colors (or RGB, sRGB) stored in a text file into an Image
38,477,123
<p>I have a list of approx. 1000 hex colors which I would like to convert into an image with (e.g. a grid of squares or rectangles) filled with these colors. Is there an easy way to achieve this in Imagemagick (or any other software: e.g. Processing/Python). </p> <p>Thanks for your help</p>
-1
2016-07-20T09:15:19Z
38,477,449
<p>Code is in python You can use the following steps:</p> <ol> <li><p>convert your list to numpy array </p> <p>import numpy as np </p> <p>myarray = np.asarray(mylist)</p></li> <li><p>Use scipy to save the numpy array you have just created</p> <p>from scipy.misc import toimage</p> <p>rgb = scipy.misc.toimage(myarra...
1
2016-07-20T09:29:19Z
[ "python", "imagemagick", "processing" ]
How can I convert a list of hex colors (or RGB, sRGB) stored in a text file into an Image
38,477,123
<p>I have a list of approx. 1000 hex colors which I would like to convert into an image with (e.g. a grid of squares or rectangles) filled with these colors. Is there an easy way to achieve this in Imagemagick (or any other software: e.g. Processing/Python). </p> <p>Thanks for your help</p>
-1
2016-07-20T09:15:19Z
38,481,950
<p>You've tagged this with the <a href="/questions/tagged/processing" class="post-tag" title="show questions tagged &#39;processing&#39;" rel="tag">processing</a> tag, so here is the Processing solution:</p> <p><strong>Step 1:</strong> Load the file. You can use the <code>loadStrings()</code> functions for this. This ...
0
2016-07-20T12:56:01Z
[ "python", "imagemagick", "processing" ]
How can I convert a list of hex colors (or RGB, sRGB) stored in a text file into an Image
38,477,123
<p>I have a list of approx. 1000 hex colors which I would like to convert into an image with (e.g. a grid of squares or rectangles) filled with these colors. Is there an easy way to achieve this in Imagemagick (or any other software: e.g. Processing/Python). </p> <p>Thanks for your help</p>
-1
2016-07-20T09:15:19Z
38,482,684
<p>I would use <code>bash</code> and <code>ImageMagick</code> like this:</p> <pre><code>while read h; do convert xc:"$h" miff:- ; done &lt; colours | montage -geometry +0+0 miff:- result.png </code></pre> <p>So, if your file <code>colours</code> looks like this:</p> <pre><code>#000000 #ffffff #ff0000 #00ff00 #0000ff...
0
2016-07-20T13:28:18Z
[ "python", "imagemagick", "processing" ]
Django how to iterate through a list of objects in a view?
38,477,153
<p>So I have a view that asks the user for input and I cannot figure out what to do to somehow iterate through the list and get the user input on all the objects...</p> <pre><code>def get(self, request, language, word): '''Get reqeust to edit taken in steps''' context = cache.get(word) form_class = Definit...
0
2016-07-20T09:16:35Z
38,514,721
<p>In this case the answer for me was to use <a href="https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#model-formsets" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#model-formsets</a> and add a queryset as an argument. </p> <p>I could then pass it to the template as contex...
0
2016-07-21T21:32:07Z
[ "python", "django" ]
Tkinter GUI is not responding
38,477,336
<p>I have only one while loop and the Tkonter say: GUI is not responding. What I'm doing wrong ? I would like with button "Pause" break and again with "button "Start" continue the program.</p> <pre><code>import Tkinter, time root = Tkinter.Tk class InterfaceApp(root): def __init__ (self, parent): root.__...
-2
2016-07-20T09:23:59Z
38,478,012
<p>Your code is nonsense. You have to figure out how to define functions and use them properly first. I wrote a little example for you:</p> <pre><code>from tkinter import * class App: def __init__(self, master): self.master = master self.startb = Button(master, text="Start", command=self.startf) ...
1
2016-07-20T09:55:43Z
[ "python", "tkinter" ]
Tkinter GUI is not responding
38,477,336
<p>I have only one while loop and the Tkonter say: GUI is not responding. What I'm doing wrong ? I would like with button "Pause" break and again with "button "Start" continue the program.</p> <pre><code>import Tkinter, time root = Tkinter.Tk class InterfaceApp(root): def __init__ (self, parent): root.__...
-2
2016-07-20T09:23:59Z
38,479,109
<h3>First issue:</h3> <p>Using the while loop. To call a function again after it finished use </p> <p><code>self.after(&lt;time in ms&gt;, &lt;function to call&gt;)</code></p> <p>at the end of your <code>def Start(self)</code></p> <p>Would look like this:</p> <pre><code> # ... def Start(self): print("X") ...
3
2016-07-20T10:45:37Z
[ "python", "tkinter" ]
load data in exact order from json string(python, django)
38,477,439
<p>I have json data coming from ajax,jquery as below</p> <pre><code>json_data_from_ajax = u'{"1_sd":{"name":"unicode","data_type_choices":"Unicode"},"2_sd":{"name":"unicode_secret","data_type_choices":"Unicode"},"3_sd":{"name":"unicode_mandatory","data_type_choices":"Unicode"},"4_sd":{"name":"boolean","data_type_choic...
0
2016-07-20T09:28:36Z
38,477,800
<p>This might help (doesn't work for python &lt;2.7):</p> <pre><code>import simplejson as json from collections import OrderedDict settings_records = json.loads(json_data_from_ajax, object_pairs_hook=OrderedDict) </code></pre>
0
2016-07-20T09:46:56Z
[ "jquery", "python", "json", "ajax", "django" ]
load data in exact order from json string(python, django)
38,477,439
<p>I have json data coming from ajax,jquery as below</p> <pre><code>json_data_from_ajax = u'{"1_sd":{"name":"unicode","data_type_choices":"Unicode"},"2_sd":{"name":"unicode_secret","data_type_choices":"Unicode"},"3_sd":{"name":"unicode_mandatory","data_type_choices":"Unicode"},"4_sd":{"name":"boolean","data_type_choic...
0
2016-07-20T09:28:36Z
38,478,296
<p>This will work for you :</p> <pre><code>from django.core import serializers import json data = serializers.serialize('json', json_data_from_ajax) result = json.dumps(data) </code></pre>
-1
2016-07-20T10:08:01Z
[ "jquery", "python", "json", "ajax", "django" ]