prefix
stringclasses
1 value
input_text
stringlengths
10
172
target_text
stringlengths
18
33.9k
QA:
Different result for String and Integers using JSON in python
<p>Editting based on the <em>edit</em> in the question:</p> <p>As far as your output is considered, it is giving me:</p> <pre><code>92 -&gt; 87; 87 -&gt; 87; 87 -&gt; 96; 92 -&gt; 96; 96 -&gt; 90; 96 -&gt; 105; </code></pre> <p>It is showing <code>"87"</code> and <code>87</code> as same because you are using <code>.format()</code> with <code>print</code> which inserts the value in string independent of maintaing the quotes <code>"</code>. For example:</p> <pre><code>&gt;&gt;&gt; '{}'.format(1) '1' &gt;&gt;&gt; '{}'.format('1') '1' </code></pre> <p>In order to fix this, you may do:</p> <pre><code>for parent, child in edges: parent = '"{}"'.format(parent) if isinstance(parent, str) else parent child = '"{}"'.format(child) if isinstance(child, str) else child print(' {0} -&gt; {1};'.format(parent, child)) </code></pre> <p>which prints:</p> <pre><code>"92" -&gt; "87"; "87" -&gt; 87; "87" -&gt; 96; "92" -&gt; "96"; "96" -&gt; 90; "96" -&gt; 105; </code></pre>
QA:
converting non-numeric to numeric value using Panda libraries
<p>To encode non-numeric data to numeric you can use scikit-learn's <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html#sklearn.preprocessing.LabelEncoder" rel="nofollow">LabelEncoder</a>. It will encode each category such as COL1's <code>a</code>, <code>b</code>, <code>c</code> to integers.</p> <p>Assuming df is your dataframe, try:</p> <pre><code>from sklearn.preprocessing import LabelEncoder enc = LabelEncoder() enc.fit(df['COL1']) df['COL1'] = enc.transform(df['col1']) </code></pre> <ul> <li><code>enc.fit()</code> creates the corresponding integer values.</li> <li><code>enc.transform()</code> applies the encoding to the df values.</li> </ul> <p>For the second column, using Pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">to_datetime()</a> function should do the trick, like @quinn-weber mentioned, try:</p> <pre><code>df['COL2'] = pd.to_datetime(df['COL2']) </code></pre>
QA:
Django choices and dictionary
<p>I would comment, but sadly not enough rep. The way <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.IntegerField" rel="nofollow">IntegerField</a> is setup, it displays the dictionary value and returns the dictionary key.</p> <p>What it seems you want to do is have that key determine the results of several other values. What you should do then is in whatever view you submit that form to, set those other values based on the key returned by your IntegerField.</p> <p>In other words:</p> <pre><code>CATEGORY_CHOICES = ((1, 'Jobs'),(2, 'Cities'),) </code></pre> <p>Then later in the class or view that this form is submitted to:</p> <pre><code>if CATEGORY_CHOICES == 1: title = 'Jobs' icon = 'fa fa-briefcase' slug = 'jobs' elif CATEGORY_CHOICES == 2: title = 'Cities' ` icon = 'fa fa-city' slug = 'cities' </code></pre>
QA:
converting non-numeric to numeric value using Panda libraries
<p>You could convert COL1 with something like this: </p> <pre><code>import pandas as pd import string table = pd.DataFrame([ ['a','9/8/2016',2], ['b','12/4/2016',23], ['n','1/1/2015',21], ], columns=['COL1', 'COL2', 'COL3']) table['COL1'] = table['COL1'].map(dict(zip(list(string.lowercase), xrange(0,25)))) </code></pre> <p>As for the timestamp, you could do:</p> <pre><code>table['COL2'] = pd.to_datetime( table['COL2'], format='%m/%d/%Y' ).dt.strftime(date_format='%Y%m%d') </code></pre>
QA:
can't assign to function call Error-Python
<p>Your error is here:</p> <pre><code>for barcode(a) in s: </code></pre> <p>It's invalid syntax because the name bound in a for loop has to be a python identifier. </p> <p>You were probably trying for something like this instead:</p> <pre><code>for the_zipcode in s: print(barcode(the_zipcode)) </code></pre>
QA:
install ns3.21 in ubuntu16.04 error
<p>I personally tried to do that and it didn't worth the trouble at all so I ended up installing it on Ubuntu 14.04.</p> <p>In case you have no other choice, try watching this <a href="https://www.youtube.com/watch?v=SckgZkBg-Oc" rel="nofollow">tutorial</a></p>
QA:
Getting attributes of a class
<pre><code>import re class MyClass: a = "12" b = "34" def myfunc(self): return self.a attributes = [a for a, v in MyClass.__dict__.items() if not re.match('&lt;function.*?&gt;', str(v)) and not (a.startswith('__') and a.endswith('__'))] </code></pre> <p>For an instance of MyClass, such as</p> <pre><code>mc = MyClass() </code></pre> <p>use <code>type(mc)</code> in place of <code>MyClass</code> in the list comprehension. However, if one dynamically adds an attribute to <code>mc</code>, such as <code>mc.c = "42"</code>, the attribute won't show up when using <code>type(mc)</code> in this strategy. It only gives the attributes of the original class.</p> <p>To get the complete dictionary for a class instance, you would need to COMBINE the dictionaries of <code>type(mc).__dict__</code> and <code>mc.__dict__</code>.</p> <pre><code>mc = MyClass() mc.c = "42" # Python 3.5 combined_dict = {**type(mc).__dict__, **mc.__dict__} # Or Python &lt; 3.5 def dict_union(d1, d2): z = d1.copy() z.update(d2) return z combined_dict = dict_union(type(mc).__dict__, mc.__dict__) attributes = [a for a, v in combined_dict.items() if not re.match('&lt;function.*?&gt;', str(v)) and not (a.startswith('__') and a.endswith('__'))] </code></pre>
QA:
How to split files according to a field and edit content
<p>AWK will do the trick:</p> <pre><code>awk '{ print "&gt;"$1 "\n" $2 &gt;&gt; $3".txt"}' input.txt </code></pre>
QA:
Error when passing parameter to form
<p>In <code>self.form = MyForm</code> you assign a class object to self.form. In <code>self.form = MyForm(my_id=obj_id)</code> you instantiate an object of class MyForm and assign it to self.form. </p> <p>Django expect to find a class in <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form" rel="nofollow">self.form</a>, not an instance.</p>
QA:
Restarting a function in Python 3.4
<p>To capture the return of the <code>modMode</code> function, <strong>just make sure you return something at the end</strong>:</p> <pre><code>score = 0; modPassword = "200605015" def modMode(score): print("Entering Overide Mode") print("Opening Overide Console") cmd = input("Enter Command: ") if cmd == "corr": print("Adding one point") score = score+1 elif cmd == "manScoreChng": score = int(input("What do want the score to be?")) elif cmd == 'exit': raise Exception('Bye!') return int(score) # MAKE SURE YOU HAVE THIS LINE HERE </code></pre> <hr> <p>To call the <code>modScore</code> command over and over again, use a loop.</p> <pre><code>try: while True: score = modMode(score) # grab the returned value from modMode by using `=` print(score) except Exception: pass </code></pre> <p>This will run until the user types in exit.</p>
QA:
Recursive functions : Inversing word
<p>You don't really need recursion here.</p> <pre><code>def inverse(chars): char_list = list(chars) char_list.reverse() return ''.join(char_list) </code></pre>
QA:
How do you make it so that a function returns a tuple divided in multiple lines?
<p>Here芒聙聶s the quick and dirty way:</p> <pre><code>def formatted_tuple(x): st = '%s' % (x,) return st.replace('),', '),\n') # now you can call formatted_tuple(hello) </code></pre>
QA:
Getting HTTP POST Error : {"reason":null,"error":"Request JSON object for insert cannot be null."}
<p>This is a working example I tested on my instance. I am using REST Table API to insert a change request. It's not true that it can not be http. It's whatever protocol your instance allows to connect, say from browser. </p> <pre><code>#Need to install requests package for python #easy_install requests import requests # Set the request parameters url = '&lt;yourinstance base url&gt;/api/now/table/change_request' user = &lt;username&gt; pwd = &lt;password&gt; # Set proper headers headers = {"Content-Type":"application/json","Accept":"application/json"} # Do the HTTP request response = requests.post(url, auth=(user, pwd), headers=headers ,data="{\"short_description\":\"test in python\"}") # Check for HTTP codes other than 201 if response.status_code != 201: print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json()) exit() # Decode the JSON response into a dictionary and use the data data = response.json() print(data) </code></pre>
QA:
How to execute multiline python code from a bash script?
<p>Use a here-doc:</p> <pre><code>result=$(python &lt;&lt;EOF import stuff print('all $code in one very long line') EOF ) </code></pre>
QA:
error handling with BeautifulSoup when scraped url doesn't respond
<p>You may check the value of <code>name_box</code> variable - it would be <code>None</code> if nothing found:</p> <pre><code>for row in urllist[4:8]: page = urllib2.urlopen(row) soup = BeautifulSoup(page, 'html.parser') name_box = soup.find(attrs={'class': 'nb-shares'}) if name_box is None: continue # ... </code></pre>
QA:
Collision Between two sprites - Python 3.5.2
<p>Well there are many different ways to detect collision, And it might be worth looking at libraries that would do so, but the simplest method by far is to use <code>pygame.sprite.spritecollide()</code>.</p> <p>But before I can show how to use the function, you need to know what a <code>pygame.sprite.Group()</code> is and what a sprite class is.</p> <p>Basicly, what a <code>pygame.sprite.Group()</code> is, is a way to keep track of and hold multiple sprites. In your case, it seems making a missile group for your missiles would be the best choice.</p> <p>So I would create a group to hold your missiles: <code>missiles_group = pygame.sprite.Group()</code>. You can add missiles to the group by saying <code>missiles_group.add(&lt;sprite instance name&gt;)</code>.</p> <p>As for the sprite class, please see this answer I gave to a question. To be terse, a Sprite class is a modular way to create a sprite. Instead of using just a plain image, a sprite class would hold necessary methods and attributes of a sprite. I will be using a sprite class in my example below, so if more detail is needed, please read the answer I linked to above. </p> <hr> <p>With that out of the way, and without going into too much detail, here is how you fill in each function parameter to the above function.</p> <ul> <li><code>sprite</code>: This is the sprite that will be tested against a group of sprites</li> <li><code>group</code>: This is the group that will be used to test with the sprite.</li> <li><code>dokill</code>: This is a boolean value. If set to true, each time the <code>sprite</code> parameter collides with something in the <code>group</code> parameter, and object from the group parameter will be deleted. And visa versa if the <code>dokill</code> argument is set to false. The is one more parameter that the function takes, but for what you're trying to do, it is not needed.</li> </ul> <p>Incorporating the above information, here is an example. The example creates a sprite and a list of sprites. Each time the sprite collides with a sprite from the group, <code>HIT</code> is printed to the screen:</p> <pre><code>import pygame #import the pygame module into the namespace &lt;module&gt; WIDTH = 640 # define a constant width for our window HEIGHT = 480 # define a constant height for our window #create a pygame window, and #initialize it with our WIDTH and HEIGHT constants display = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() # create a game clock class Sprite(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((20, 20)) self.image.fill((255, 0, 0)) self.rect = self.image.get_rect() self.rect.x = WIDTH / 2 self.rect.y = HEIGHT / 2 self.vx = 0 self.vy = 0 def update(self): self.vx = 0 self.vy = 0 key = pygame.key.get_pressed() if key[pygame.K_LEFT]: self.vx = -1 elif key[pygame.K_RIGHT]: self.vx = 1 if key[pygame.K_UP]: self.vy = -1 elif key[pygame.K_DOWN]: self.vy = 1 self.rect.x += self.vx self.rect.y += self.vy # cretae a player sprite player = Sprite() # create a group to hold all of our sprites sprites = pygame.sprite.Group() # create a group to hold sprites we want to # test collions against. These sprites will # still be added to the sprites list # but we need a seperate group to test for # collisions against collision_sprites = pygame.sprite.Group() # add a sprite to out collison sprite group # We also add the sprite to our sprites group # that holds all sprites tmp = Sprite() tmp.update = lambda: None sprites.add(tmp) collision_sprites.add(tmp) # add a player sprites to the player group player.rect.x = 10 sprites.add(player) running = True # our variable for controlling our game loop while running: for e in pygame.event.get(): # iterate ofver all the events pygame is tracking clock.tick(60) # make our clock keep pour game at 60 FPS if e.type == pygame.QUIT: # is the user trying to close the window? running = False # if so break the loop pygame.quit() # quit the pygame module quit() # quit is for IDLE friendliness sprites.update() # here is where we test for collision if pygame.sprite.spritecollide(player, collision_sprites, False): print("HIT!") display.fill((180, 180, 180)) # fill the pygame screen with white sprites.draw(display) pygame.display.flip() # update the screen </code></pre> <p>My example if fairly big, so take your time and step through it carefully. I tried to add as many good comments as I could. Good luck!</p>
QA:
How to execute multiline python code from a bash script?
<p>Tanks to <a href="http://stackoverflow.com/a/37222377/333403">this SO answer</a> I found the answer myself:</p> <pre><code>#!/bin/bash # some bash code END_VALUE=10 PYTHON_CODE=$(cat &lt;&lt;END # python code starts here import math for i in range($END_VALUE): print(i, math.sqrt(i)) # python code ends here END ) # use the res="$(python3 -c "$PYTHON_CODE")" # continue with bash code echo "$res" </code></pre>
QA:
can't assign to function call Error-Python
<p>I am fairly certain your problem is your use of <code>s=zipcode.split(",")</code>. What that does is split the string that is put in by the user (if you're using python 3) into an array of strings, where each element is delimited by a comma. For example:</p> <pre><code>'11111'.split(',') # ['11111'] '11111,12345'.split(',') # ['11111', '12345'] </code></pre> <p>That is almost certainly not what you want, since you're asking the user to input a 5-digit zip code. If you just use the input directly, I think you'll get what you want.</p> <p>That is:</p> <pre><code>zipcode=input("What is your 5 digit zipcode?") # . . . for digit in zipcode: print(barcode(digit)) </code></pre>
QA:
finding cubed root using delta and epsilon in Python
<p>First thing, you should use <code>if/elif</code> instead of separate <code>if</code> blocks. </p> <p>Consider the following: when <code>guess**3 &gt; num</code> is <code>True</code>, you update <code>guess</code> by reducing its value so that <code>guess**3 &lt; num</code> (the next if condition) becomes <code>True</code> again, which reverses the initial update. In summary, the value of <code>guess</code> is never changed in that loop, and the loop whirls to infinity.</p> <p>Secondly you want to regularize the <code>delta</code> value (penalize it) as it can be come alarming large as the value of <code>num</code> increases.</p> <pre><code>num = 100 epsilon = 0.01 guess = num/3.0 while abs(guess**3 - num) &gt;= epsilon: delta = abs(guess**3 - num)/num if guess**3 &gt; num: guess = (guess - delta*epsilon**0.5) elif guess**3 &lt; num: guess = (guess + delta*epsilon**0.5) print("Guess:", guess) </code></pre>
QA:
errors with webdriver.Firefox() with selenium
<p>If you are using firefox ver >47.0.1 you need to have the <code>[geckodriver][1]</code> executable in your system path. For earlier versions you want to turn marionette off. You can to so like this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities capabilities = DesiredCapabilities.FIREFOX.copy() capabilities['marionette'] = False driver = webdriver.Firefox(capabilities=capabilities) </code></pre>
QA:
Can't pass random variable to tf.image.central_crop() in Tensorflow
<p>I solved my own problem defining the following function. I adjusted the code provided in tf.image.central_crop(image, central_fraction). The function RandomCrop will crop an image taking a central_fraction drawn from a uniform distribution. You can just specify the min and max fraction you want. You can replace random_uniform distribution to a different one obviously.</p> <pre><code>def RandomCrop(image,fMin, fMax): from tensorflow.python.ops import math_ops from tensorflow.python.ops import array_ops from tensorflow.python.framework import ops image = ops.convert_to_tensor(image, name='image') if fMin &lt;= 0.0 or fMin &gt; 1.0: raise ValueError('fMin must be within (0, 1]') if fMax &lt;= 0.0 or fMax &gt; 1.0: raise ValueError('fMin must be within (0, 1]') img_shape = array_ops.shape(image) depth = image.get_shape()[2] my_frac2 = tf.random_uniform([1], minval=fMin, maxval=fMax, dtype=tf.float32, seed=42, name="uniform_dist") fraction_offset = tf.cast(math_ops.div(1.0 , math_ops.div(math_ops.sub(1.0,my_frac2[0]), 2.0)),tf.int32) bbox_h_start = math_ops.div(img_shape[0], fraction_offset) bbox_w_start = math_ops.div(img_shape[1], fraction_offset) bbox_h_size = img_shape[0] - bbox_h_start * 2 bbox_w_size = img_shape[1] - bbox_w_start * 2 bbox_begin = array_ops.pack([bbox_h_start, bbox_w_start, 0]) bbox_size = array_ops.pack([bbox_h_size, bbox_w_size, -1]) image = array_ops.slice(image, bbox_begin, bbox_size) # The first two dimensions are dynamic and unknown. image.set_shape([None, None, depth]) return(image) </code></pre>
QA:
Scrapy spider for JSON response is giving me error
<p>I can't seem to reproduce your error but upon copying your code, I got a key error which pertains to your yield statement. See the code below:</p> <pre><code>import scrapy import json class SpidyQuotesSpider(scrapy.Spider): name = "hotelspider" allowed_domains = ["tr.hotels.com"] start_urls = ( 'https://tr.hotels.com/search/listings.json?destination-id=1648683&amp;q-check-out=2016-10-22&amp;q-destination=Didim,+T%C3%BCrkiye&amp;q-room-0-adults=2&amp;pg=2&amp;q-rooms=1&amp;start-index=7&amp;q-check-in=2016-10-21&amp;resolved-location=CITY:1648683:UNKNOWN:UNKNOWN&amp;q-room-0-children=0&amp;pn=1', ) def parse(self, response): myresponse = json.loads(response.body) data = myresponse.get('data') body = data.get('body') searchresults = body.get('searchResults') for item in searchresults.get('results', []): yield { 'text': item['altText'] } </code></pre> <p>Make sure you are indenting using the same amount of spaces or just use TAB. Though the indentation shown in your code seems fine. Try pasting mine and see what comes up.</p>