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 |
---|---|---|---|---|---|---|---|---|---|
TypeError: cannot concatenate 'str' and 'NoneType' objects when placing the custom url in scrapy.Request() | 39,794,747 | <p>I get a url that cannot be used to fetch data from next page, so created a <code>base_url = 'http://www.marinetraffic.com'</code> variable and passed it scrapy request. <code>port_homepage_url = base_url + port_homepage_url</code>. It works fine, when i yeild the result like this. <code>yield {'a': port_homepage_url, 'b':item['port_name']}</code>
I get this result i wanted. </p>
<p><a href="http://www.marinetraffic.com/en/ais/index/ships/range/port_id:20585/port_name:FUJAIRAH%20ANCH,FUJAIRAH" rel="nofollow">http://www.marinetraffic.com/en/ais/index/ships/range/port_id:20585/port_name:FUJAIRAH%20ANCH,FUJAIRAH</a> ANCH</p>
<p>however if place it in scrapy request <code>yield scrapy.Request(port_homepage_url, callback=self.parse, meta={'item': item})</code> i get error </p>
<pre><code>port_homepage_url = base_url + port_homepage_url
TypeError: cannot concatenate 'str' and 'NoneType' objects
</code></pre>
<p>here is code</p>
<pre><code>class GetVessel(scrapy.Spider):
name = "getvessel"
allowed_domains = ["marinetraffic.com"]
start_urls = [
'http://www.marinetraffic.com/en/ais/index/ports/all/flag:AE',
]
def parse(self, response):
item = VesseltrackerItem()
base_url = 'http://www.marinetraffic.com'
for ports in response.xpath('//table/tr[position()>1]'):
item['port_name'] = ports.xpath('td[2]/a/text()').extract_first()
port_homepage_url = ports.xpath('td[7]/a/@href').extract_first()
port_homepage_url = base_url + port_homepage_url
yield scrapy.Request(port_homepage_url, callback=self.parse, meta={'item': item})
</code></pre>
| 2 | 2016-09-30T15:11:26Z | 39,794,893 | <p>The problem does not happen on the initial start URL page, but happens later on when subsequent requests are processed. Take for example <a href="http://www.marinetraffic.com/en/ais/index/ships/range/port_id:1699/port_name:HAMRIYA" rel="nofollow">this page</a>. There are no links in the 7-th <code>td</code> element and, hence, <code>ports.xpath('td[7]/a/@href').extract_first()</code> returns <code>None</code> which results in a failure on the <code>port_homepage_url = base_url + port_homepage_url</code> line.</p>
<p>How to approach the problem depends on what were you planning to do on the "port" pages. From what I understand, you did not mean to actually handle the "port" page requests with <code>self.parse</code> and need to have a separate callback with different logic inside.</p>
| 2 | 2016-09-30T15:20:21Z | [
"python",
"scrapy"
]
|
When saving ManyToMany Field value in django ,error occures invalid literal for int() with base 10 | 39,794,828 | <p>I am trying to save ManyToMany filed value in django model objects.But when i ma saving an error comes invalid literal for int() with base 10.
My code is</p>
<pre><code>def saveDetail(request):
userExp = str(request.GET.get('user'))
tags = request.POST.getlist('tags')
comment = request.POST.get('comment')
exp = customer.objects.get(user = userExp)
exp.tags = tags
exp.save()
</code></pre>
<p>and the error is </p>
<pre><code>ValueError: invalid literal for int() with base 10: 'tag2
</code></pre>
<p>my tagExp model is</p>
<pre><code>class TagsExp(models.Model):
label=models.CharField(max_length=50,null=True, blank=True)
def __unicode__(self):
return str(self.label)
</code></pre>
<p>My customer model is</p>
<pre><code>class Customer(models.Model):
user = models.OneToOneField(User) remark = models.TextField(null=True, blank=True)
tags = models.ManyToManyField(TagsExp, null=True, blank=True)
time = models.DateField(null=True)
</code></pre>
<p>I have added traceback of my error below.</p>
<p>Traceback:</p>
<pre><code>File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/channels/handler.py" in process_exception_by_middleware
227. return super(AsgiHandler, self).process_exception_by_middleware(exception, request)
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
23. return view_func(request, *args, **kwargs)
File "/home/cp/Documents/projects/beta/upKonnect/decorators.py" in wrapped
12. return view_func(request, *args, **kwargs)
File "/home/cp/Documents/projects/beta/adminProfile/views.py" in saveExpDetail
506. exp.tags = tags
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py" in __set__
481. manager.set(value)
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py" in set
910. self.add(*new_objs)
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py" in add
843. self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py" in _add_items
986. '%s__in' % target_field_name: new_ids,
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/query.py" in filter
790. return self._filter_or_exclude(False, *args, **kwargs)
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
808. clone.query.add_q(Q(*args, **kwargs))
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
1243. clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
1269. allow_joins=allow_joins, split_subq=split_subq,
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
1199. condition = lookup_class(lhs, value)
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/lookups.py" in __init__
19. self.rhs = self.get_prep_lookup()
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/fields/related_lookups.py" in get_prep_lookup
54. self.lookup_name, self.rhs)
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_lookup
746. return [self.get_prep_value(v) for v in value]
File "/home/cp/Documents/beta/envBeta/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
976. return int(value)
Exception Type: ValueError at /upadmin/save-Exp-Detail/
Exception Value: invalid literal for int() with base 10: 'tag2 '
</code></pre>
| 0 | 2016-09-30T15:16:22Z | 39,795,071 | <p><code>tags</code> is a <code>ManyToMany</code> field. You can't use a direct assignment to a list item to update the field. You should instead assign via the field's <code>add</code> method tag <em>objects</em> corresponding to the items in the list.</p>
<p>Assuming you <code>TagsExp</code> has a field <code>label</code> which corresponds to the items in the list, you would do:</p>
<pre><code>for tag_label in tags:
tag_label = tag_label.strip().lower() # clean up tag
tag, _ = TagsExp.objects.get_or_create(label=tag_label)
exp.tags.add(tag)
exp.save()
</code></pre>
<hr>
<p>On another note, the tag in your traceback has a trailing space. That would create a new tag if there were no clean up as opposed to getting the existing one. Also, multiple cases will not be handled by default. I think you should give a look to <a href="https://django-taggit.readthedocs.io/en/latest/" rel="nofollow"><code>django-taggit</code></a> app for <em>tagging</em> which has great features for managing whitespace characters and different cases.</p>
| 1 | 2016-09-30T15:30:36Z | [
"python",
"django"
]
|
Understanding Parsing Error when reading model file into PySD | 39,794,851 | <p>I am receiving the following error message when I try to read a Vensim model file (.mdl) using Python's PySD package. </p>
<p>My code is:</p>
<pre><code>import pysd
import os
os.chdir('path/to/model_file')
model = pysd.read_vensim('my_model.mdl')
</code></pre>
<p>The Error I receive is:</p>
<pre><code>Traceback (most recent call last):
Python Shell, prompt 13, line 1
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pysd/pysd.py", line 53, in read_vensim
py_model_file = translate_vensim(mdl_file)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pysd/vensim2py.py", line 673, in translate_vensim
entry.update(get_equation_components(entry['eqn']))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pysd/vensim2py.py", line 251, in get_equation_components
tree = parser.parse(equation_str)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/parsimonious/grammar.py", line 123, in parse
return self.default_rule.parse(text, pos=pos)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/parsimonious/expressions.py", line 110, in parse
node = self.match(text, pos=pos)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/parsimonious/expressions.py", line 127, in match
raise error
parsimonious.exceptions.ParseError: Rule 'subscriptlist' didn't match at '' (line 1, column 21).
</code></pre>
<p>I have searched for this particular error and I cannot find much information on the failed matching rule for 'subscriptlist'. </p>
<p>I appreciate any insight. Thank you.</p>
| 0 | 2016-09-30T15:17:57Z | 40,115,491 | <p>Good news is that there is nothing wrong with your code. =) (Although you can also just include the path to the file in the <code>.read_vensim</code> call, if you don't want to make the dir change). </p>
<p>That being the case, there are a few possibilities that would cause this issue. One is if the model file is created with a sufficiently old version of Vensim, the syntax may be different from what the current parser is designed for. One way to get around this is to update Vensim and reload the model file there - Vensim will update to the current syntax.</p>
<p>If you are already using a recent version of Vensim (the parser was developed using syntax of Vensim 6.3E) then the parsing error may be due to a feature that isn't yet included. There are still some outstanding issues with subscripts, which you can read about <a href="https://github.com/JamesPHoughton/pysd/issues/71" rel="nofollow">here</a> and <a href="https://github.com/JamesPHoughton/pysd/issues/70" rel="nofollow">here</a>).</p>
| 0 | 2016-10-18T18:28:44Z | [
"python",
"vensim"
]
|
Understanding Parsing Error when reading model file into PySD | 39,794,851 | <p>I am receiving the following error message when I try to read a Vensim model file (.mdl) using Python's PySD package. </p>
<p>My code is:</p>
<pre><code>import pysd
import os
os.chdir('path/to/model_file')
model = pysd.read_vensim('my_model.mdl')
</code></pre>
<p>The Error I receive is:</p>
<pre><code>Traceback (most recent call last):
Python Shell, prompt 13, line 1
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pysd/pysd.py", line 53, in read_vensim
py_model_file = translate_vensim(mdl_file)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pysd/vensim2py.py", line 673, in translate_vensim
entry.update(get_equation_components(entry['eqn']))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pysd/vensim2py.py", line 251, in get_equation_components
tree = parser.parse(equation_str)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/parsimonious/grammar.py", line 123, in parse
return self.default_rule.parse(text, pos=pos)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/parsimonious/expressions.py", line 110, in parse
node = self.match(text, pos=pos)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/parsimonious/expressions.py", line 127, in match
raise error
parsimonious.exceptions.ParseError: Rule 'subscriptlist' didn't match at '' (line 1, column 21).
</code></pre>
<p>I have searched for this particular error and I cannot find much information on the failed matching rule for 'subscriptlist'. </p>
<p>I appreciate any insight. Thank you.</p>
| 0 | 2016-09-30T15:17:57Z | 40,134,671 | <p>If you aren't using subscripts, you may have found a bug in the parser. If so, best course is to create a report in the github <a href="https://github.com/JamesPHoughton/pysd/issues" rel="nofollow">issue tracker</a> for the project. The stack trace you posted says that the error is happening in the first line of the file, and that the error has to do with how the right hand side of the equation is being parsed. You might include the first few lines in your bug report to help me recreate the issue. I'll add a case to our growing <a href="https://github.com/SDXorg/test-models" rel="nofollow">test suite</a> and then we can make sure it isn't a problem going forwards.</p>
| 0 | 2016-10-19T14:43:24Z | [
"python",
"vensim"
]
|
OCR pytesseract, recognize the biggest word in an image | 39,794,876 | <p>I'm using <strong>pytesseract</strong> to recognize text from an image, is there anyway i can detect/recognize the biggest word in that image</p>
<p><a href="http://i.stack.imgur.com/7lgZs.jpg" rel="nofollow">Click here to display the image</a></p>
<p>In the image above, i'm trying to detect/recognize "Atacand Plus" which is the biggest words in the whole image in size. I tried to apply filters like sharppen, smooth, and Max filter and repeated them many times between 5-10 times depends on the picture, to remove the smaller words, but is there any other way to do it?</p>
<p>Thanks,
Reagards</p>
| 2 | 2016-09-30T15:19:28Z | 40,003,222 | <p>The issue here is that when you use the Tesseract segmentation it doesn't segment the image word by word, rather it does it by zones in the image, so paragraphs and blocks of words. So if you are trying to do this pre-recognition, then you are going to run into issues and errors. </p>
<p>Another option is to do post processing on the image and after recognition get the size of the characters and words and then filter out the ones that aren't the biggest words.</p>
<p>Tesseract OCR can return position information but it is not easy to get to. Here is some information on how to get the position information from Tesseract:</p>
<p><a href="http://stackoverflow.com/questions/20831612/getting-the-bounding-box-of-the-recognized-words-using-python-tesseract">Getting the bounding box of the recognized words using python-tesseract</a></p>
<p>Another option is to use a commercial library that makes this process easier. The <a href="https://www.leadtools.com/sdk/ocr" rel="nofollow">LEADTOOLS OCR Library</a> has an <a href="https://www.leadtools.com/help/leadtools/v19/dh/fo/leadtools.forms.ocr~leadtools.forms.ocr.ocrword.html" rel="nofollow">OcrWord struct</a> that you can use to get the location of the word and then compare it to the rest of the words. Disclaimer : I am an employee of this product.</p>
<p>I wrote a sample application using the .NET libraries from LEADTOOLS to show you how to achieve the functionality you are looking for:</p>
<pre><code>string filename = @"7lgZs.jpg";
using (RasterCodecs codecs = new RasterCodecs())
using (RasterImage image = codecs.Load(filename))
using (IOcrEngine ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.Advantage, false))
{
ocrEngine.Startup(null, null, null, null);
using (IOcrPage ocrPage = ocrEngine.CreatePage(image, OcrImageSharingMode.None))
{
ocrPage.Recognize(null);
string biggestWord = GetBiggestWord(ocrPage);
Console.WriteLine("The biggest word in this image is : {0}" , biggestWord);
Console.ReadLine();
}
}
static string GetBiggestWord(IOcrPage ocrPage)
{
IOcrPageCharacters ocrPageCharacters = ocrPage.GetRecognizedCharacters();
OcrWord biggestWord = new OcrWord();
biggestWord.Bounds = LogicalRectangle.Empty;
biggestWord.Value = "";
foreach (IOcrZoneCharacters ocrZoneCharacters in ocrPageCharacters)
{
ICollection<OcrWord> words = ocrZoneCharacters.GetWords(ocrPage.DpiX, ocrPage.DpiY, LogicalUnit.Pixel);
foreach (var word in words)
{
double area = word.Bounds.Width * word.Bounds.Height;
double biggestArea = biggestWord.Bounds.Width * biggestWord.Bounds.Height;
if (area > biggestArea)
biggestWord = word;
}
}
return biggestWord.Value;
}
</code></pre>
<p>and here is a screenshot of the console output:</p>
<p><a href="https://i.stack.imgur.com/OLGJ9.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/OLGJ9.jpg" alt="demo screenshot"></a></p>
<p>I know you mentioned you were wanting to use python in your question, but you can call C# libraries from python as can be seen from this link:</p>
<p><a href="http://stackoverflow.com/questions/7367976/calling-a-c-sharp-library-from-python">Calling a C# library from python</a></p>
| 2 | 2016-10-12T16:03:42Z | [
"python",
"image-processing",
"ocr"
]
|
print average percentage of a student from an array | 39,794,878 | <p>The program is supposed to calculate and print out a given student's average percentage.</p>
<p>Unfortunately I am only able to print out the average percentage of the last student name in the array.
I want to know where exacltly I am going wrong with my coding.
Thanks. Heres my code below.</p>
<pre><code>def averagepercentage():
scores = int(name_marks[1]),int(name_marks[2]),int(name_marks[3])
ap = sum(scores)/3
return ap
N = int(input('Number of students: ')) # total number of students
marks = int()
arr = []
for i in range(N):
name_marks = input('name & marks').split() #enter name & three different scores
name = str(name_marks[0])
arr.append(name)
print(arr)
student_name = str(input('student_name'))
for x in arr:
if student_name in x:
print (x)
print("%.2f" %averagepercentage())
</code></pre>
| 0 | 2016-09-30T15:19:29Z | 39,795,301 | <p>In your first loop:</p>
<pre><code>for i in range(N):
name_marks = input('name & marks').split() #enter name & three different scores
name = str(name_marks[0])
arr.append(name)
print(arr)
</code></pre>
<p>you don't store the marks of the previous students, you replace your variable <code>name_marks</code> by the last marks from your input</p>
<p>the <code>if student_name in x:</code> looks if <code>student_name</code> is included in <code>x</code>, which is not exactly what you want to do, consider doing <code>if student_name == x:</code> instead.</p>
<p>Then:</p>
<pre><code>def averagepercentage():
scores = int(name_marks[1]),int(name_marks[2]),int(name_marks[3])
ap = sum(scores)/3
return ap
</code></pre>
<p>looks at the global variable <code>name_marks</code> to compute the average, but this variables only contains the value of the last student (because of my first remark)</p>
<p>what you can do, to keep most of your code structure is:</p>
<pre><code>for i in range(N):
name_marks = input('name & marks').split() #enter name & three different scores
name = str(name_marks[0])
arr.append((name,averagepercentage()))
print(arr)
student_name = str(input('student_name'))
for x in arr:
if student_name in x:
print ("student :" + x[0])
print("average :" + x[1])
</code></pre>
| 0 | 2016-09-30T15:43:51Z | [
"python",
"arrays",
"python-3.x",
"iteration"
]
|
What to do when api returns html or json for different errors | 39,794,885 | <p>Using python requests to talk to the github api.</p>
<pre><code>response = requests.post('https://api.github.com/orgs/orgname/repos', auth, data)
</code></pre>
<p>If the request returns a 405 error I get HTML in the response.text</p>
<pre><code><html>
<head><title>405 Not Allowed</title></head>
<body bgcolor="white">
<center><h1>405 Not Allowed</h1></center>
</body>
</html>
</code></pre>
<p>If the request returns a 422 error I get JSON in the response.text</p>
<pre><code>{"message":"Validation Failed","errors": [{"resource":"Repository","code":"custom","field":"name","message":"name already exists on this account"}],"documentation_url":"https://developer.github.com/v3/repos/#create"}
</code></pre>
<p>Can I force the API to only return JSON?</p>
<p>If not, can I find out what type the response content will be?</p>
| 0 | 2016-09-30T15:19:55Z | 39,795,745 | <p>In response to:</p>
<blockquote>
<p>If not, can I find out what type the response content will be?</p>
</blockquote>
<p>If you want to know why github returns html rather than JSON for the API call, I can not answer that; however, to the answer to the above asked question, you can look at the "content" header of the http response.</p>
<pre><code>response = requests.post('https://api.github.com/orgs/orgname/repos', auth, data)
if "application/json" in response.headers['content-type']:
print response.json()
</code></pre>
<p>In response to:</p>
<blockquote>
<p>Can I force the API to only return JSON?
you could try forcing the "Accept header within the request; however, this is down to GitHub server if it wants to serve json in the response</p>
</blockquote>
<pre><code>response = requests.post('https://api.github.com/orgs/omnifone/repos', auth=auth, data=data, headers={"Accept": "application/json"})
</code></pre>
| 0 | 2016-09-30T16:08:37Z | [
"python",
"json",
"http",
"python-requests"
]
|
Better way to implement `df[m] = df[x] + df[y] + df[z]` | 39,794,937 | <p>I want to get the sum of three columns, the method I took is as follows:</p>
<pre><code>In [14]:
a_pd = pd.DataFrame({'a': np.arange(3),
'b': [5, 7, np.NAN],
'c': [2, 9, 0]})
a_pd
Out[14]:
a b c
0 0 5.0 2
1 1 7.0 9
2 2 NaN 0
In [18]:
b_pd = a_pd['a'] + a_pd['b'] + a_pd['c']
b_pd
Out[18]:
0 7.0
1 17.0
2 NaN
dtype: float64
</code></pre>
<p>But as you can see, NaN can not be excluded.
so I tried <code>np.add()</code>,but something wrong:</p>
<pre><code>In [19]:
b_pd = a_pd[['a', 'b', 'c']].apply(np.add, axis=1)
b_pd
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-19-f52f400573b4> in <module>()
----> 1 b_pd = a_pd[['a', 'b', 'c']].apply(np.add, axis=1)
2 b_pd
F:\anaconda\lib\site-packages\pandas\core\frame.pyc in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
4045
4046 if isinstance(f, np.ufunc):
-> 4047 results = f(self.values)
4048 return self._constructor(data=results, index=self.index,
4049 columns=self.columns, copy=False)
ValueError: invalid number of arguments
</code></pre>
<p>So, I want to know how you fix this bug.</p>
| 2 | 2016-09-30T15:22:21Z | 39,794,989 | <p>You can use the sum method of the DataFrame:</p>
<pre><code>a_pd.sum(axis=1)
Out:
0 7.0
1 17.0
2 2.0
dtype: float64
</code></pre>
<p>If you want to specify columns:</p>
<pre><code>a_pd[['a', 'b', 'c']].sum(axis=1)
Out:
0 7.0
1 17.0
2 2.0
dtype: float64
</code></pre>
| 5 | 2016-09-30T15:25:28Z | [
"python",
"pandas",
"apply",
null
]
|
Better way to implement `df[m] = df[x] + df[y] + df[z]` | 39,794,937 | <p>I want to get the sum of three columns, the method I took is as follows:</p>
<pre><code>In [14]:
a_pd = pd.DataFrame({'a': np.arange(3),
'b': [5, 7, np.NAN],
'c': [2, 9, 0]})
a_pd
Out[14]:
a b c
0 0 5.0 2
1 1 7.0 9
2 2 NaN 0
In [18]:
b_pd = a_pd['a'] + a_pd['b'] + a_pd['c']
b_pd
Out[18]:
0 7.0
1 17.0
2 NaN
dtype: float64
</code></pre>
<p>But as you can see, NaN can not be excluded.
so I tried <code>np.add()</code>,but something wrong:</p>
<pre><code>In [19]:
b_pd = a_pd[['a', 'b', 'c']].apply(np.add, axis=1)
b_pd
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-19-f52f400573b4> in <module>()
----> 1 b_pd = a_pd[['a', 'b', 'c']].apply(np.add, axis=1)
2 b_pd
F:\anaconda\lib\site-packages\pandas\core\frame.pyc in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
4045
4046 if isinstance(f, np.ufunc):
-> 4047 results = f(self.values)
4048 return self._constructor(data=results, index=self.index,
4049 columns=self.columns, copy=False)
ValueError: invalid number of arguments
</code></pre>
<p>So, I want to know how you fix this bug.</p>
| 2 | 2016-09-30T15:22:21Z | 39,795,083 | <p>np.add requires inputs</p>
<pre><code>b_pd = a_pd[['a', 'b', 'c']].apply(np.sum, axis=1)
</code></pre>
| 2 | 2016-09-30T15:31:20Z | [
"python",
"pandas",
"apply",
null
]
|
Python Flask Split Text in Form by comma | 39,795,018 | <p>I'm writing a function in Flask that takes a list of IDs and sends a request to Amazon for data on those IDs. I'm running into an issue where the contents of the form are not splitting the way I want it to. I'd like it to be split by a comma or whitespace so that each ID is sent to the request, but instead it's sending a request for each individual character in the form. </p>
<p>As an example, I would put IDs in the form as 'id-12345, id-24689' and it would send a request for those ids. Rather, it is sending a request for 'i', 'd',' '-', etc... Here's the code for the form request:</p>
<pre><code>if request.method == 'POST':
IDlist = []
ids = request.form['ids']
f_n = request.form['f_n']
for i in ids:
i.split(',')
IDlist.append(i)
</code></pre>
| 0 | 2016-09-30T15:27:05Z | 39,795,602 | <p>You have a for loop that you don't need. Instead the following would work</p>
<pre><code>if request.method == 'POST':
ids = request.form['ids']
f_n = request.form['f_n']
IDlist = ids.split(',')
</code></pre>
<p>What you are doing is you are looping through each individual character, splitting each character e.g. "i" by a comma (which returns the item ["i"]), and then appending that to the list. What you are therefore getting is the following list</p>
<pre><code>[['i'], ['d'], etc...
</code></pre>
<p>Hope that is helpful. This might be helpful - <a href="http://stackoverflow.com/questions/4071396/split-by-comma-and-strip-whitespace-in-python?rq=1">Split by comma and strip whitespace in Python</a></p>
| 1 | 2016-09-30T15:59:27Z | [
"python",
"forms",
"flask"
]
|
Filtering out stopwords | 39,795,061 | <p>I've created a simple word count program and I'm trying to filter out commonly used words from my list using nltk (see below).</p>
<p>My question is how would I apply my "stop" filter to my "frequency" list?</p>
<pre><code>#Start
from nltk.corpus import stopwords
import re
import string
frequency = {}
document_text = open('Import.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)
for word in match_pattern:
count = frequency.get(word,0)
frequency[word] = count + 1
frequency = {k:v for k,v in frequency.items() if v>1}
stop = set(stopwords.words('english'))
stop = list(stop)
stop.append(".")
import csv
with open('Export.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
for key, value in frequency.items():
writer.writerow([key, value])
</code></pre>
| 0 | 2016-09-30T15:29:59Z | 39,795,146 | <pre><code>stop = set(stopwords.words('english'))
stop.(".")
frequency = {k:v for k,v in frequency.items() if v>1 and k not in stop}
</code></pre>
<p>While <code>stop</code> is still a <code>set</code>, check the keys of your <code>frequency</code> dictionary when doing the comprehension. You can still make stop a list again afterwards. </p>
<p>The reason I keep it as a set is because it is much more efficient to search sets than it is to search lists.</p>
| 1 | 2016-09-30T15:34:45Z | [
"python",
"nltk",
"stop-words"
]
|
Finding width of peaks | 39,795,062 | <p>I have a data set on which I'm trying to detect peaks and the left/right bounds of those peaks.</p>
<p>I'm successfully using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks_cwt.html" rel="nofollow">scipy <code>find_peaks_cwt</code></a> to find the peaks, but I don't know how to then identify the left and right bounds of those peaks.</p>
<p>In the below graph, the line and circle markers on the peaks are being drawn programmatically, but the square markers were drawn by hand are what I'm now trying to do programmatically.</p>
<p><a href="http://i.stack.imgur.com/U1yg6.png" rel="nofollow"><img src="http://i.stack.imgur.com/U1yg6.png" alt="enter image description here"></a></p>
<p>Any advice on how to do this? I considered searching for inflection points, but that won't work because of the noise in the data.</p>
| 2 | 2016-09-30T15:30:07Z | 39,797,156 | <p>If a Gaussian fit would be appropriate, you could take the number of peaks you have found and fit n Gaussian distributions (1 for each peak) plus a constant variable for the background noise (or you could add another Gaussian to the curve fit</p>
<pre class="lang-python prettyprint-override"><code>import numpy as np
from scipy.optimize import curve_fit
from scipy.signal import find_peaks_cwt
from math import *
peak_indices = find_peaks_cwt(data, *args)
#make a fitting function that takes x number of peak widths
def makeFunction(indices, data):
def fitFunction(x, *args):
#sum of gaussian functions with centers at peak_indices and heights at data[peak_indices] plus a constant for background noise (args[-1])
return sum([data[indices[i]]*exp(-((x-indices[i])**2)/(2*args[i]**2)) for i in range(len(peak_indices))])+args[-1] #does my code golfing show? xD
return fitFunction
f = makeFunction(peak_indices, data)
#you must provide the initial guess of "np.ones(len(peak_indices)+1)" for the parameters, because f(x, *args) will otherwise take a variable number of arguments.
popt, pcov = curve_fit(f, np.arange(len(data)), data, np.ones(len(peak_indices)+1))
#standard deviations (widths) of each gaussian peak and the average of the background noise
stdevs, background = popt[:-1], popt[-1]
#covariance of result variables
stdevcov, bgcov = pcov[:-1], pcov[-1]
</code></pre>
<p>This should give you a place to start, but you'll likely have to tweak the optimization function to work with your data (or maybe work at all, I didn't test)</p>
| 1 | 2016-09-30T17:41:49Z | [
"python",
"numpy",
"scipy"
]
|
Max heap throwing index out of bounds | 39,795,082 | <p>Below is my max heap implementation. I can really figure out why I am getting the index out of bounds error. I have assigned array to self.heap</p>
<pre><code>class heap:
def __init__(self):
self.heapsize=0
self.heap=[0]
def builheap(self,list):
self.heapsize = len(list)
self.heap=list
for i in range(len(list)//2, 0, -1):
self.maxheap(self.heap,i)
def maxheap(self, list, index):
if list[2*index]<=self.heapsize and list[2*index]>list[index]:
largest=list[2*index]
else:
largest=index
if list[2*index+1]<= self.heapsize and list[2*index+1]>list[index]:
largest=list[2*index+1]
if largest!=index:
tmp = list[index]
list[index] = list[largest]
list[largest] = tmp
maxheap(list,largest)
h=heap()
h.builheap([16,14,10,8,7,9,3,2,4,1])
</code></pre>
<p>Error:</p>
<pre><code>Traceback (most recent call last):
File "heap.py", line 24, in <module>
h.builheap([16,14,10,8,7,9,3,2,4,1])
File "heap.py", line 9, in builheap
self.maxheap(self.heap,i)
File "heap.py", line 11, in maxheap
if list[2*index]<=self.heapsize and list[2*index]>list[index]:
IndexError: list index out of range
</code></pre>
| 0 | 2016-09-30T15:31:19Z | 39,796,197 | <p>You have this code:</p>
<pre><code> if list[2*index]<=self.heapsize and list[2*index]>list[index]:
largest=list[2*index]
else:
largest=index
if list[2*index+1]<= self.heapsize and list[2*index+1]>list[index]:
</code></pre>
<p>You're trying to index into the list before checking to see if the index is beyond the list's bounds. Besides, you want to check the index to see if it's within bounds, rather than checking that the contents at that index is within bounds.</p>
<p>It should be:</p>
<pre><code> if 2*index<=self.heapsize and list[2*index]>list[index]:
largest=list[2*index]
else:
largest=index
if 2*index+1<= self.heapsize and list[2*index+1]>list[index]:
</code></pre>
<p>It's unclear to me whether your root is at 0 or 1.</p>
<p>If the root node is at <code>list[0]</code>, then your calculations should be <code>(2*index) + 1</code> and <code>(2*index)+2</code>. The calculations you have assume that the root is at <code>list[1]</code>. </p>
| 1 | 2016-09-30T16:36:09Z | [
"python",
"algorithm",
"tree",
"heap",
"binary-heap"
]
|
How to put these outputs into 9 by 9 array using Numpy array | 39,795,138 | <p>sorry if this is a basic question. I am just starting with python and programming.</p>
<p>I want the output from iteration in a 9 by 9 array. For now I just get the output in one column.</p>
<pre><code>for q in range(11,20,1):
for x in range(11,20,1):
if q <= x:
V = 3.5*q â 1.5 * x
elif q > x:
V = 3.5*x â 1.5*x
print(V)
</code></pre>
<p>Try doing this but I get error: <strong>IndexError: index 11 is out of bounds for axis 0 with size 9</strong></p>
<pre><code>import numpy as np
V = np.zeros((9,9))
for q in range(11,20,):
for x in range(11,20):
if q <= x:
V[q][x] = 3.5*q - 1.5*x
elif q > x:
V[q][x] = 3.5*x - 1.5*x
print(V)
</code></pre>
<p>Thank you for your help.</p>
| 0 | 2016-09-30T15:34:24Z | 39,795,514 | <p>Your problem is exactly what the error says: you are trying to access index 11 in a an array of size 9 (by 9).</p>
<p><code>for q in range(11,20):</code> is iterating over <code>q = 11, 12, 13,..., 19</code>.
Then <code>V[q][x]</code> is trying to access element with indexes <code>q</code> and <code>x</code> in <code>V</code>. But <code>V</code> is of size 9x9 which means the only elements you can access are <code>[0,0], [0,1], ..., [0,8], [1,0], ..., [8,8]</code> hence the error: you are trying to acess an element that doesn't exist.</p>
| 1 | 2016-09-30T15:55:34Z | [
"python",
"arrays",
"numpy",
"multidimensional-array"
]
|
Regex to match repeated set of characters | 39,795,262 | <p>I'd like to be able to extract the following patterns from free text.</p>
<pre><code>VBAV/123456.01
VBAV/132453.02
VSAV/132452.01.03
VMAV/142143.01.02
</code></pre>
<p>Currently I am trying as below but not much success</p>
<pre><code>df["Project Id"] = df["WBS element"].str.cat(
df["Network VxAV"]).str.cat(
df["Text"]).str.cat(
df["Assignment"]).str.cat(
df["Reference"]).str.extract(
"(V[BSM]AV\/[\d]{6}[.0-30-3]{0,2})", expand=True)
</code></pre>
<p>The challenging part for me was to extract the patterns of repeated .01 or .02 or .03 at the end. This part can repeat between 0 to 2 times, hence my attempt with {0,2} with the regex.</p>
<p>What would be the right regex for this? </p>
| 2 | 2016-09-30T15:41:42Z | 39,795,337 | <p>Why not:</p>
<pre><code>V[BSM]AV/[\d.]+
</code></pre>
<p>See <a href="https://regex101.com/r/zHX8gH/1" rel="nofollow"><strong>a demo on regex101.com</strong></a>.</p>
| 0 | 2016-09-30T15:45:51Z | [
"python",
"regex",
"pandas"
]
|
Regex to match repeated set of characters | 39,795,262 | <p>I'd like to be able to extract the following patterns from free text.</p>
<pre><code>VBAV/123456.01
VBAV/132453.02
VSAV/132452.01.03
VMAV/142143.01.02
</code></pre>
<p>Currently I am trying as below but not much success</p>
<pre><code>df["Project Id"] = df["WBS element"].str.cat(
df["Network VxAV"]).str.cat(
df["Text"]).str.cat(
df["Assignment"]).str.cat(
df["Reference"]).str.extract(
"(V[BSM]AV\/[\d]{6}[.0-30-3]{0,2})", expand=True)
</code></pre>
<p>The challenging part for me was to extract the patterns of repeated .01 or .02 or .03 at the end. This part can repeat between 0 to 2 times, hence my attempt with {0,2} with the regex.</p>
<p>What would be the right regex for this? </p>
| 2 | 2016-09-30T15:41:42Z | 39,796,413 | <pre><code>r'V[BSM]AV/\d{6}(?:\.\d\d){0,2}(?!\d)'
</code></pre>
<p>Matches exactly 6 digits, and 0-2 instances of <code>.##</code>. <code>(?:xxxx)</code> is a non-capturing group. Cannot be followed by another digit, so it won't match:</p>
<pre><code>VBAV\1234567
VBAV\122346.123
</code></pre>
<p>You may need to adjust what can't follow the match.</p>
| 0 | 2016-09-30T16:52:05Z | [
"python",
"regex",
"pandas"
]
|
Regex to match repeated set of characters | 39,795,262 | <p>I'd like to be able to extract the following patterns from free text.</p>
<pre><code>VBAV/123456.01
VBAV/132453.02
VSAV/132452.01.03
VMAV/142143.01.02
</code></pre>
<p>Currently I am trying as below but not much success</p>
<pre><code>df["Project Id"] = df["WBS element"].str.cat(
df["Network VxAV"]).str.cat(
df["Text"]).str.cat(
df["Assignment"]).str.cat(
df["Reference"]).str.extract(
"(V[BSM]AV\/[\d]{6}[.0-30-3]{0,2})", expand=True)
</code></pre>
<p>The challenging part for me was to extract the patterns of repeated .01 or .02 or .03 at the end. This part can repeat between 0 to 2 times, hence my attempt with {0,2} with the regex.</p>
<p>What would be the right regex for this? </p>
| 2 | 2016-09-30T15:41:42Z | 39,796,677 | <p>consider the the <code>pd.Series</code> <code>s</code></p>
<pre><code>s = pd.concat([pd.Series(txt.split('\n')) for _ in range(3)], ignore_index=True)
</code></pre>
<p><strong><em>Option 1</em></strong><br>
my preference</p>
<pre><code>s.str.split('/', expand=True)
</code></pre>
<p><a href="http://i.stack.imgur.com/B8ejM.png" rel="nofollow"><img src="http://i.stack.imgur.com/B8ejM.png" alt="enter image description here"></a></p>
<p><strong><em>Option 2</em></strong><br>
Also Nice</p>
<pre><code>s.str.extract(r'(?P<first>\w+)/(?P<second>.*)', expand=True)
</code></pre>
<p><a href="http://i.stack.imgur.com/MFCJm.png" rel="nofollow"><img src="http://i.stack.imgur.com/MFCJm.png" alt="enter image description here"></a></p>
<p><strong><em>Option 3</em></strong><br>
Very Explicit</p>
<pre><code>cols = ['first', 'second']
s.str.extract(r'(?P<first>V[BSM]AV)/(?P<second>\d{6}(.\d{2})+)', expand=True)[cols]
</code></pre>
<p><a href="http://i.stack.imgur.com/MFCJm.png" rel="nofollow"><img src="http://i.stack.imgur.com/MFCJm.png" alt="enter image description here"></a></p>
| 1 | 2016-09-30T17:11:10Z | [
"python",
"regex",
"pandas"
]
|
Numpy array trims string values | 39,795,280 | <p>Here is the code I am trying to execute</p>
<pre><code>matrix = []
sample = [10,10,'mike','']
for i in range(10):
r = [sample] * 3
matrix.append(r)
matrix = np.array(matrix)
matrix[1][1] = [123,123,'james', 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
print matrix[1][1]
</code></pre>
<p>and here is what I am getting</p>
<pre><code>['123' '123' 'james' 'sdfsdfsdf w']
</code></pre>
<p>so basically the text is trimmed for some reason. Has anyone seen it before?</p>
| 2 | 2016-09-30T15:42:37Z | 39,795,516 | <p>I found the problem.</p>
<p>conversion from native Python array to Numpy should take place as the last step.</p>
<pre><code>matrix[1][1] = [123,123,'james', 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
matrix = np.array(matrix)
</code></pre>
<p>Now works fine.</p>
| 0 | 2016-09-30T15:55:44Z | [
"python",
"numpy"
]
|
Numpy array trims string values | 39,795,280 | <p>Here is the code I am trying to execute</p>
<pre><code>matrix = []
sample = [10,10,'mike','']
for i in range(10):
r = [sample] * 3
matrix.append(r)
matrix = np.array(matrix)
matrix[1][1] = [123,123,'james', 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
print matrix[1][1]
</code></pre>
<p>and here is what I am getting</p>
<pre><code>['123' '123' 'james' 'sdfsdfsdf w']
</code></pre>
<p>so basically the text is trimmed for some reason. Has anyone seen it before?</p>
| 2 | 2016-09-30T15:42:37Z | 39,795,556 | <p>If you do not specify the <code>dtype</code> when you are converting your list to an array, it will use default behavior. In your case, you are mixing int's and strings, so it will default to unicode <11:</p>
<pre><code>>>> np.array([1,2,'a'])
array(['1', '2', 'a'],
dtype='<U11')
</code></pre>
<p>When you try to add a new element with a length more than 11, it will truncate to the dtype:</p>
<pre><code>>>> x = np.array([1,2,'a'])
>>> x[2] = 'abcdefghijklmnopqrstuvwxyz'
>>> x
array(['1', '2', 'abcdefghijk'],
dtype='<U11')
</code></pre>
<p>You can resolve this by specifying a higher <code>dtype</code> when you create the array:</p>
<pre><code>>>> x = np.array([1,2,'a'], '<U50')
>>> x[2] = 'abcdefhijkmnopqrstuvwxyz'
>>> x
array(['1', '2', 'abcdefhijkmnopqrstuvwxyz'],
dtype='<U50')
</code></pre>
| 0 | 2016-09-30T15:57:13Z | [
"python",
"numpy"
]
|
Numpy array trims string values | 39,795,280 | <p>Here is the code I am trying to execute</p>
<pre><code>matrix = []
sample = [10,10,'mike','']
for i in range(10):
r = [sample] * 3
matrix.append(r)
matrix = np.array(matrix)
matrix[1][1] = [123,123,'james', 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
print matrix[1][1]
</code></pre>
<p>and here is what I am getting</p>
<pre><code>['123' '123' 'james' 'sdfsdfsdf w']
</code></pre>
<p>so basically the text is trimmed for some reason. Has anyone seen it before?</p>
| 2 | 2016-09-30T15:42:37Z | 39,795,656 | <p>Your solution:</p>
<pre><code>matrix[1][1] = [123,123,'james', 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
matrix = np.array(matrix)
</code></pre>
<p>works only because if you do not specify the data type in the array method, numpy set's it to the smallest size possible to hold all data.</p>
<p>If from an interactice python terminal you typed <code>matrix[1][1]</code> you would have gotten:</p>
<pre><code>array(['123', '123', 'james', 'sdfsdfsdf werwerwer s'], dtype='|S21')
</code></pre>
<p>The dtype indicates that it's a string of length 21 characters. Which is why your text get's truncated. When you implement your array structure, you should provide the dtype if you at some point later want to increase the size of the data.</p>
<pre><code>matrix = np.array(matrix, dtype='S50')
matrix[1][1] = [123,123,'james', 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
print matrix[1][1]
['123' '123' 'james' 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
</code></pre>
| 0 | 2016-09-30T16:02:39Z | [
"python",
"numpy"
]
|
Using "self" in function arguments definition | 39,795,312 | <p>Instead of doing the following:</p>
<pre><code>def MyFunc(self, a, b, c)
self.a = a
self.b = b
self.c = c
</code></pre>
<p>I want to do the following:</p>
<pre><code>def MyFunc(self, self.a, self.b, self.c)
</code></pre>
<p>Why does this not work?</p>
<p>If I have to use the first approach, is there any good way to make sure I don't unintentionally overwrite variables used elsewhere in the project with the same names (e.g. perhaps "a" is a variable used by another object).</p>
| -1 | 2016-09-30T15:44:32Z | 39,795,846 | <p>Maybe the problem is related to this behaviour, which might be supprising for new pythoneers:</p>
<pre><code>class Cl():
def MyFunction(self, a):
self.a = a
a= {"w":"old"}
myCl = Cl()
myCl.MyFunction(a)
print a, myCl.a
a.update({"w":"new"})
print a, myCl.a
</code></pre>
<p>which outputs</p>
<pre><code>{'w': 'old'} {'w': 'old'}
{'w': 'new'} {'w': 'new'}
</code></pre>
| -3 | 2016-09-30T16:15:19Z | [
"python"
]
|
Using "self" in function arguments definition | 39,795,312 | <p>Instead of doing the following:</p>
<pre><code>def MyFunc(self, a, b, c)
self.a = a
self.b = b
self.c = c
</code></pre>
<p>I want to do the following:</p>
<pre><code>def MyFunc(self, self.a, self.b, self.c)
</code></pre>
<p>Why does this not work?</p>
<p>If I have to use the first approach, is there any good way to make sure I don't unintentionally overwrite variables used elsewhere in the project with the same names (e.g. perhaps "a" is a variable used by another object).</p>
| -1 | 2016-09-30T15:44:32Z | 39,799,261 | <p>I'm really not sure why you want to do something such as what you describe. It doesn't really make sense that parameters of a function are class attributes.</p>
<p>Now, if what your asking is how to stop the parameters <code>MyFunc()</code> from conflicting with the parameters of another function, then your covered. As was pointed out in the comments, Python has proper scope. So the parameters of <code>MyFunc()</code> will not conflict with any other variables/parameters.</p>
| 0 | 2016-09-30T20:01:32Z | [
"python"
]
|
Using SRV DNS records with the python requests library | 39,795,400 | <p>Is it possible to have the Python requests library resolve a consul domain name with a SRV record and utilize the correct IP address and port when making the request?</p>
<p>For example, given that I have serviceA running with the IP address 172.18.0.5 on port 8080 and this service is registered with consul. And given that DNS for the host is set to use consul to resolve queries. Can I make a request like:</p>
<pre><code>requests.get('http://serviceA.service.consul')
</code></pre>
<p>and have it be equivalent to the request:</p>
<pre><code>requests.get('http://172.18.0.5:8080')
</code></pre>
| 0 | 2016-09-30T15:49:43Z | 39,803,800 | <p>No, you can't unless you rewrite <code>requests</code>.</p>
<p>SRV record is design to find a service.<br>
In this case, you already indicate to use http. So client will only query A or AAAA record for <code>serviceA.service.consul</code>.</p>
| 0 | 2016-10-01T06:46:48Z | [
"python",
"dns",
"python-requests",
"consul"
]
|
Trying to automate a python script.....Using Windows scheduler | 39,795,451 | <p>So I have the following script which I am using to grab data from the net and save it as an html file in a folder on my pc (same pc) each time I run the script. I'm now trying to automate the process.</p>
<pre><code>import pandas as pd
import datetime as dt
today_date = dt.date.today().isoformat()
df = pd.read_html('http://www.livevol.com/largest-option-trades-on-the-day', header=1)[0].set_index('Time')
html_name = 'option data/{}.html'.format(today_date)
df.to_html(html_name)
</code></pre>
<p>Ordinarily, when I click on the .py, I get a the black screen (command prompt) which lasts for a few seconds and then If I go to a certain folder, I see that a new html has been created.</p>
<p>However, when I use Windows scheduler, the script seems to run but an html file is not being created. </p>
<p>The script seems to be running because the command prompt black screen pops up and stays there for <em>a few seconds</em> (rather than just flashing), just like it did when I manually clicked on the .py file. </p>
<p>I've played around with the different parameters of the "actions" field of Windows Scheduler.</p>
<p>Program/script: C:\Python27\python.exe
Add arguments: C:\Python27\Option.py</p>
<p>"Run when user is logged on" and "highest privileges" are check-marked.</p>
<p>Not sure what I'm doing wrong.
Thanks. </p>
| 0 | 2016-09-30T15:52:04Z | 39,802,210 | <p>I got it working by filling in the "Start in(optional)" parameter under the Actions tab, with the first part of the path to the Python exe. </p>
<p>"C:\Python27"</p>
| 0 | 2016-10-01T01:41:40Z | [
"python",
"windows",
"scheduler"
]
|
Detect if key is down mac python | 39,795,518 | <p>I've googled all over the place.</p>
<p>I have a python application and I'd like to detect if a key is down (on OSX).</p>
<p>The only answers I've been able to find are either libraries for windows, or libraries that require an application window to be active (like pygame).</p>
<p>Similar to how pymouse has a position() method.</p>
<p>I'd like to be able to do something in my code like:</p>
<pre><code>if keyboard.keydown(<key code>):
# do something
elif keyboard.keycode(<some other keycode>):
# do something
</code></pre>
<p>On Mac.</p>
| 0 | 2016-09-30T15:55:47Z | 39,795,982 | <p>The only way I could think of is <a href="https://docs.python.org/2/library/tty.html" rel="nofollow">tty</a> or <a href="https://docs.python.org/2/library/termios.html#module-termios" rel="nofollow">termios</a>.</p>
<p>Here is a minimal example that waits for user input and prints the keycode if 'a' pressed ...</p>
<pre><code> #!/usr/bin/env python
import sys,tty
tty.setcbreak(sys.stdin)
key = ord(sys.stdin.read(1)) # key captures the key-code
# based on the input we do something - in this case print something
if key==97:
print "you pressed a"
else:
print "you pressed something else ..."
sys.exit(0)
</code></pre>
<p>Hope it helps!</p>
<p><strong>Note:</strong> This solution refers to linux/mac operating systems specifically - for windows there are other ways!</p>
| 0 | 2016-09-30T16:23:31Z | [
"python",
"osx",
"python-2.7"
]
|
Detect if key is down mac python | 39,795,518 | <p>I've googled all over the place.</p>
<p>I have a python application and I'd like to detect if a key is down (on OSX).</p>
<p>The only answers I've been able to find are either libraries for windows, or libraries that require an application window to be active (like pygame).</p>
<p>Similar to how pymouse has a position() method.</p>
<p>I'd like to be able to do something in my code like:</p>
<pre><code>if keyboard.keydown(<key code>):
# do something
elif keyboard.keycode(<some other keycode>):
# do something
</code></pre>
<p>On Mac.</p>
| 0 | 2016-09-30T15:55:47Z | 39,801,622 | <p>Python comex with tkinter, a gui framework that includes cross-platform key press and release handling. The gui part can be suppressed if one only wants the event handling. This works as expected on my Windows machine. It should work on your Mac.</p>
<pre><code>from time import sleep
import tkinter as tk
root = tk.Tk()
root.withdraw() # Do not show root window.
spacedown = False
def press_s(dummy):
global spacedown
spacedown = True
print('down')
def release_s(dummy):
global spacedown
spacedown = False
print('up')
root.bind('<KeyPress- >', press_s)
root.bind('<KeyRelease- >', release_s)
while True:
sleep(1)
root.update()
print('tick', 'down' if spacedown else 'up')
</code></pre>
<p>In the bind statements, replace the space <code></code> after the <code>-</code> with the key (such as <code>a</code> or <code>*</code>) or a <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/key-names.html" rel="nofollow">keyname</a>. Whenever you want to detect the current state of the key, call root.update to process queued events and set keydown.</p>
| 0 | 2016-09-30T23:59:54Z | [
"python",
"osx",
"python-2.7"
]
|
adding score when clicking inside rectangle | 39,795,640 | <p>I have the following exercise to do for school:</p>
<p>Create a textfield which shows a score as follows "Score: " (You can use the text(StringValue, IntegerXposition, IntegerYposition) for the drawing of text), starting at zero.
Make it so that when the user clicks the left mouseButton a score of 10 is added to the result.</p>
<p>Create a rectangle on screen and make it so that when the user clicks inside the rectangle, a score of 20 is added to the score value.</p>
<p>I have done the first part but don't know how to add a score of 20 when clicking inside the rectangle. This is the code i have so far.</p>
<pre><code>def setup():
global Score, xPos, yPos
size(800,800)
textSize(30)
Score= 0
xPos= 200
yPos= 200
def draw():
global Score, xPos, yPos
background(51)
rect(xPos,yPos,100,100)
text("Score: ", 50, 50)
text(Score, 150, 50)
def mousePressed():
global Score, xPos, yPos
if (mouseButton == LEFT):
Score= Score + 10
</code></pre>
| 0 | 2016-09-30T16:01:29Z | 39,802,030 | <p>I'm not quiet sure if this is possible with just <code>Python/Python 3.5.1</code> alone. I think <code>tkinter</code> is more suitable with making shapes with Python (And I'm not quiet sure because, I never used it before). I would suggest you use a <code>class</code> initialization for this. Here is what I got:</p>
<pre><code>class shapesYo:
def __init__(self, xPos, yPos):
self.xPos = xPos
self.yPos = yPos
self.size = (800, 800)
def displayPos(self):
print("The x Position is {0} and the y Position is {1}.".format(self.xPos, self.yPos))
def displayScore(self):
self.Score = 0
print("Score: {0}".format(self.Score))
rect = shapesYo(100, 100)
text = shapesYo(50, 50)
rect.displayPos()
text.displayPos()
text.displayScore()
</code></pre>
<p>This may not help out with the actual events happening (or that you want to happen) in the code but, it is a better was (in my opinion) to setup a set of code like this.</p>
| 0 | 2016-10-01T01:07:48Z | [
"python",
"python-3.x"
]
|
adding score when clicking inside rectangle | 39,795,640 | <p>I have the following exercise to do for school:</p>
<p>Create a textfield which shows a score as follows "Score: " (You can use the text(StringValue, IntegerXposition, IntegerYposition) for the drawing of text), starting at zero.
Make it so that when the user clicks the left mouseButton a score of 10 is added to the result.</p>
<p>Create a rectangle on screen and make it so that when the user clicks inside the rectangle, a score of 20 is added to the score value.</p>
<p>I have done the first part but don't know how to add a score of 20 when clicking inside the rectangle. This is the code i have so far.</p>
<pre><code>def setup():
global Score, xPos, yPos
size(800,800)
textSize(30)
Score= 0
xPos= 200
yPos= 200
def draw():
global Score, xPos, yPos
background(51)
rect(xPos,yPos,100,100)
text("Score: ", 50, 50)
text(Score, 150, 50)
def mousePressed():
global Score, xPos, yPos
if (mouseButton == LEFT):
Score= Score + 10
</code></pre>
| 0 | 2016-09-30T16:01:29Z | 39,802,060 | <p>Just check the position of the mouse pointer when there is a click.</p>
<p>I don't know what library you are using, but just replace <code>mouseX</code> and <code>mouseY</code> with the actual variable names.</p>
<pre><code>def mousePressed():
global Score, xPos, yPos
if mouseButton == LEFT and xPos < mouseX < xPos+100 and yPos < mouseY < yPos+100:
Score= Score + 10
</code></pre>
| 0 | 2016-10-01T01:13:31Z | [
"python",
"python-3.x"
]
|
Python beginner - Sorting tuples using lambda functions | 39,795,734 | <p>I'm going through the tutorial intro for Python and I'm stuck on understanding a piece of code. This is from section 4.7.5 of the tutorial.</p>
<pre><code>pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs
</code></pre>
<p>This bit of code returns </p>
<pre><code>[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
</code></pre>
<p>So in line one, it defines pairs with a list of different tuples. I get that.
Line two is where I'm completely thrown off and I've done quite a bit of messing around with it to try to understand what's happening.</p>
<p>I've found that sort() is applying a built-in function to the variable pairs, and presumably it is sorting it per the instructions I'm giving it.</p>
<p>The sort() function requires a key, and key has to be defined using a function, hence the use of lambda. I think all of this is correct, but I may be way off here.</p>
<p>Lambda defines a new parameter, "pair" on the left side of the colon, and on the right side is the calculation to define the return value of the lambda function.</p>
<p>That's where I'm thrown off. What does "pair[1]" do? What is its affect on the "pair" on the left side of the colon? </p>
<p>What value does it return? I can't seem to get it to return any sort of value outside of coding it just like this.</p>
<p>I'm guessing that it somehow points to a specific tuple and sorts it based on repositioning that, but I'm not sure of the logic behind that. </p>
<p>Can anyone explain this for me? Thank you.</p>
| 0 | 2016-09-30T16:07:46Z | 39,795,817 | <p>your lambda function takes an tuple as input and return the element with index 1 (so the second element since the first would have 0 for index).
so the sorting will only take into consideration the second element of each tuple (the English word). That's why your output is sorted alphabetically in the second element <code>'four'>'one'>'three'>'two'</code></p>
| 0 | 2016-09-30T16:13:45Z | [
"python",
"sorting",
"lambda"
]
|
Python beginner - Sorting tuples using lambda functions | 39,795,734 | <p>I'm going through the tutorial intro for Python and I'm stuck on understanding a piece of code. This is from section 4.7.5 of the tutorial.</p>
<pre><code>pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs
</code></pre>
<p>This bit of code returns </p>
<pre><code>[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
</code></pre>
<p>So in line one, it defines pairs with a list of different tuples. I get that.
Line two is where I'm completely thrown off and I've done quite a bit of messing around with it to try to understand what's happening.</p>
<p>I've found that sort() is applying a built-in function to the variable pairs, and presumably it is sorting it per the instructions I'm giving it.</p>
<p>The sort() function requires a key, and key has to be defined using a function, hence the use of lambda. I think all of this is correct, but I may be way off here.</p>
<p>Lambda defines a new parameter, "pair" on the left side of the colon, and on the right side is the calculation to define the return value of the lambda function.</p>
<p>That's where I'm thrown off. What does "pair[1]" do? What is its affect on the "pair" on the left side of the colon? </p>
<p>What value does it return? I can't seem to get it to return any sort of value outside of coding it just like this.</p>
<p>I'm guessing that it somehow points to a specific tuple and sorts it based on repositioning that, but I'm not sure of the logic behind that. </p>
<p>Can anyone explain this for me? Thank you.</p>
| 0 | 2016-09-30T16:07:46Z | 39,795,832 | <p>A <code>lambda</code> is a simplified function, using only an expression.</p>
<p>Any lambda can be written as a function, by adding in a <code>return</code> before the expression, so <code>lambda pair: pair[1]</code> becomes:</p>
<pre><code>def lambda_function(pair): return pair[1]
</code></pre>
<p>So the lambda in the <code>list.sort()</code> call here returns the <em>second</em> element of each sequence that is passed in (Python indexes start at <code>0</code>).</p>
<p>You can make this visible by assigning the lambda to a variable, say, <code>key</code>:</p>
<pre><code>>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> key = lambda pair: pair[1]
>>> key(pairs[0])
'one'
>>> key(pairs[1])
'two'
</code></pre>
<p>The <code>list.sort()</code> method uses the output of these calls (once for each element in the list) to sort the elements. So for the 4 elements, the function returns <code>'one'</code>, <code>'two'</code>, <code>'three'</code>, and <code>'four'</code>, and the 4 tuples are then sorted purely on the lexicographical (alphabetical) ordering of those 4 strings. That order would be <code>'four'</code>, <code>'one'</code>, <code>'three'</code>, <code>'two'</code>, which is what you see reflected in the final sorted list.</p>
<p>This form of sorting-by-alternative-key is commonly called a <a href="https://en.wikipedia.org/wiki/Schwartzian_transform" rel="nofollow"><em>Schwartzian transform</em></a>, after Randal L. Schwartz, who popularised the technique in Perl.</p>
| 0 | 2016-09-30T16:14:26Z | [
"python",
"sorting",
"lambda"
]
|
Python beginner - Sorting tuples using lambda functions | 39,795,734 | <p>I'm going through the tutorial intro for Python and I'm stuck on understanding a piece of code. This is from section 4.7.5 of the tutorial.</p>
<pre><code>pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs
</code></pre>
<p>This bit of code returns </p>
<pre><code>[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
</code></pre>
<p>So in line one, it defines pairs with a list of different tuples. I get that.
Line two is where I'm completely thrown off and I've done quite a bit of messing around with it to try to understand what's happening.</p>
<p>I've found that sort() is applying a built-in function to the variable pairs, and presumably it is sorting it per the instructions I'm giving it.</p>
<p>The sort() function requires a key, and key has to be defined using a function, hence the use of lambda. I think all of this is correct, but I may be way off here.</p>
<p>Lambda defines a new parameter, "pair" on the left side of the colon, and on the right side is the calculation to define the return value of the lambda function.</p>
<p>That's where I'm thrown off. What does "pair[1]" do? What is its affect on the "pair" on the left side of the colon? </p>
<p>What value does it return? I can't seem to get it to return any sort of value outside of coding it just like this.</p>
<p>I'm guessing that it somehow points to a specific tuple and sorts it based on repositioning that, but I'm not sure of the logic behind that. </p>
<p>Can anyone explain this for me? Thank you.</p>
| 0 | 2016-09-30T16:07:46Z | 39,795,839 | <p>Sometimes when starting to work with <code>lambda</code>, it's easier to write out the function explicitly. Your lambda function is equivalent to:</p>
<pre><code>def sort_key(pair):
return pair[1]
</code></pre>
<p>If we want to be more verbose, we can unpack pair to make it even more obvious:</p>
<pre><code>def sort_key(pair):
int_value, string_value = pair
return string_value
</code></pre>
<p>Because <code>list.sort</code> orders the items based on the return value of the <code>key</code> function (if present), now we see that it is sorting the tuples by their <em>string value</em>. Since strings sort lexicographically, <code>"four"</code> comes before <code>"one"</code> (think alphabetical order).</p>
| 0 | 2016-09-30T16:14:56Z | [
"python",
"sorting",
"lambda"
]
|
Get the index of a unique character in a table (list of lists)? | 39,795,784 | <p>I have a list of r lists of r elements each.
Let's say <code>r=3</code> then I have something that looks like this:</p>
<pre><code>list=[["o","o","o"],["o","i","o"],["o","o","o"]]
</code></pre>
<p>I would like, using the method """<code>list.index(item)</code>""", to get the index of the "i" elements inside this list. So as a result I should get something I imagine like (x,y) with x for the xth sublist and y for the yth element inside the xth sublist ((1,1) in this case).</p>
<p>I can join the code of my program (game) if you need it later. </p>
| -1 | 2016-09-30T16:11:12Z | 39,795,995 | <p>You could <code>try</code> to find the index row by row:</p>
<pre><code>def findI(rows):
for i,row in enumerate(rows):
try:
return (i,row.index("i"))
except ValueError:
pass
</code></pre>
<p>For example:</p>
<pre><code>>>> x =[["o","o","o"],["o","i","o"],["o","o","o"]]
>>> findI(x)
(1, 1)
</code></pre>
| 1 | 2016-09-30T16:24:32Z | [
"python",
"list",
"python-3.x"
]
|
Get the index of a unique character in a table (list of lists)? | 39,795,784 | <p>I have a list of r lists of r elements each.
Let's say <code>r=3</code> then I have something that looks like this:</p>
<pre><code>list=[["o","o","o"],["o","i","o"],["o","o","o"]]
</code></pre>
<p>I would like, using the method """<code>list.index(item)</code>""", to get the index of the "i" elements inside this list. So as a result I should get something I imagine like (x,y) with x for the xth sublist and y for the yth element inside the xth sublist ((1,1) in this case).</p>
<p>I can join the code of my program (game) if you need it later. </p>
| -1 | 2016-09-30T16:11:12Z | 39,796,244 | <p>Or you can try this:</p>
<pre><code>list=[["o","o","o"],["o","i","o"],["o","o","o"]]
f = [sublist for sublist in list if element in sublist][0]
print(list.index(f), f.index(element))
</code></pre>
<p>That <code>[0]</code> is because it will return something like <code>[[a,b]]</code>, because is like a filter. But I need <code>[a, b]</code>. Hope it helps. The problem with this is that it fails when the element isn't in list.</p>
| 0 | 2016-09-30T16:38:53Z | [
"python",
"list",
"python-3.x"
]
|
Get the index of a unique character in a table (list of lists)? | 39,795,784 | <p>I have a list of r lists of r elements each.
Let's say <code>r=3</code> then I have something that looks like this:</p>
<pre><code>list=[["o","o","o"],["o","i","o"],["o","o","o"]]
</code></pre>
<p>I would like, using the method """<code>list.index(item)</code>""", to get the index of the "i" elements inside this list. So as a result I should get something I imagine like (x,y) with x for the xth sublist and y for the yth element inside the xth sublist ((1,1) in this case).</p>
<p>I can join the code of my program (game) if you need it later. </p>
| -1 | 2016-09-30T16:11:12Z | 39,797,970 | <p>If you are looking for a solution that finds an index for all values in the nested list, here is a function for you:</p>
<pre><code>def find_indexes(needle, lst):
return [(lst_idx, sub_idx) for lst_idx, sublst in enumerate(lst)
for sub_idx, i in enumerate(sublst)
if i == needle]
</code></pre>
<p>You can use as follows:</p>
<pre><code>>>> lst = [["o","a","o"],["a","i","o"],["o","o","a"]]
>>> find_indexes('a', lst)
[(0, 1), (1, 0), (2, 2)]
</code></pre>
| 2 | 2016-09-30T18:34:05Z | [
"python",
"list",
"python-3.x"
]
|
Iterating through two lists, operating and creating a third list in Python | 39,795,840 | <p>I am a completely Python beginner and am really struggling with iterations on Lists!
There's this problem I have been trying to solve using python using Lists:</p>
<p>I have a "<strong>TotalList</strong>" for the total costs on each hour for a product:</p>
<p>Hr totalcost<br>
1 100<br>
2 50<br>
...<br>
24 150</p>
<p>And I have <strong>minList</strong> which has the % of the total cost in that hour for that minute </p>
<p>Hr Min (%) Cost<br>
1 1 1.0<br>
1 2 5.0<br>
...<br>
2 1 2.0<br>
2 2 4.0<br>
...
24 1 2.3 </p>
<p>I want to evaluate <strong>for each hour</strong> the total cost in every minute and put it in a third list. That list <strong>minuteCost</strong> would look like this:</p>
<p>Hr Min Cost<br>
1 1 totalList [0][2] * minList [0][2]<br>
1 2 totalList [1][2] * minList [1][2]<br>
...<br>
2 1 xxx<br>
2 2 xxx<br>
...<br>
24 1 xxx</p>
<p>I am sure there's an easy way to do this! Any suggestion would be much appreciated! I would also appreciate solutions based on numpy.</p>
| 0 | 2016-09-30T16:14:57Z | 39,795,948 | <p>You can create a dictionary from your total cost list and compute the minute costs by referencing the total cost at each hour (from the dict) and multiplying by the percentage minute cost.</p>
<p>A <em>list comprehension</em> will do:</p>
<pre><code>tc_mapping = dict(totalList) # map hour to cost
minute_cost = [(h, m, percent * tc_mapping[h]) for h, m, percent in minList]
</code></pre>
| 1 | 2016-09-30T16:21:23Z | [
"python",
"list",
"numpy",
"comparison"
]
|
Iterating through two lists, operating and creating a third list in Python | 39,795,840 | <p>I am a completely Python beginner and am really struggling with iterations on Lists!
There's this problem I have been trying to solve using python using Lists:</p>
<p>I have a "<strong>TotalList</strong>" for the total costs on each hour for a product:</p>
<p>Hr totalcost<br>
1 100<br>
2 50<br>
...<br>
24 150</p>
<p>And I have <strong>minList</strong> which has the % of the total cost in that hour for that minute </p>
<p>Hr Min (%) Cost<br>
1 1 1.0<br>
1 2 5.0<br>
...<br>
2 1 2.0<br>
2 2 4.0<br>
...
24 1 2.3 </p>
<p>I want to evaluate <strong>for each hour</strong> the total cost in every minute and put it in a third list. That list <strong>minuteCost</strong> would look like this:</p>
<p>Hr Min Cost<br>
1 1 totalList [0][2] * minList [0][2]<br>
1 2 totalList [1][2] * minList [1][2]<br>
...<br>
2 1 xxx<br>
2 2 xxx<br>
...<br>
24 1 xxx</p>
<p>I am sure there's an easy way to do this! Any suggestion would be much appreciated! I would also appreciate solutions based on numpy.</p>
| 0 | 2016-09-30T16:14:57Z | 39,796,114 | <p>Easiest for a beginner to understand IMO:</p>
<pre><code>minuteCost = []
x = 0
for i in minList:
tempList = [i[0], i[1], totalList[x][1]*i[2]]
minuteCost.append(tempList)
x += 1
</code></pre>
<p>This assumes that TotalList and minList are the same length.</p>
| 0 | 2016-09-30T16:31:25Z | [
"python",
"list",
"numpy",
"comparison"
]
|
python Return value none | 39,796,124 | <p>I need some clarification. When I execute the below code with the function using <code>return</code>, I am getting different behavior from when I use the function using <code>print</code>. I am getting the same output but it is printing a word "none" which is not in the program.</p>
<pre><code>import random
# **With Return**
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
# **With Print**
def getAnswer2(answerNumber):
if answerNumber == 1:
print('It is certain')
elif answerNumber == 2:
print('It is decidedly so')
elif answerNumber == 3:
print('Yes')
r = random.randint(1, 3)
fortune = getAnswer(r)
print(fortune)
fortune = getAnswer2(r)
print(fortune)
</code></pre>
<p>The output is for example</p>
<pre><code>Yes
Yes
None
</code></pre>
| -1 | 2016-09-30T16:32:03Z | 39,796,469 | <p>The problem is that the function you use with print statements does not have a return value. However you are printing the return of that function with the line <code>print(fortune)</code>. So what should it print if there is nothing there? Well, it prints <code>None</code>.</p>
| 0 | 2016-09-30T16:55:44Z | [
"python",
"python-2.7"
]
|
python Return value none | 39,796,124 | <p>I need some clarification. When I execute the below code with the function using <code>return</code>, I am getting different behavior from when I use the function using <code>print</code>. I am getting the same output but it is printing a word "none" which is not in the program.</p>
<pre><code>import random
# **With Return**
def getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
# **With Print**
def getAnswer2(answerNumber):
if answerNumber == 1:
print('It is certain')
elif answerNumber == 2:
print('It is decidedly so')
elif answerNumber == 3:
print('Yes')
r = random.randint(1, 3)
fortune = getAnswer(r)
print(fortune)
fortune = getAnswer2(r)
print(fortune)
</code></pre>
<p>The output is for example</p>
<pre><code>Yes
Yes
None
</code></pre>
| -1 | 2016-09-30T16:32:03Z | 39,796,577 | <p>Every Python function implicitly returns <code>None</code>, unless you explicitly return something else.</p>
<p>In your first section, you are explicitly returning the string, and printing that value.</p>
<p>In your second section, you are printing the message, and then printing the return value (<code>None</code>, implicitly).</p>
| 0 | 2016-09-30T17:04:53Z | [
"python",
"python-2.7"
]
|
Proxybroker IndexError | 39,796,177 | <p>I'm trying to use the python package proxybroker.<br>
I tried to use one of the examples mentioned here. I just copied the following example to run locally:</p>
<blockquote>
<pre><code>import asyncio from proxybroker import Broker
async def save(proxies, filename):
"""Save proxies to a file."""
with open(filename, 'w') as f:
while True:
proxy = await proxies.get()
if proxy is None:
break
proto = 'https' if 'HTTPS' in proxy.types else 'http'
row = '%s://%s:%d\n' % (proto, proxy.host, proxy.port)
f.write(row)
def main():
proxies = asyncio.Queue()
broker = Broker(proxies)
tasks = asyncio.gather(broker.find(types=['HTTP', 'HTTPS'], limit=10),
save(proxies, filename='proxies.txt'))
loop = asyncio.get_event_loop()
loop.run_until_complete(tasks)
if __name__ == '__main__':
main()</code></pre>
</blockquote>
<p>When I try to run the code the following error is thrown together with some deprecation warnings:</p>
<blockquote>
<pre><code>/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/aiohttp/client.py:494:
DeprecationWarning: Use async with instead warnings.warn("Use async
with instead", DeprecationWarning)
/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/aiohttp/client.py:494:
DeprecationWarning: Use async with instead warnings.warn("Use async
with instead", DeprecationWarning)
/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/aiohttp/client.py:494:
DeprecationWarning: Use async with instead warnings.warn("Use async
with instead", DeprecationWarning)
/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/aiohttp/client.py:494:
DeprecationWarning: Use async with instead warnings.warn("Use async
with instead", DeprecationWarning)
/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/aiohttp/client.py:494:
DeprecationWarning: Use async with instead warnings.warn("Use async
with instead", DeprecationWarning)
/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/aiohttp/client.py:494:
DeprecationWarning: Use async with instead warnings.warn("Use async
with instead", DeprecationWarning)
/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/aiohttp/client.py:494:
DeprecationWarning: Use async with instead warnings.warn("Use async
with instead", DeprecationWarning)
/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/aiohttp/client.py:494:
DeprecationWarning: Use async with instead warnings.warn("Use async
with instead", DeprecationWarning)
/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/aiohttp/client.py:494:
DeprecationWarning: Use async with instead warnings.warn("Use async
with instead", DeprecationWarning)
/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/aiohttp/client.py:494:
DeprecationWarning: Use async with instead warnings.warn("Use async
with instead", DeprecationWarning) https://getproxy.net/en/ is failed.
Error: ClientOSError(101, 'Cannot connect to host getproxy.net:443
ssl:True [Can not connect to getproxy.net:443 [Network is
unreachable]]'); https://getproxy.net/en/ is failed. Error:
ClientOSError(101, 'Cannot connect to host getproxy.net:443 ssl:True
[Can not connect to getproxy.net:443 [Network is unreachable]]');
https://getproxy.net/en/ is failed. Error: ClientOSError(101, 'Cannot
connect to host getproxy.net:443 ssl:True [Can not connect to
getproxy.net:443 [Network is unreachable]]'); Traceback (most recent
call last): File
"/home/sebastian/PycharmProjects/testing/test/test_prox.py", line 27,
in
main() File "/home/sebastian/PycharmProjects/testing/test/test_prox.py", line 23,
in main
loop.run_until_complete(tasks) File "/usr/lib/python3.5/asyncio/base_events.py", line 387, in
run_until_complete
return future.result() File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step
result = coro.throw(exc) File "/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/proxybroker/api.py",
line 108, in find
await self._run(self._checker.check_judges(), action) File "/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/proxybroker/api.py",
line 114, in _run
await tasks File "/usr/lib/python3.5/asyncio/futures.py", line 361, in __iter__
yield self # This tells Task to wait for completion. File "/usr/lib/python3.5/asyncio/tasks.py", line 296, in _wakeup
future.result() File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step
result = coro.throw(exc) File "/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/proxybroker/checker.py",
line 26, in check_judges
await asyncio.gather(*[j.check() for j in self._judges]) File "/usr/lib/python3.5/asyncio/futures.py", line 361, in __iter__
yield self # This tells Task to wait for completion. File "/usr/lib/python3.5/asyncio/tasks.py", line 296, in _wakeup
future.result() File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None) File "/home/sebastian/PycharmProjects/STW/venv/lib/python3.5/site-packages/proxybroker/judge.py",
line 82, in check
j=self, code=resp.status, page=page[0], IndexError: string index out of range</code></pre>
</blockquote>
<p>I use python3.5.2 and the up to date versions of proxybroker (0.1.4) aiohttp (1.0.2) asyncio (3.4.3).</p>
<p>I'm not sure what causes the error as I did not change the code example and as far as I know I have installed all dependencies. Can anyone help me and tell me what I am doing wrong and even better how to do it right?</p>
<p><strong>EDIT</strong><br>
A quick workaround for the issue is to change the line where the error occurs. That line is only for logging an error, thus the change should not do any harm.
For this workaround - not a solution - I added an additional check in the judge.py in line 79 where the exception was raised before.
Locally I changed it to:</p>
<pre><code> if isinstance(page, type(list())) or isinstance(page, type(dict())):
log.error(('{j} is failed. HTTP status code: {code}; '
'Real IP on page: {ip}; Version: {word}; '
'Response: {page}').format(
j=self, code=resp.status, page=page[0],
ip=(get_my_ip() in page), word=(rv in page)))
else:
log.error(('{j} is failed. HTTP status code: {code}; '
'Real IP on page: {ip}; Version: {word}; '
'Response: {page}').format(
j=self, code=resp.status, page=page,
ip=(get_my_ip() in page), word=(rv in page)))
</code></pre>
<p>That way I can use proxybroker again. The issue is filed on gihub with <a href="https://github.com/constverum/ProxyBroker/issues/23" rel="nofollow">proxybroker</a>.</p>
| 0 | 2016-09-30T16:35:00Z | 39,804,885 | <p>Deprecation warnings are harmless (at least unless I'll remove this kind of backward compatibility).</p>
<p>The error just says that <code>getproxy.net</code> is not available -- this is your main problem.</p>
| 0 | 2016-10-01T09:15:02Z | [
"python",
"asynchronous",
"python-3.5",
"python-asyncio",
"aiohttp"
]
|
statsmodels mosaic plot - how to order categories | 39,796,183 | <p>Here is dataframe:</p>
<pre><code>import pandas as pd
from statsmodels.graphics.mosaicplot import mosaic
df = pd.DataFrame({'size' : ['small', 'large', 'large', 'small', 'large', 'small'],
'length' : ['long', 'short', 'short', 'long', 'long', 'short']})
</code></pre>
<p>if I plot it <code>mosaic(df, ['size', 'length'])</code> it will display <code>size</code> in this order <code>small</code> then <code>large</code>, while I would like to have <code>large</code> and then <code>small</code>. Is there way to achieve it?</p>
| 2 | 2016-09-30T16:35:10Z | 39,796,405 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a> to sort values present in the size column to alter the order.</p>
<pre><code>mosaic(df.sort_values('size'), ['size', 'length'])
</code></pre>
<p><a href="http://i.stack.imgur.com/iMG3i.png" rel="nofollow"><img src="http://i.stack.imgur.com/iMG3i.png" alt="Image"></a></p>
| 2 | 2016-09-30T16:51:02Z | [
"python",
"pandas",
"statsmodels",
"mosaic"
]
|
PCRE Regex (*COMMIT) equivalent for Python | 39,796,252 | <p>The below pattern took me a long time to find. When I finally found it, it turns out that it doesn't work in Python. Does anyone know if there is an alternative?</p>
<p><code>(*COMMIT)</code> Defined: Causes the whole match to fail outright if the rest of the pattern does not match.</p>
<p><code>(*FAIL)</code> doesn't work in Python either. But this can be replaced by <code>(?!)</code>.</p>
<pre><code>+-----------------------------------------------+
|Pattern: |
|^.*park(*COMMIT)(*FAIL)|dog |
+-------------------------------------+---------+
|Subject | Matches |
+-----------------------------------------------+
|The dog and the man play in the park.| FALSE |
|Man I love that dog! | TRUE |
|I'm dog tired | TRUE |
|The dog park is no place for man. | FALSE |
|park next to this dog's man. | FALSE |
+-------------------------------------+---------+
</code></pre>
<p>Example taken from:
<a href="http://stackoverflow.com/questions/32747887/regex-match-substring-unless-another-substring-matches/39795732#39795732">regex match substring unless another substring matches</a></p>
| 2 | 2016-09-30T16:39:24Z | 39,796,696 | <p>This might not be a generic replacement, but for your case you can work with lookaheads, to assert that dog is matched, but park is not: <code>^(?=.*dog)(?!.*park).*$</code></p>
<p>Your samples on <a href="https://regex101.com/r/gOY9GT/1" rel="nofollow">regex101</a></p>
| 2 | 2016-09-30T17:12:32Z | [
"python",
"regex"
]
|
get list in python | 39,796,301 | <pre><code>#ideal nodes list should be
['A','B','C','D','E','F','G','H','I','J','K','L','M','N']
</code></pre>
<p>So I tried to write a definition to read the nodes and edges.Here is my code,but it seems does not work.</p>
<pre><code>""" read nodes"""
def rd_nodes(a):
nline =[line.split(":")[1].replace(';',',').split(',') for line in a]
for i in nline:
return i
</code></pre>
| 1 | 2016-09-30T16:42:57Z | 39,796,787 | <p><a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations</code></a> can help you here.</p>
<p>Try this:</p>
<pre><code>from itertools import combinations
s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
nodes = set()
edges = set()
for line in s.split():
clusters = line.split(':')[1].split(';')
for cluster in clusters:
_nodes = cluster.split(',')
nodes.update(_nodes)
edges.update(combinations(_nodes, 2))
</code></pre>
<p>You may use <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="nofollow"><code>collections.OrderedDict</code></a> structure for <code>nodes</code> and <code>edges</code> to maintain order if you want. Just use nodes and edges as dict keys and then at the end of the script get list of the keys.</p>
| 1 | 2016-09-30T17:18:33Z | [
"python",
"list",
"edges"
]
|
get list in python | 39,796,301 | <pre><code>#ideal nodes list should be
['A','B','C','D','E','F','G','H','I','J','K','L','M','N']
</code></pre>
<p>So I tried to write a definition to read the nodes and edges.Here is my code,but it seems does not work.</p>
<pre><code>""" read nodes"""
def rd_nodes(a):
nline =[line.split(":")[1].replace(';',',').split(',') for line in a]
for i in nline:
return i
</code></pre>
| 1 | 2016-09-30T16:42:57Z | 39,797,325 | <p>As @skovorodkin has the correct answer, but if you want pure Python version (Though I wonder why) you could use this code</p>
<pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def combinations(nodes):
if len(nodes) < 2:
return (tuple(nodes))
else:
i = 1
ret_tuple = []
for n in nodes:
rest = nodes[i:]
for r in rest:
ret_tuple.append(tuple([n,r]))
i += 1
return tuple(ret_tuple)
nodes = set()
edges = set()
for line in s.split():
clusters = line.split(':')[1].split(';')
for cluster in clusters:
_nodes = cluster.split(',')
nodes.update(_nodes)
edges.update(combinations(_nodes))
print nodes
print edges
</code></pre>
| 0 | 2016-09-30T17:52:53Z | [
"python",
"list",
"edges"
]
|
range as input in python | 39,796,305 | <p>this is a simple program for Fibonacci series . its running perfectly for fixed range. but i would like to know is it possible to get range as input? if so please let me know the syntax to get range as input. </p>
<pre><code>xx=0
x=float (raw_input("enter the starting number:"))
r1=xx+x
print r1
r2=r1+x
print r2
r3=r1+r2
print r3
for i in range(10):
r4=r2+r3
print r4
r2=r3
r3=r4
</code></pre>
<p>""" looking for answers"""</p>
| -5 | 2016-09-30T16:43:06Z | 39,796,421 | <p>Do it like you asked for the starting number:</p>
<pre><code>number_of_outputs = int( raw_input('Enter the number of outputs: '))
#Your code goes here
for i in range(number_of_ouputs):
#More code goes here
</code></pre>
| 1 | 2016-09-30T16:53:03Z | [
"python",
"fibonacci"
]
|
How can I call prompt_toolkit from the tornado event loop? | 39,796,344 | <p>I am trying to use prompt_toolkit from an application that uses the tornado event loop, but I can not work out the correct way to add the prompt_toolkit prompt to the event loop.</p>
<p>The prompt_toolkit documentation has an example of using it in asyncio (<a href="http://python-prompt-toolkit.readthedocs.io/en/stable/pages/building_prompts.html#prompt-in-an-asyncio-application" rel="nofollow">Asyncio Docs</a>):</p>
<pre><code>from prompt_toolkit.shortcuts import prompt_async
async def my_coroutine():
while True:
result = await prompt_async('Say something: ', patch_stdout=True)
print('You said: %s' % result)
</code></pre>
<p>I have managed to make this work from the asyncio event loop:</p>
<pre><code>import asyncio
l = asyncio.get_event_loop()
l.create_task(my_coroutine())
l.run_forever()
Say something: Hello
You said: Hello
</code></pre>
<p>However, I have failed to make it work from the tornado event loop. I have tried the following:</p>
<pre><code>from tornado.ioloop import IOLoop
IOLoop.current().run_sync(my_coroutine)
</code></pre>
<p>This will issue the initial prompt but then appears to block the console.</p>
<p>I have also tried:</p>
<pre><code>IOLoop.current().add_callback(my_coroutine)
IOLoop.current().start()
</code></pre>
<p>This does the same thing, but also produces the error message:</p>
<pre><code>RuntimeWarning: coroutine 'my_coroutine' was never awaited
</code></pre>
<p>And I have tried:</p>
<pre><code>IOLoop.current().spawn_callback(my_coroutine)
IOLoop.current().start()
</code></pre>
<p>I am clearly not understanding something here.</p>
<p>Can anyone throw any light on how this should be done?</p>
<p>I am using: Python 3.5.0, tornado 4.3.</p>
| 0 | 2016-09-30T16:46:32Z | 39,805,136 | <p>To use <a href="http://www.tornadoweb.org/en/stable/asyncio.html" rel="nofollow">Tornado's asyncio integration</a>, you must tell Tornado to use the asyncio event loop. Usually, that means doing this at the start of your app:</p>
<pre><code>from tornado.platform.asyncio import AsyncIOMainLoop
AsyncIOMainLoop().install()
</code></pre>
| 0 | 2016-10-01T09:44:38Z | [
"python",
"tornado",
"prompt",
"toolkit"
]
|
My Django application is not displaying content from the db | 39,796,387 | <pre><code>{% extends 'photos/base.html' %}
{% block galleries_active %}active{% endblock %}
{% block body%}
<div class="gallery-container" container-fluid>
<!--- Galleries--->
<div class="row">
<div class="col-sm-12">
<h3>Text's Gallery</h3>
</div>
{% if gallery %}
{% for gallery in galleries %}
<div class="col-sm-4 col-lg-2">
<div class="thumbnail">
<a href="{% url 'photos:details' gallery.id %}">
<img src="{{gallery.Gallery_logo}}" class="img-responsive" height="240" width="240">
</a>
<div class="caption">
<h2>{{gallery.Title}}</h2>
<h4>{{gallery.Category}}</h4>
<!-- View Details-->
<a href="{% url 'photos:detail' gallery.id %}" class="btn btn-primary btn-sm" role="button">View Details</a>
<!-- Delete Album-->
<form action="{% url 'photos:delete_gallery' gallery.id %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="gallery_id" value="{{gallery.id}}">
<button type="submit" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash"></span>
</button>
</form>
<!-- Favorite -->
<a href="#" class="btn btn-default btn-sm btn-favorite" role="button">
<span class="glyphicon glyphicon-star"></span>
</a>
</div>
</div>
</div>
{% cycle '' '' '' '' '' '<div class="clearfix visible-lg"></div>' %}
{% endfor %}
{% else %}
<div class="col-sm-12">
<br>
<a href="#">
<button type="button" class="btn btn-success">
<span class="glyphicon glyphicon-plus"></span>&nbsp; Add a Gallery
</button>
</a>
</div>
{% endif %}
</div>
</div>
</div>
{% endblock %}
</code></pre>
<p>That is my index file</p>
<p>below is my views.py file </p>
<pre><code>from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from .models import Gallery
class IndexView(generic.ListView):
template_name = 'photos/index.html'
context_object_name = 'all_galleries'
def get_queryset(self):
return Gallery.objects.all()
class DetailsView(generic.DetailView):
model = Gallery
template_name = 'photos/detail.html'
class GalleryCreate(CreateView):
model = Gallery
fields = ['Title','Category','Gallery_logo']
class GalleryUpdate(UpdateView):
model = Gallery
fields = ['Title','Category','Gallery_logo']
class GalleryDelete(DeleteView):
model = Gallery
success_url = reverse_lazy('photos:index')
</code></pre>
<p>and my models.py </p>
<pre><code>from django.db import models
from django.core.urlresolvers import reverse
class Gallery(models.Model):
Title = models.CharField(max_length=250)
Category = models.CharField(max_length=250)
Gallery_logo = models.CharField(max_length=1000)
def get_absolute_url(self):
return reverse('photos:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.Title + '_' + self.Gallery_logo
class Picture (models.Model):
Gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE)
Title = models.CharField(max_length=250)
Artist = models.CharField(max_length=250)
Price = models.CharField(max_length=20)
interested = models.BooleanField(default=False)
def __str__(self):
return self.Title
</code></pre>
<p>I was following the newboston django tutorials video number 30 trying to make the same out put as bucky. If any one has followed the series and has a clean version of the video 30 index page source code please help out. </p>
<p>I modified the code to work for an online photogallery store where the admin will add images which are grouped in categories which can be downloaded by visitors.</p>
| 0 | 2016-09-30T16:49:25Z | 39,796,496 | <p>You have <code>context_object_name = 'all_galleries'</code> in </p>
<pre><code>class IndexView(generic.ListView):
template_name = 'photos/index.html'
context_object_name = 'all_galleries'
...
</code></pre>
<p>However you loop over <code>galleries</code> in template</p>
<pre><code>{% for gallery in galleries %}
</code></pre>
<p>Needs to be </p>
<pre><code>{% for gallery in all_galleries %}
</code></pre>
<p>Also you have <code>{% if gallery %}</code> before the loop in template which doesn't make sense, because there is no <code>gallery</code> variable. You need to check <code>{% if all_galleries %}</code>.</p>
<p>NOTE #1: your field names in classes that in models better be lowercase.</p>
<p>NOTE #2: in <code>IndexView</code> you need to provide <code>model</code> and you can remove <code>get_queryset()</code>, because there is no custom query that retrieve data with filters. So you need to use</p>
<pre><code>class IndexView(generic.ListView):
model = Gallery
template_name = 'photos/index.html'
context_object_name = 'all_galleries'
</code></pre>
| 1 | 2016-09-30T16:59:09Z | [
"python",
"django"
]
|
Error handling np.arccos() and classifying triangles in Python | 39,796,422 | <p>The code below is my attempt at a codewars challenge asking you to <a href="https://www.codewars.com/kata/53907ac3cd51b69f790006c5/train/python" rel="nofollow">calculate the interior angles of a triangle</a>. Really inelegant, brute force. I'm passing all test cases, but also receiving an error: </p>
<pre><code>-c:37: RuntimeWarning: invalid value encountered in arccos
-c:38: RuntimeWarning: invalid value encountered in arccos
-c:39: RuntimeWarning: invalid value encountered in arccos
</code></pre>
<p>So I am trying to figure out how my current checks aren't catching invalid values prior to the gamma calculations (noted with ** in the code, below). </p>
<p>THE PROBLEM:</p>
<p>You should calculate type of triangle with three given sides a, b and c (given in any order).</p>
<p>If all angles are less than 90°, this triangle is acute and function should return 1.</p>
<p>If one angle is strictly 90°, this triangle is right and function should return 2.</p>
<p>If one angle more than 90°, this triangle is obtuse and function should return 3.</p>
<p>If three sides cannot form triangle, or one angle is 180° (which turns triangle into segment) - function should return 0.</p>
<p>Input parameters are sides of given triangle. All input values are non-negative floating point or integer numbers (or both).</p>
<pre><code>import numpy
def triangle_type(a, b, c):
# Should return triangle type:
# 0 : if triangle cannot be made with given sides
# 1 : acute triangle
# 2 : right triangle
# 3 : obtuse triangle
# make sure all sides are non-zero
if a and b and c:
pass
else:
return 0
# triangle inequality test
if not ((c - b) < a < (c + b)) and ((a - c) < b < (a + c)) and ((b - a) < b < (b + a)):
return 0
elif a < b < c or b < a < c:
# print a,b,c
pass
elif b < c < a or c < b < a:
a, c = c, a
# print a, b, c
elif c < a < b or a < c < b:
b, c = c, b
# print a, b, c
else:
# print a, b, c
pass
# calculate the gammas **THIS IS WHERE I NEED HELD**
gamma_1 = numpy.rad2deg(numpy.arccos((a * a + b * b - c * c) / (2.0 * a * b)))
gamma_2 = numpy.rad2deg(numpy.arccos((c * c + a * a - b * b) / (2.0 * c * a)))
gamma_3 = numpy.rad2deg(numpy.arccos((b * b + c * c - a * a) / (2.0 * b * c)))
#check for a right angle
if (a * a + b * b == c * c) or (b * b + c * c == a * a) or (c * c + b * b == a * a):
return 2
#check acute angles
elif max(gamma_1, gamma_2, gamma_3) < 90.0:
return 1
#check obtuse
elif max(gamma_1, gamma_2, gamma_3) > 90.0:
return 3
else:
return 0
</code></pre>
<p>I can't check the validity of the <code>gamma</code> values without actually making the call, thus generating the error. How can I get around this problem?</p>
<p>Some test cases are</p>
<pre><code>triangle_type(7,3,2) # Not triangle 0
triangle_type(2,4,6) # Not triangle 0
triangle_type(8,5,7) # Acute 1
triangle_type(3,4,5) # Right 2
triangle_type(7,12,8) # Obtuse 3
</code></pre>
<p>But this is by no means exhaustive - there are 121 other tests I can't see.</p>
| 0 | 2016-09-30T16:53:12Z | 39,797,430 | <p>You need to check the values you pass to <code>numpy.arccos</code>. They must be between -1 and 1. But due to floating point calculations they could end up larger than 1 or smaller than -1.</p>
| 0 | 2016-09-30T17:59:58Z | [
"python",
"numpy",
"math",
"triangulation"
]
|
Running python in powershell crashes | 39,796,424 | <p>I am learning python from the book <em>Learn Python the Hardway</em>. I tried running python in powershell and python crashes.</p>
<pre class="lang-none prettyprint-override"><code>PS C:\python27>Fatal Python error:
Py_Initialize: can't initialize sys standard streams
File ".\lib\encodings\__init__.py, line 123
raise CodecRegistryError,\
^ SyntaxError: invalid syntax
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
</code></pre>
<p>I have tried reinstalling several versions of python. Please tell me a way to fix this.</p>
| 0 | 2016-09-30T16:53:16Z | 39,796,569 | <p>I'm assuming here that you have tried using cmd.exe (the command prompt) (which you can run by pressing the windows key + R and then typing cmd). It might be a bug. When I looked at the Python <a href="https://bugs.python.org/issue10920" rel="nofollow">issue trackers</a>, it seems that something like this has happened before. You could try dual-booting Linux, or using <a href="https://www.cygwin.com" rel="nofollow">cygwin</a>, which allows you to use a Linux shell on your Windows machine.</p>
| 0 | 2016-09-30T17:04:21Z | [
"python",
"python-2.7",
"powershell"
]
|
Python Pycharm loop error | 39,796,455 | <p>I started at university and programming in python 3.5 is one of our important courses. We use an online website to code and compile the programs but I like to save them on my computer as well but there is a slight error...</p>
<pre><code>tolerantie = float(input("Tolerantie = "))
i = 0
fact = 1
nterm = float(1)
s = 0
while nterm > tolerantie:
s += nterm
i += 1
fact *= i
nterm = 1/fact
print s
print i
</code></pre>
<p>I use this program to approximate the number 'e' using Pycharm but my computer always gives the values s=2 and i=2 so I assume it doesn't execute the while-loop... Do I need to add something because it is in Pycharm because this program works perfectly on the server of the University?</p>
<p>Regards,</p>
| 0 | 2016-09-30T16:55:07Z | 39,796,828 | <p>In your case <code>PyCharm</code> uses <code>python2.x</code> to compile the script.<br>
You can <a href="http://stackoverflow.com/questions/1267869/how-can-i-force-division-to-be-floating-point-in-python">force division to be floating point in <code>Pythno2.x</code></a> or change pycharm configuration and choose <code>Python3.5</code> interpreter then instead of <code>print s</code> use <code>print(s)</code>.</p>
| 0 | 2016-09-30T17:21:12Z | [
"python",
"while-loop",
"pycharm"
]
|
How to break the string into pieces and assign the values to the substrings preceding the number in the originial string | 39,796,484 | <p>I want to break the string into pieces (delimiters are space and <code>/</code>) and assign values to the sub-strings every time a float or int follows the string:</p>
<p>For example, the string could be:</p>
<p>'ABC 12/5 a1 b-2.5 c34.5d54'</p>
<p>Using this, I want the output as:</p>
<p><code>somelist=['ABC', '12', '5']</code>, and
<code>a=1, b=-2.5, c=34.5, d=54</code></p>
| 0 | 2016-09-30T16:57:49Z | 39,797,368 | <p>I propose this script:</p>
<pre><code>import re
s = 'ABC 12/5 a1 b-2.5 c34.5d54'
parts = re.findall('([a-z]+)(-?\d+(?:\.\d+)?)|([^ /]+)', s)
somelist = [rest for (key, value, rest) in parts if key == '']
vars = dict((key, float(value)) for (key, value, rest) in parts if key != '')
print(somelist)
print(vars)
</code></pre>
<p>Output:</p>
<pre><code>['ABC', '12', '5']
{'c': 34.5, 'd': 54.0, 'a': 1.0, 'b': -2.5}
</code></pre>
<p>The "variables" are in fact output as dictionary keys, which I think is more appropriate.</p>
<h3>Explanation</h3>
<p>This regular expression:</p>
<pre><code>([a-z]+)(-?\d+(?:\.\d+)?)|([^ /]+)
</code></pre>
<p>will somehow match anything that is not a space or slash. First it tries to match the part before the <code>|</code>:</p>
<pre><code>([a-z]+)(-?\d+(?:\.\d+)?)
</code></pre>
<p>This will match any sequence of letters followed by a number. The letters are captured in the first group (cf. the parentheses), and the number part in the second one. The number can optionally have a minus sign (<code>-?</code>) and/or a fractional part (<code>(?:\.\d+)?</code>), which is not captured in a separate group (hence the <code>?:</code>).</p>
<p>If that fails, the other part of the regular expression kicks in:</p>
<pre><code>([^ /]+)
</code></pre>
<p>This captures anything up to the next delimiter into the third capture group.</p>
<p>Now <code>findall</code> makes a nice array of this, with each part ending up at the corresponding index of each sub array.</p>
<p>The two list comprehensions each take care of the two different cases and gather those results in either an array (where the third capture group was matched) or a dict (where the first two were matched). </p>
| 1 | 2016-09-30T17:56:06Z | [
"python",
"regex"
]
|
How would I count the number of days based on months with zero data? | 39,796,519 | <p>I'm writing a script in which I read in a csv with several columns and rows. I need the script to total the values in each column for a single row and return which columns have a value of zero for the row. Here's an example of what the data looks like, there are several other columns but these are the columns of interest for my question:</p>
<pre><code> JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
0 0 5 5 0 5 5 5 5 0 0 0
</code></pre>
<p>this is what I have so far:</p>
<pre><code> import pandas as pd
import os
os.chdir('C:\\users\\vroland\\desktop\\RR_WMD\\WUdata')
fout=open("WUinput.csv","a")
#read water use file
df=pd.read_csv("WUtest.csv")
#Header & months with zero values
cols=df.columns
#Boolean array of columns with zero values
bt=df.apply(lambda x: x==0)
#List months with zero values
zar=bt.apply(lambda x:list(cols[x.values]),axis=1)
</code></pre>
<p>I've tried a combination of ways including <code>if</code> statements, but i keep getting an error stating my conditional statement is ambiguous so I'm trying another route. So this is what i have now to go along with the block of code above:</p>
<pre><code> a=30
b=31
c=28
num_days=pd.DataFrame({'JAN':[b],'FEB':[c],'MAR':[b],'APR':[a],'MAY':[b],
'JUN':[a],'JUL':[b],'AUG':[b],'SEP':[a],'OCT':[b],
'NOV':[a],'DEC':[b]})
</code></pre>
<p>The idea is to use the values returned in <code>zar</code> to look up the appropriate day value in my data frame <code>num_days</code>. Return this value and calculate the total number of days with a value of zero. </p>
| 3 | 2016-09-30T17:00:50Z | 39,796,814 | <p>well, I would get rid of the "fout" line. You don't seem to write to that file, and it doesn't need to be open to use the "read_csv" feature of pandas. then you can go through each row and find what's zero, and what isn't</p>
<pre><code>returnArray = []
i=0
while i < len(df.values):
j=14 #since user only cares about column 14-26
while j < len(df.values[i]):
if df.values[i][j] == 0:
returnArray.append([i,j])
j=j+1
i=i+1
</code></pre>
| 0 | 2016-09-30T17:20:12Z | [
"python",
"pandas"
]
|
How would I count the number of days based on months with zero data? | 39,796,519 | <p>I'm writing a script in which I read in a csv with several columns and rows. I need the script to total the values in each column for a single row and return which columns have a value of zero for the row. Here's an example of what the data looks like, there are several other columns but these are the columns of interest for my question:</p>
<pre><code> JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
0 0 5 5 0 5 5 5 5 0 0 0
</code></pre>
<p>this is what I have so far:</p>
<pre><code> import pandas as pd
import os
os.chdir('C:\\users\\vroland\\desktop\\RR_WMD\\WUdata')
fout=open("WUinput.csv","a")
#read water use file
df=pd.read_csv("WUtest.csv")
#Header & months with zero values
cols=df.columns
#Boolean array of columns with zero values
bt=df.apply(lambda x: x==0)
#List months with zero values
zar=bt.apply(lambda x:list(cols[x.values]),axis=1)
</code></pre>
<p>I've tried a combination of ways including <code>if</code> statements, but i keep getting an error stating my conditional statement is ambiguous so I'm trying another route. So this is what i have now to go along with the block of code above:</p>
<pre><code> a=30
b=31
c=28
num_days=pd.DataFrame({'JAN':[b],'FEB':[c],'MAR':[b],'APR':[a],'MAY':[b],
'JUN':[a],'JUL':[b],'AUG':[b],'SEP':[a],'OCT':[b],
'NOV':[a],'DEC':[b]})
</code></pre>
<p>The idea is to use the values returned in <code>zar</code> to look up the appropriate day value in my data frame <code>num_days</code>. Return this value and calculate the total number of days with a value of zero. </p>
| 3 | 2016-09-30T17:00:50Z | 39,796,873 | <p>Consider the <code>pd.DataFrame</code> <code>df</code></p>
<pre><code>cols = ['JAN', 'FEB', 'MAR', 'APR',
'MAY', 'JUN', 'JUL', 'AUG',
'SEP', 'OCT', 'NOV', 'DEC']
df = pd.DataFrame(np.random.randint(0, 3, (10, 12)), columns=cols)
df
</code></pre>
<p><a href="http://i.stack.imgur.com/1iTj9.png" rel="nofollow"><img src="http://i.stack.imgur.com/1iTj9.png" alt="enter image description here"></a></p>
<hr>
<p>I'll use each rows evaluation of <code>row == 0</code> to be a boolean mask on the columns themselves. Use <code>list</code> to fit nicely back into a <code>pd.Series</code></p>
<pre><code>df.eq(0).apply(lambda x: list(df.columns[x]), 1)
0 [FEB, MAR, APR, NOV]
1 [FEB, OCT, NOV]
2 [JAN, APR, AUG, NOV, DEC]
3 [MAR, APR, SEP]
4 [MAY, JUN, NOV, DEC]
5 [APR, AUG, NOV]
6 [MAR, APR, JUN, OCT, NOV, DEC]
7 [JAN, FEB, APR, JUL, OCT, NOV, DEC]
8 [MAY, JUL, AUG, SEP, OCT]
9 [FEB, MAR, APR, JUN, AUG, SEP]
dtype: object
</code></pre>
<hr>
<p>To get the number of days</p>
<pre><code>days_in_month = pd.Series(dict(
JAN=31, FEB=28, MAR=31,
APR=30, MAY=31, JUN=30,
JUL=31, AUG=31, SEP=30,
OCT=31, NOV=30, DEC=31
))
df.eq(0).dot(days_in_month)
0 119
1 89
2 153
3 91
4 122
5 91
6 183
7 212
8 154
9 180
dtype: int64
</code></pre>
| 1 | 2016-09-30T17:23:36Z | [
"python",
"pandas"
]
|
Python how to sum a list | 39,796,664 | <p>I'm having trouble because I'm asking the user to input 6 numbers into a list and then total and average it depending on input from user. It's my HWK. Please help.</p>
<pre><code>x = 0
list = []
while x < 6:
user = int(input("Enter a number"))
list.append(user)
x = x + 1
numb = input("Do you want a total or average of numbers?")
numb1 = numb.lower
if numb1 == "total":
</code></pre>
| -2 | 2016-09-30T17:10:34Z | 39,800,096 | <p>Here is my answer:</p>
<pre><code>def numberTest():
global x, y, z
L1 = []
x = 0
y = 6
z = 1
while(x < 6):
try:
user = int(input("Enter {0} more number(s)".format(y)))
print("Your entered the number {0}".format(user))
x += 1
y -= 1
L1.append(user)
except ValueError:
print("That isn't a number please try again.")
while(z > 0):
numb = input("Type \"total\" for the total and \"average\"").lower()
if(numb == "total"):
a = sum(L1)
print("Your total is {0}".format(a))
z = 0
elif(numb == "average"):
b = sum(L1)/ len(L1)
print("Your average is {0}".format(round(b)))
z = 0
else:
print("Please try typing either \"total\" or \"average\".")
numberTest()
</code></pre>
<p>I tried this a couple of times and I know it works. If you are confused about parts of the code, I will add comments and answer further questions.</p>
| 0 | 2016-09-30T21:05:42Z | [
"python",
"list",
"sum",
"average"
]
|
Why doesn't this python keyboard interrupt work? (in pycharm) | 39,796,689 | <p>My python try/except loop does not seem to trigger a keyboard interrupt when Ctrl + C is pressed while debugging my code in pycharm. My code look like this:</p>
<pre><code>numbers = []
loop = True
try:
# ===========SUBROUTINES==================
def help():
print("To view the list type 'view'"
"\n To add an item type 'add'"
"\n To remove an item type 'remove'"
"\n To exit type exit or Ctrl + c can be used at any time")
# =========SUBROUTENES END===============
while loop:
task = input("What do you want to do? Type \"help\" for help:- ")
if task == 'help':
help()
else:
print("Invalid return please try again.")
except KeyboardInterrupt:
exit()
</code></pre>
<p><strong>EDIT:</strong> There seems to be some problems with my slimmed down code working and not producing the same error. The full code can be viewed <a href="https://gist.github.com/shardros/61901ba8a70caf0a12b00b3a61b2a88e" rel="nofollow">here</a>. I have also re-slimed down the code (The code above) and it has produced the same error.</p>
| 2 | 2016-09-30T17:12:11Z | 39,796,898 | <p>If that comment doesn't solve your problem, (from @tdelaney) you need to have your shell window focused (meaning you've clicked on it when the program is running.) and then you can use <kbd>Control</kbd>+<kbd>C</kbd></p>
| 1 | 2016-09-30T17:25:04Z | [
"python",
"pycharm",
"try-except",
"keyboardinterrupt"
]
|
Why doesn't this python keyboard interrupt work? (in pycharm) | 39,796,689 | <p>My python try/except loop does not seem to trigger a keyboard interrupt when Ctrl + C is pressed while debugging my code in pycharm. My code look like this:</p>
<pre><code>numbers = []
loop = True
try:
# ===========SUBROUTINES==================
def help():
print("To view the list type 'view'"
"\n To add an item type 'add'"
"\n To remove an item type 'remove'"
"\n To exit type exit or Ctrl + c can be used at any time")
# =========SUBROUTENES END===============
while loop:
task = input("What do you want to do? Type \"help\" for help:- ")
if task == 'help':
help()
else:
print("Invalid return please try again.")
except KeyboardInterrupt:
exit()
</code></pre>
<p><strong>EDIT:</strong> There seems to be some problems with my slimmed down code working and not producing the same error. The full code can be viewed <a href="https://gist.github.com/shardros/61901ba8a70caf0a12b00b3a61b2a88e" rel="nofollow">here</a>. I have also re-slimed down the code (The code above) and it has produced the same error.</p>
| 2 | 2016-09-30T17:12:11Z | 39,796,979 | <p>Make sure the window is selected when you press ctrl+c. I just ran your program in IDLE and it worked perfectly for me.</p>
| 1 | 2016-09-30T17:31:16Z | [
"python",
"pycharm",
"try-except",
"keyboardinterrupt"
]
|
Why doesn't this python keyboard interrupt work? (in pycharm) | 39,796,689 | <p>My python try/except loop does not seem to trigger a keyboard interrupt when Ctrl + C is pressed while debugging my code in pycharm. My code look like this:</p>
<pre><code>numbers = []
loop = True
try:
# ===========SUBROUTINES==================
def help():
print("To view the list type 'view'"
"\n To add an item type 'add'"
"\n To remove an item type 'remove'"
"\n To exit type exit or Ctrl + c can be used at any time")
# =========SUBROUTENES END===============
while loop:
task = input("What do you want to do? Type \"help\" for help:- ")
if task == 'help':
help()
else:
print("Invalid return please try again.")
except KeyboardInterrupt:
exit()
</code></pre>
<p><strong>EDIT:</strong> There seems to be some problems with my slimmed down code working and not producing the same error. The full code can be viewed <a href="https://gist.github.com/shardros/61901ba8a70caf0a12b00b3a61b2a88e" rel="nofollow">here</a>. I have also re-slimed down the code (The code above) and it has produced the same error.</p>
| 2 | 2016-09-30T17:12:11Z | 39,797,021 | <p>Here is working normally, since i put a variable "x" in your code and i use <em>tabs</em> instead <em>spaces</em>.</p>
<pre><code>try:
def help():
print("Help.")
def doStuff():
print("Doing Stuff")
while True:
x = int(input())
if x == 1:
help()
elif x == 2:
doStuff()
else:
exit()
except KeyboardInterrupt:
exit()
</code></pre>
| 1 | 2016-09-30T17:33:27Z | [
"python",
"pycharm",
"try-except",
"keyboardinterrupt"
]
|
Why doesn't this python keyboard interrupt work? (in pycharm) | 39,796,689 | <p>My python try/except loop does not seem to trigger a keyboard interrupt when Ctrl + C is pressed while debugging my code in pycharm. My code look like this:</p>
<pre><code>numbers = []
loop = True
try:
# ===========SUBROUTINES==================
def help():
print("To view the list type 'view'"
"\n To add an item type 'add'"
"\n To remove an item type 'remove'"
"\n To exit type exit or Ctrl + c can be used at any time")
# =========SUBROUTENES END===============
while loop:
task = input("What do you want to do? Type \"help\" for help:- ")
if task == 'help':
help()
else:
print("Invalid return please try again.")
except KeyboardInterrupt:
exit()
</code></pre>
<p><strong>EDIT:</strong> There seems to be some problems with my slimmed down code working and not producing the same error. The full code can be viewed <a href="https://gist.github.com/shardros/61901ba8a70caf0a12b00b3a61b2a88e" rel="nofollow">here</a>. I have also re-slimed down the code (The code above) and it has produced the same error.</p>
| 2 | 2016-09-30T17:12:11Z | 39,797,131 | <p>From your screen shot it appears that you are running this code in an IDE. The thing about IDEs is that they are not quite the same as running normally, especially when it comes to handling of keyboard characters. The way you press ctrl-c, your IDE thinks you want to copy text. The python program never sees the character. Pehaps it brings up a separate window when running? Then you would select that window before ctrl-c.</p>
| 2 | 2016-09-30T17:40:37Z | [
"python",
"pycharm",
"try-except",
"keyboardinterrupt"
]
|
Append 1D numpy array to file with new element in new line | 39,796,811 | <p>I have a number of numpy arrays which I generate iteratively. I want to save each array to a file. I then generate the next array and append it to the file and so forth (if I did it in one go I would use too much memory). How do I best do that? Is there a way of making us of numpy functions such as e.g. <code>numpy.savetxt</code>? (I couldn't find an append option for that function.)</p>
<p>My current code is:</p>
<pre><code>with open('paths.dat','w') as output:
for i in range(len(hist[0])):
amount = hist[0][i].astype(int)
array = hist[1][i] * np.ones(amount)
for value in array:
output.write(str(value)+'\n')
</code></pre>
| 0 | 2016-09-30T17:20:07Z | 39,797,820 | <p>I would recommend using HDF5. They are very fast for IO.
Here is how you write your data:</p>
<pre><code>import numpy as np
import tables
fname = 'myOutput.h5'
length = 100 # your data length
my_data_generator = xrange(length) # Your data comes here instead of the xrange
filters = tables.Filters(complib='blosc', complevel=5) # you could change these
h5file = tables.open_file(fname, mode='w', title='yourTitle', filters=filters)
group = h5file.create_group(h5file.root, 'MyData', 'MyData')
x_atom = tables.Float32Atom()
x = h5file.create_carray(group, 'X', atom=x_atom, title='myTitle',
shape=(length,), filters=filters)
# this is a basic example. It will be faster if you write it in larger chunks in your real code
# like x[start1:end1] = elements[start2:end2]
for element_i, element in enumerate(my_data_generator):
x[element_i] = element
h5file.flush()
h5file.close()
</code></pre>
<p>For reading it use:</p>
<pre><code>h5file = tables.open_file(fname, mode='r')
x = h5file.get_node('/MyData/X')
print x[:10]
</code></pre>
<p>The result:</p>
<pre><code>marray([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], dtype=float32)
</code></pre>
| 0 | 2016-09-30T18:25:40Z | [
"python",
"arrays",
"numpy",
"file-io"
]
|
Append 1D numpy array to file with new element in new line | 39,796,811 | <p>I have a number of numpy arrays which I generate iteratively. I want to save each array to a file. I then generate the next array and append it to the file and so forth (if I did it in one go I would use too much memory). How do I best do that? Is there a way of making us of numpy functions such as e.g. <code>numpy.savetxt</code>? (I couldn't find an append option for that function.)</p>
<p>My current code is:</p>
<pre><code>with open('paths.dat','w') as output:
for i in range(len(hist[0])):
amount = hist[0][i].astype(int)
array = hist[1][i] * np.ones(amount)
for value in array:
output.write(str(value)+'\n')
</code></pre>
| 0 | 2016-09-30T17:20:07Z | 39,799,398 | <p>You could pass the open file (handle) to <code>savetxt</code></p>
<pre><code>with open('paths.dat','w') as output:
for i in range(len(hist[0])):
amount = hist[0][i].astype(int)
myArray = hist[1][i] * np.ones(amount)
np.savetxt(output, myArray, delimiter=',', fmt='%10f')
</code></pre>
<p><code>np.savetxt</code> opens the file if given a name, otherwise it used the file.</p>
<p>Then iterates on the rows of the array and writes them</p>
<pre><code>for row in myArray:
f.write(fmt % tuple(row))
</code></pre>
<p>where <code>fmt</code> is the string you give, or one that is replicated to match the number of columns in your array.</p>
| 1 | 2016-09-30T20:12:14Z | [
"python",
"arrays",
"numpy",
"file-io"
]
|
Using .apply() in Sframes to manipulate multiple columns of each row | 39,796,839 | <p>I have an SFrame with the columns Date1 and Date2.</p>
<p>I am trying to use <code>.apply()</code> to find the datediff between Date1 and Date2, but I can't figure out how to use the other argument.</p>
<p>Ideally something like </p>
<pre><code>frame['new_col'] = frame['Date1'].apply(lambda x: datediff(x,frame('Date2')))
</code></pre>
| 0 | 2016-09-30T17:21:49Z | 39,822,429 | <p>You can directly take the difference between the dates in column <code>Date2</code> and those in <code>Date1</code> by just subtracting <code>frame['Date1']</code> from <code>frame['Date2']</code>. That, for some reason, returns the number of seconds between the two dates (only tested with python's <code>datetime</code> objects), which you can convert into <em>number of days</em> with simple arithmetics:</p>
<pre><code>from sframe import SFrame
from datetime import datetime, timedelta
mydict = {'Date1':[datetime.now(), datetime.now()+timedelta(2)],
'Date2':[datetime.now()+timedelta(10), datetime.now()+timedelta(17)]}
frame = SFrame(mydict)
frame['new_col'] = (frame['Date2'] - frame['Date1']).apply(lambda x: x//(60*60*24))
</code></pre>
<p>Output:</p>
<pre><code>+----------------------------+----------------------------+---------+
| Date1 | Date2 | new_col |
+----------------------------+----------------------------+---------+
| 2016-10-02 21:12:14.712556 | 2016-10-12 21:12:14.712574 | 10.0 |
| 2016-10-04 21:12:14.712567 | 2016-10-19 21:12:14.712576 | 15.0 |
+----------------------------+----------------------------+---------+
</code></pre>
| 0 | 2016-10-02T22:34:51Z | [
"python",
"sframe"
]
|
Regular Expression Matching First Non-Repeated Character | 39,796,852 | <p><strong>TL;DR</strong></p>
<p><code>re.search("(.)(?!.*\1)", text).group()</code> doesn't match the first non-repeating character contained in text (it always returns a character at or before the first non-repeated character, or before the end of the string if there are no non-repeated characters. My understanding is that re.search() should return None if there were no matches).
I'm only interested in understanding why this regex is not working as intended using the Python <code>re</code> module, not in any other method of solving the problem</p>
<p><strong>Full Background</strong></p>
<p>The problem description comes from <a href="https://www.codeeval.com/open_challenges/12/">https://www.codeeval.com/open_challenges/12/</a>. I've already solved this problem using a non-regex method, but revisited it to expand my understanding of Python's <code>re</code> module.
The regular expressions i thought would work (named vs unnamed backreferences) are: </p>
<p><code>(?P<letter>.)(?!.*(?P=letter))</code> and <code>(.)(?!.*\1)</code> (same results in python2 and python3)</p>
<p>My entire program looks like this</p>
<pre><code>import re
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
print(re.search("(?P<letter>.)(?!.*(?P=letter))",
test.strip()
).group()
)
</code></pre>
<p>and some input/output pairs are:</p>
<pre><code>rain | r
teetthing | e
cardiff | c
kangaroo | k
god | g
newtown | e
taxation | x
refurbished | f
substantially | u
</code></pre>
<p>According to what I've read at <a href="https://docs.python.org/2/library/re.html">https://docs.python.org/2/library/re.html</a>:</p>
<ul>
<li><code>(.)</code> creates a named group that matches any character and allows later backreferences to it as <code>\1</code>. </li>
<li><code>(?!...)</code> is a negative lookahead which restricts matches to cases where <code>...</code> does not match.</li>
<li><code>.*\1</code> means any number (including zero) of characters followed by whatever was matched by <code>(.)</code> earlier</li>
<li><code>re.search(pattern, string)</code> returns only the first location where the regex pattern produces a match (and would return None if no match could be found)</li>
<li><code>.group()</code> is equivalent to <code>.group(0)</code> which returns the entire match</li>
</ul>
<p>I think these pieces together should solve the stated problem, and it does work like I think it should for most inputs, but failed on <code>teething</code>. Throwing similar problems at it reveals that it seems to ignore repeated characters if they are consecutive:</p>
<pre><code>tooth | o # fails on consecutive repeated characters
aardvark | d # but does ok if it sees them later
aah | a # verified last one didn't work just because it was at start
heh | e # but it works for this one
hehe | h # What? It thinks h matches (lookahead maybe doesn't find "heh"?)
heho | e # but it definitely finds "heh" and stops "h" from matching here
hahah | a # so now it won't match h but will match a
hahxyz | a # but it realizes there are 2 h characters here...
hahxyza | h # ... Ok time for StackOverflow
</code></pre>
<p>I know lookbehind and negative lookbehind are limited to 3-character-max fixed length strings, and cannot contain backreferences even if they evaluate to a fixed length string, but I didn't see the documentation specify any restrictions on negative lookahead.</p>
| 27 | 2016-09-30T17:22:24Z | 39,796,953 | <p>Well let's take your <code>tooth</code> example - here is what the regex-engine does (a lot simplified for better understanding)</p>
<p>Start with <code>t</code> then look ahead in the string - and fail the lookahead, as there is another <code>t</code>.</p>
<pre><code>tooth
^ °
</code></pre>
<p>Next take <code>o</code>, look ahead in the string - and fail, as there is another <code>o</code>.</p>
<pre><code>tooth
^°
</code></pre>
<p>Next take the second <code>o</code>, look ahead in the string - no other <code>o</code> present - match it, return it, work done.</p>
<pre><code>tooth
^
</code></pre>
<p>So your regex doesn't match the first unrepeated character, but the first one, that has no further repetitions towards the end of the string.</p>
| 14 | 2016-09-30T17:29:38Z | [
"python",
"regex",
"regex-lookarounds"
]
|
Regular Expression Matching First Non-Repeated Character | 39,796,852 | <p><strong>TL;DR</strong></p>
<p><code>re.search("(.)(?!.*\1)", text).group()</code> doesn't match the first non-repeating character contained in text (it always returns a character at or before the first non-repeated character, or before the end of the string if there are no non-repeated characters. My understanding is that re.search() should return None if there were no matches).
I'm only interested in understanding why this regex is not working as intended using the Python <code>re</code> module, not in any other method of solving the problem</p>
<p><strong>Full Background</strong></p>
<p>The problem description comes from <a href="https://www.codeeval.com/open_challenges/12/">https://www.codeeval.com/open_challenges/12/</a>. I've already solved this problem using a non-regex method, but revisited it to expand my understanding of Python's <code>re</code> module.
The regular expressions i thought would work (named vs unnamed backreferences) are: </p>
<p><code>(?P<letter>.)(?!.*(?P=letter))</code> and <code>(.)(?!.*\1)</code> (same results in python2 and python3)</p>
<p>My entire program looks like this</p>
<pre><code>import re
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
print(re.search("(?P<letter>.)(?!.*(?P=letter))",
test.strip()
).group()
)
</code></pre>
<p>and some input/output pairs are:</p>
<pre><code>rain | r
teetthing | e
cardiff | c
kangaroo | k
god | g
newtown | e
taxation | x
refurbished | f
substantially | u
</code></pre>
<p>According to what I've read at <a href="https://docs.python.org/2/library/re.html">https://docs.python.org/2/library/re.html</a>:</p>
<ul>
<li><code>(.)</code> creates a named group that matches any character and allows later backreferences to it as <code>\1</code>. </li>
<li><code>(?!...)</code> is a negative lookahead which restricts matches to cases where <code>...</code> does not match.</li>
<li><code>.*\1</code> means any number (including zero) of characters followed by whatever was matched by <code>(.)</code> earlier</li>
<li><code>re.search(pattern, string)</code> returns only the first location where the regex pattern produces a match (and would return None if no match could be found)</li>
<li><code>.group()</code> is equivalent to <code>.group(0)</code> which returns the entire match</li>
</ul>
<p>I think these pieces together should solve the stated problem, and it does work like I think it should for most inputs, but failed on <code>teething</code>. Throwing similar problems at it reveals that it seems to ignore repeated characters if they are consecutive:</p>
<pre><code>tooth | o # fails on consecutive repeated characters
aardvark | d # but does ok if it sees them later
aah | a # verified last one didn't work just because it was at start
heh | e # but it works for this one
hehe | h # What? It thinks h matches (lookahead maybe doesn't find "heh"?)
heho | e # but it definitely finds "heh" and stops "h" from matching here
hahah | a # so now it won't match h but will match a
hahxyz | a # but it realizes there are 2 h characters here...
hahxyza | h # ... Ok time for StackOverflow
</code></pre>
<p>I know lookbehind and negative lookbehind are limited to 3-character-max fixed length strings, and cannot contain backreferences even if they evaluate to a fixed length string, but I didn't see the documentation specify any restrictions on negative lookahead.</p>
| 27 | 2016-09-30T17:22:24Z | 39,796,971 | <p>The reason why your regex is not working is that it will not match a character that is <em>followed</em> by the same character, but there is nothing to prevent it from matching a character that isn't <em>followed</em> by the same character, <em>even if</em> it is preceded by the same character.</p>
| 3 | 2016-09-30T17:30:49Z | [
"python",
"regex",
"regex-lookarounds"
]
|
Regular Expression Matching First Non-Repeated Character | 39,796,852 | <p><strong>TL;DR</strong></p>
<p><code>re.search("(.)(?!.*\1)", text).group()</code> doesn't match the first non-repeating character contained in text (it always returns a character at or before the first non-repeated character, or before the end of the string if there are no non-repeated characters. My understanding is that re.search() should return None if there were no matches).
I'm only interested in understanding why this regex is not working as intended using the Python <code>re</code> module, not in any other method of solving the problem</p>
<p><strong>Full Background</strong></p>
<p>The problem description comes from <a href="https://www.codeeval.com/open_challenges/12/">https://www.codeeval.com/open_challenges/12/</a>. I've already solved this problem using a non-regex method, but revisited it to expand my understanding of Python's <code>re</code> module.
The regular expressions i thought would work (named vs unnamed backreferences) are: </p>
<p><code>(?P<letter>.)(?!.*(?P=letter))</code> and <code>(.)(?!.*\1)</code> (same results in python2 and python3)</p>
<p>My entire program looks like this</p>
<pre><code>import re
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
print(re.search("(?P<letter>.)(?!.*(?P=letter))",
test.strip()
).group()
)
</code></pre>
<p>and some input/output pairs are:</p>
<pre><code>rain | r
teetthing | e
cardiff | c
kangaroo | k
god | g
newtown | e
taxation | x
refurbished | f
substantially | u
</code></pre>
<p>According to what I've read at <a href="https://docs.python.org/2/library/re.html">https://docs.python.org/2/library/re.html</a>:</p>
<ul>
<li><code>(.)</code> creates a named group that matches any character and allows later backreferences to it as <code>\1</code>. </li>
<li><code>(?!...)</code> is a negative lookahead which restricts matches to cases where <code>...</code> does not match.</li>
<li><code>.*\1</code> means any number (including zero) of characters followed by whatever was matched by <code>(.)</code> earlier</li>
<li><code>re.search(pattern, string)</code> returns only the first location where the regex pattern produces a match (and would return None if no match could be found)</li>
<li><code>.group()</code> is equivalent to <code>.group(0)</code> which returns the entire match</li>
</ul>
<p>I think these pieces together should solve the stated problem, and it does work like I think it should for most inputs, but failed on <code>teething</code>. Throwing similar problems at it reveals that it seems to ignore repeated characters if they are consecutive:</p>
<pre><code>tooth | o # fails on consecutive repeated characters
aardvark | d # but does ok if it sees them later
aah | a # verified last one didn't work just because it was at start
heh | e # but it works for this one
hehe | h # What? It thinks h matches (lookahead maybe doesn't find "heh"?)
heho | e # but it definitely finds "heh" and stops "h" from matching here
hahah | a # so now it won't match h but will match a
hahxyz | a # but it realizes there are 2 h characters here...
hahxyza | h # ... Ok time for StackOverflow
</code></pre>
<p>I know lookbehind and negative lookbehind are limited to 3-character-max fixed length strings, and cannot contain backreferences even if they evaluate to a fixed length string, but I didn't see the documentation specify any restrictions on negative lookahead.</p>
| 27 | 2016-09-30T17:22:24Z | 39,818,123 | <p>Regular expressions are not optimal for the task even if you use alternative implementations of re that do not limit lookbehind by fixed length strings (such as Matthew Barnett's regex).</p>
<p>The easiest way is to count occurrences of letters and print the first one with frequency equal to 1:</p>
<pre><code>import sys
from collections import Counter, OrderedDict
# Counter that remembers that remembers the order entries were added
class OrderedCounter(Counter, OrderedDict):
pass
# Calling next() once only gives the first entry
first=next
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
lettfreq = OrderedCounter(test)
print(first((l for l in lettfreq if lettfreq[l] == 1)))
</code></pre>
| 5 | 2016-10-02T14:42:39Z | [
"python",
"regex",
"regex-lookarounds"
]
|
Regular Expression Matching First Non-Repeated Character | 39,796,852 | <p><strong>TL;DR</strong></p>
<p><code>re.search("(.)(?!.*\1)", text).group()</code> doesn't match the first non-repeating character contained in text (it always returns a character at or before the first non-repeated character, or before the end of the string if there are no non-repeated characters. My understanding is that re.search() should return None if there were no matches).
I'm only interested in understanding why this regex is not working as intended using the Python <code>re</code> module, not in any other method of solving the problem</p>
<p><strong>Full Background</strong></p>
<p>The problem description comes from <a href="https://www.codeeval.com/open_challenges/12/">https://www.codeeval.com/open_challenges/12/</a>. I've already solved this problem using a non-regex method, but revisited it to expand my understanding of Python's <code>re</code> module.
The regular expressions i thought would work (named vs unnamed backreferences) are: </p>
<p><code>(?P<letter>.)(?!.*(?P=letter))</code> and <code>(.)(?!.*\1)</code> (same results in python2 and python3)</p>
<p>My entire program looks like this</p>
<pre><code>import re
import sys
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
print(re.search("(?P<letter>.)(?!.*(?P=letter))",
test.strip()
).group()
)
</code></pre>
<p>and some input/output pairs are:</p>
<pre><code>rain | r
teetthing | e
cardiff | c
kangaroo | k
god | g
newtown | e
taxation | x
refurbished | f
substantially | u
</code></pre>
<p>According to what I've read at <a href="https://docs.python.org/2/library/re.html">https://docs.python.org/2/library/re.html</a>:</p>
<ul>
<li><code>(.)</code> creates a named group that matches any character and allows later backreferences to it as <code>\1</code>. </li>
<li><code>(?!...)</code> is a negative lookahead which restricts matches to cases where <code>...</code> does not match.</li>
<li><code>.*\1</code> means any number (including zero) of characters followed by whatever was matched by <code>(.)</code> earlier</li>
<li><code>re.search(pattern, string)</code> returns only the first location where the regex pattern produces a match (and would return None if no match could be found)</li>
<li><code>.group()</code> is equivalent to <code>.group(0)</code> which returns the entire match</li>
</ul>
<p>I think these pieces together should solve the stated problem, and it does work like I think it should for most inputs, but failed on <code>teething</code>. Throwing similar problems at it reveals that it seems to ignore repeated characters if they are consecutive:</p>
<pre><code>tooth | o # fails on consecutive repeated characters
aardvark | d # but does ok if it sees them later
aah | a # verified last one didn't work just because it was at start
heh | e # but it works for this one
hehe | h # What? It thinks h matches (lookahead maybe doesn't find "heh"?)
heho | e # but it definitely finds "heh" and stops "h" from matching here
hahah | a # so now it won't match h but will match a
hahxyz | a # but it realizes there are 2 h characters here...
hahxyza | h # ... Ok time for StackOverflow
</code></pre>
<p>I know lookbehind and negative lookbehind are limited to 3-character-max fixed length strings, and cannot contain backreferences even if they evaluate to a fixed length string, but I didn't see the documentation specify any restrictions on negative lookahead.</p>
| 27 | 2016-09-30T17:22:24Z | 39,890,983 |
<p><a href="http://stackoverflow.com/a/39796953/3764814">Sebastian's answer</a> already explains pretty well why your current attempt doesn't work.</p>
<h3>.NET</h3>
<p>Since <s>you're</s> <a href="http://stackoverflow.com/users/1020526/revo">revo</a> is interested in a .NET flavor workaround, the solution becomes trivial:</p>
<pre class="lang-none prettyprint-override"><code>(?<letter>.)(?!.*?\k<letter>)(?<!\k<letter>.+?)
</code></pre>
<p><a href="http://regexstorm.net/tester?p=(%3F%3Cletter%3E.)(%3F!.*%3F%5Ck%3Cletter%3E)(%3F%3C!%5Ck%3Cletter%3E.%2B%3F)&i=tooth%0D%0Aaardvark%0D%0Aaah%0D%0Aheh%0D%0Ahehe%0D%0Aheho%0D%0Ahahah%0D%0Ahahxyz%0D%0Ahahxyza" rel="nofollow">Demo link</a></p>
<p>This works because .NET supports <strong>variable-length lookbehinds</strong>. You can also get that result with Python (see below).</p>
<p>So for each letter <code>(?<letter>.)</code> we check:</p>
<ul>
<li>if it's repeated further in the input <code>(?!.*?\k<letter>)</code> </li>
<li>if it was already encountered before <code>(?<!\k<letter>.+?)</code><br>
(we have to skip the letter we're testing when going backwards, hence the <code>+</code>).</li>
</ul>
<hr>
<h3>Python</h3>
<p>The Python <a href="https://pypi.python.org/pypi/regex" rel="nofollow">regex module</a> also supports variable-length lookbehinds, so the regex above will work with a small syntactical change: you need to replace <code>\k</code> with <code>\g</code> (which is quite unfortunate as with this module <code>\g</code> is a group backreference, whereas with PCRE it's a recursion).</p>
<p>The regex is:</p>
<pre class="lang-none prettyprint-override"><code>(?<letter>.)(?!.*?\g<letter>)(?<!\g<letter>.+?)
</code></pre>
<p>And here's an example:</p>
<pre class="lang-none prettyprint-override"><code>$ python
Python 2.7.10 (default, Jun 1 2015, 18:05:38)
[GCC 4.9.2] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import regex
>>> regex.search(r'(?<letter>.)(?!.*?\g<letter>)(?<!\g<letter>.+?)', 'tooth')
<regex.Match object; span=(4, 5), match='h'>
</code></pre>
<hr>
<h3>PCRE</h3>
<p>Ok, now things start to get dirty: since PCRE doesn't support variable-length lookbehinds, we need to <em>somehow</em> remember whether a given letter was already encountered in the input or not.</p>
<p>Unfortunately, the regex engine doesn't provide random access memory support. The best we can get in terms of generic memory is a <em>stack</em> - but that's not sufficient for this purpose, as a stack only lets us access its topmost element.</p>
<p>If we accept to restrain ourselves to a given alphabet, we can abuse capturing groups for the purpose of storing flags. Let's see this on a limited alphabet of the three letters <code>abc</code>:</p>
<pre class="lang-none prettyprint-override"><code># Anchor the pattern
\A
# For each letter, test to see if it's duplicated in the input string
(?(?=[^a]*+a[^a]*a)(?<da>))
(?(?=[^b]*+b[^b]*b)(?<db>))
(?(?=[^c]*+c[^c]*c)(?<dc>))
# Skip any duplicated letter and throw it away
[a-c]*?\K
# Check if the next letter is a duplicate
(?:
(?(da)(*FAIL)|a)
| (?(db)(*FAIL)|b)
| (?(dc)(*FAIL)|c)
)
</code></pre>
<p>Here's how that works:</p>
<ul>
<li>First, the <code>\A</code> anchor ensures we'll process the input string only once</li>
<li>Then, for each letter <code>X</code> of our alphabet, we'll set up a <em>is duplicate</em> flag <code>dX</code>:
<ul>
<li>The conditional pattern <code>(?(cond)then|else)</code> is used there:
<ul>
<li>The condition is <code>(?=[^X]*+X[^X]*X)</code> which is true if the input string contains the letter <code>X</code> twice.</li>
<li>If the condition is true, the <em>then</em> clause is <code>(?<dX>)</code>, which is an empty capturing group that will match the empty string.</li>
<li>If the condition is false, the <code>dX</code> group won't be matched</li>
</ul></li>
<li>Next, we lazily skip valid letters from our alphabet: <code>[a-c]*?</code></li>
<li>And we throw them out in the final match with <code>\K</code></li>
<li>Now, we're trying to match <em>one</em> letter whose <code>dX</code> flag is <em>not</em> set. For this purpose, we'll do a conditional branch: <code>(?(dX)(*FAIL)|X)</code>
<ul>
<li>If <code>dX</code> was matched (meaning that <code>X</code> is a duplicated character), we <code>(*FAIL)</code>, forcing the engine to backtrack and try a different letter.</li>
<li>If <code>dX</code> was <em>not</em> matched, we try to match <code>X</code>. At this point, if this succeeds, we know that <code>X</code> is the first non-duplicated letter.</li>
</ul></li>
</ul></li>
</ul>
<p>That last part of the pattern could also be replaced with:</p>
<pre class="lang-none prettyprint-override"><code>(?:
a (*THEN) (?(da)(*FAIL))
| b (*THEN) (?(db)(*FAIL))
| c (*THEN) (?(dc)(*FAIL))
)
</code></pre>
<p>Which is <em>somewhat</em> more optimized. It matches the current letter <em>first</em> and only <em>then</em> checks if it's a duplicate.</p>
<p>The full pattern for the lowercase letters <code>a-z</code> looks like this:</p>
<pre class="lang-none prettyprint-override"><code># Anchor the pattern
\A
# For each letter, test to see if it's duplicated in the input string
(?(?=[^a]*+a[^a]*a)(?<da>))
(?(?=[^b]*+b[^b]*b)(?<db>))
(?(?=[^c]*+c[^c]*c)(?<dc>))
(?(?=[^d]*+d[^d]*d)(?<dd>))
(?(?=[^e]*+e[^e]*e)(?<de>))
(?(?=[^f]*+f[^f]*f)(?<df>))
(?(?=[^g]*+g[^g]*g)(?<dg>))
(?(?=[^h]*+h[^h]*h)(?<dh>))
(?(?=[^i]*+i[^i]*i)(?<di>))
(?(?=[^j]*+j[^j]*j)(?<dj>))
(?(?=[^k]*+k[^k]*k)(?<dk>))
(?(?=[^l]*+l[^l]*l)(?<dl>))
(?(?=[^m]*+m[^m]*m)(?<dm>))
(?(?=[^n]*+n[^n]*n)(?<dn>))
(?(?=[^o]*+o[^o]*o)(?<do>))
(?(?=[^p]*+p[^p]*p)(?<dp>))
(?(?=[^q]*+q[^q]*q)(?<dq>))
(?(?=[^r]*+r[^r]*r)(?<dr>))
(?(?=[^s]*+s[^s]*s)(?<ds>))
(?(?=[^t]*+t[^t]*t)(?<dt>))
(?(?=[^u]*+u[^u]*u)(?<du>))
(?(?=[^v]*+v[^v]*v)(?<dv>))
(?(?=[^w]*+w[^w]*w)(?<dw>))
(?(?=[^x]*+x[^x]*x)(?<dx>))
(?(?=[^y]*+y[^y]*y)(?<dy>))
(?(?=[^z]*+z[^z]*z)(?<dz>))
# Skip any duplicated letter and throw it away
[a-z]*?\K
# Check if the next letter is a duplicate
(?:
a (*THEN) (?(da)(*FAIL))
| b (*THEN) (?(db)(*FAIL))
| c (*THEN) (?(dc)(*FAIL))
| d (*THEN) (?(dd)(*FAIL))
| e (*THEN) (?(de)(*FAIL))
| f (*THEN) (?(df)(*FAIL))
| g (*THEN) (?(dg)(*FAIL))
| h (*THEN) (?(dh)(*FAIL))
| i (*THEN) (?(di)(*FAIL))
| j (*THEN) (?(dj)(*FAIL))
| k (*THEN) (?(dk)(*FAIL))
| l (*THEN) (?(dl)(*FAIL))
| m (*THEN) (?(dm)(*FAIL))
| n (*THEN) (?(dn)(*FAIL))
| o (*THEN) (?(do)(*FAIL))
| p (*THEN) (?(dp)(*FAIL))
| q (*THEN) (?(dq)(*FAIL))
| r (*THEN) (?(dr)(*FAIL))
| s (*THEN) (?(ds)(*FAIL))
| t (*THEN) (?(dt)(*FAIL))
| u (*THEN) (?(du)(*FAIL))
| v (*THEN) (?(dv)(*FAIL))
| w (*THEN) (?(dw)(*FAIL))
| x (*THEN) (?(dx)(*FAIL))
| y (*THEN) (?(dy)(*FAIL))
| z (*THEN) (?(dz)(*FAIL))
)
</code></pre>
<p>And here's the <a href="https://regex101.com/r/Mhwxog/1" rel="nofollow">demo on regex101</a>, complete with unit tests.</p>
<p>You can expand on this pattern if you need a larger alphabet, but obviously this is <em>not</em> a general-purpose solution. It's primarily of educational interest and should <em>not</em> be used for any serious application.</p>
<hr>
<p>For other flavors, you may try to tweak the pattern to replace PCRE features with simpler equivalents:</p>
<ul>
<li><code>\A</code> becomes <code>^</code></li>
<li><code>X (*THEN) (?(dX)(*FAIL))</code> can be replaced with <code>(?(dX)(?!)|X)</code></li>
<li>You may throw away the <code>\K</code> and replace the last noncapturnig group <code>(?:</code>...<code>)</code> with a named group like <code>(?<letter></code>...<code>)</code> and treat its content as the result.</li>
</ul>
<p>The only required but somewhat unusual construct is the conditional group <code>(?(cond)then|else)</code>.</p>
| 11 | 2016-10-06T08:19:28Z | [
"python",
"regex",
"regex-lookarounds"
]
|
Installing MoviePy for Python 3.2 with pip | 39,796,864 | <p>I am trying to install the Python module MoviePy onto my Raspberry Pi for use with Python 3.2.3 which came ready installed with the OS. I have tried every command line command that I can find and lots of possible permutations of certain words.</p>
<p>Following are the download instructions.
<a href="https://zulko.github.io/moviepy/install.html" rel="nofollow">https://zulko.github.io/moviepy/install.html</a></p>
<p>After much effort, I eventually managed to download pip and installed moviepy, but it was the Python 2.7 version. í ½í¸¡
I found a separate thing called pip3 and installed it using:</p>
<pre><code>sudo apt-get install python3-pip --fix-missing
</code></pre>
<p>It appeared to be successful.</p>
<p>Eventually I found a command that should work with Python 3.2:
pip-3.2 install moviepy
But it gave the error:</p>
<pre><code>Cannot fetch index base URL http://pypi.python.org/simple/
Could not find any downloads that satisfy the requirement moviepy
No distributions at all found for moviepy
Storing complete log in /home/Pi/.pip/pip.log
</code></pre>
<p>What do I do?
I have no knowledge of CLI at all...</p>
| 0 | 2016-09-30T17:23:00Z | 39,797,542 | <p>Do</p>
<pre><code>sudo pip install ez_setup
sudo pip install moviepy
</code></pre>
<p>If it says like pip not found type </p>
<pre><code>sudo apt-get install python
</code></pre>
<p>Python 3 is a little harder to setup so doing that command will give you 2.7
But there syntax is basicly the same.</p>
| 0 | 2016-09-30T18:08:02Z | [
"python",
"python-3.x",
"pip",
"moviepy"
]
|
Dynamic call to an Instance Variable | 39,796,880 | <p>I have a dynamic string based on the current file's extension called "extension"</p>
<pre><code>fileextension = os.path.splitext(file.filename)[1]
extension = fileextension.replace(".","")
</code></pre>
<p>Lets say extension = "pdf"</p>
<p>How would I be able to call the Ext.pdf() instance variable below?</p>
<pre><code>class Ext:
def pdf(self):
self.filetype = "pdf - Adobe Portable Document Format"
def txt(self):
self.filetype = "txt - ASCII text file"
Ext = Ext()
</code></pre>
<p>I have tried:</p>
<pre><code>Ext.filetype = getattr(Ext, extension)()
</code></pre>
<p>But this comes up with a blank entry</p>
| 2 | 2016-09-30T17:24:13Z | 39,796,947 | <p>You called the instance attribute correctly. To fix your issue do not assign the result to the <code>filetype</code> attribute:</p>
<pre><code>ext = Ext()
getattr(ext, extension)()
print(ext.filetype)
</code></pre>
<p>It did not work because you return <code>None</code> within <code>pdf()</code> and <code>txt()</code> method and assigned that to <code>filetype</code> attribute. </p>
<p>Note that I relabeled the instance of <code>Ext</code> to <code>ext</code> since it may be not a good idea to override a class definition by its instance. </p>
| 4 | 2016-09-30T17:29:11Z | [
"python"
]
|
How do you change a variable in a function to then be used in the main code? | 39,797,042 | <p>I am quite new to Python and I am having some trouble figuring out the following:</p>
<pre><code>import random
import sys
print("Welcome to this Maths quiz.")
playerName = str(input("Please enter your name: "))
playerAge = int(input("Please enter your age: "))
if playerAge < 11:
print("This quiz is not for your age.")
sys.exit(0)
else :
print("Great! Let's begin.\n")
quizQuestions = ["9(3+8)", "7+9*8", "(9+13)(9-5)", "50*25%", "104-4+5*20"]
quizAnswers = ["99", "79", "88", "12.5", "0"]
quizSync = list(zip(quizQuestions, quizAnswers))
random.shuffle(quizSync)
quizQuestions, quizAnswers = zip( * quizSync)
questionNumber = 1
quizScore = 0
def displayQuestion(quizQuestions, quizAnswers, questionNumber, quizScore):
print("Question " + str(questionNumber) + ": " + quizQuestions[questionNumber - 1] + "\n")
questionAnswer = str(input())
if questionAnswer == quizAnswers[questionNumber - 1]:
print("\nCorrect!\n")
quizScore += 1
else :
print("\nIncorrect! The answer is: " + quizAnswers[questionNumber - 1] + "\n")
while questionNumber < 6:
displayQuestion(quizQuestions, quizAnswers, questionNumber, quizScore)
questionNumber += 1
print("You have a total score of: "+str(quizScore))
</code></pre>
<p>I would like the variable "quizScore" in the function "displayQuestion" to increase by one if the player gets a question right. However, after the quiz is finished, the print function at the end always prints the score is 0 even if the player gets questions right.</p>
| 0 | 2016-09-30T17:34:52Z | 39,797,103 | <p>You have to declare it as a global variable inside the function so that it can modify the variable in the global scope</p>
<pre><code>def displayQuestion(quizQuestions, quizAnswers, questionNumber):
global quizScore
...
quizScore += 1
</code></pre>
<p>That being said, you should generally avoid global variables if you can and try to redesign your program to either pass the variables along as arguments and return values, or use a class to encapsulate the data.</p>
| 3 | 2016-09-30T17:38:31Z | [
"python",
"function",
"variables"
]
|
How do you change a variable in a function to then be used in the main code? | 39,797,042 | <p>I am quite new to Python and I am having some trouble figuring out the following:</p>
<pre><code>import random
import sys
print("Welcome to this Maths quiz.")
playerName = str(input("Please enter your name: "))
playerAge = int(input("Please enter your age: "))
if playerAge < 11:
print("This quiz is not for your age.")
sys.exit(0)
else :
print("Great! Let's begin.\n")
quizQuestions = ["9(3+8)", "7+9*8", "(9+13)(9-5)", "50*25%", "104-4+5*20"]
quizAnswers = ["99", "79", "88", "12.5", "0"]
quizSync = list(zip(quizQuestions, quizAnswers))
random.shuffle(quizSync)
quizQuestions, quizAnswers = zip( * quizSync)
questionNumber = 1
quizScore = 0
def displayQuestion(quizQuestions, quizAnswers, questionNumber, quizScore):
print("Question " + str(questionNumber) + ": " + quizQuestions[questionNumber - 1] + "\n")
questionAnswer = str(input())
if questionAnswer == quizAnswers[questionNumber - 1]:
print("\nCorrect!\n")
quizScore += 1
else :
print("\nIncorrect! The answer is: " + quizAnswers[questionNumber - 1] + "\n")
while questionNumber < 6:
displayQuestion(quizQuestions, quizAnswers, questionNumber, quizScore)
questionNumber += 1
print("You have a total score of: "+str(quizScore))
</code></pre>
<p>I would like the variable "quizScore" in the function "displayQuestion" to increase by one if the player gets a question right. However, after the quiz is finished, the print function at the end always prints the score is 0 even if the player gets questions right.</p>
| 0 | 2016-09-30T17:34:52Z | 39,797,897 | <p>Although this won't be the shortest answer, which is to use another global variable. It instead will show you how to avoid using global variables (<a href="http://c2.com/cgi/wiki?GlobalVariablesConsideredHarmful" rel="nofollow">which are considered harmful</a>) by using <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="nofollow">Object Oriented Programming (OOP)</a>. To accomplish this, most of the code in your question can be encapsulated into a single class named <code>MathQuiz</code> below.</p>
<p>Besides getting rid of almost all global variables, it also provides a usable template for you to create any number of independent math quizzes.</p>
<pre><code>import random
import sys
class MathQuiz:
def __init__(self, questions, answers):
quizSync = list(zip(questions, answers))
random.shuffle(quizSync)
self.quizQuestions, self.quizAnswers = zip(*quizSync)
self.quizScore = 0
print("Welcome to this Maths quiz.")
self.playerName = str(input("Please enter your name: "))
self.playerAge = int(input("Please enter your age: "))
if self.playerAge > 10:
print("Great! Let's begin.\n")
else :
print("This quiz is not for your age.")
sys.exit(0)
def run(self):
for questionNumber in range(len(self.quizQuestions)):
self._displayQuestion(questionNumber)
print("You have a total score of: " + str(self.quizScore))
def _displayQuestion(self, questionNumber):
print("Question " + str(questionNumber) + ": "
+ self.quizQuestions[questionNumber-1]
+ "\n")
questionAnswer = str(input())
if questionAnswer == self.quizAnswers[questionNumber-1]:
print("\nCorrect!\n")
self.quizScore += 1
else :
print("\nIncorrect! The answer is: "
+ self.quizAnswers[questionNumber-1]
+ "\n")
quiz = MathQuiz(["9(3+8)", "7+9*8", "(9+13)(9-5)", "50*25%", "104-4+5*20"],
["99", "79", "88", "12.5", "0"])
quiz.run()
</code></pre>
| 0 | 2016-09-30T18:29:56Z | [
"python",
"function",
"variables"
]
|
How to make Q lookups in django look for multiple values | 39,797,090 | <p>Currently I have a very simple search option which goes through my pages and looks up through several fields for requested query. If I input a single word in it it works just fine, however if I input multiple words in search query, I get nothing, even if a single page contains all attributes. For example if I search for <code>test admin</code>, I will not get empty query, even though there's a page with title test, with content test and author admin. Is there a way to expand the search to look up each word in search query individually?</p>
<pre><code># Fetch all pages and sort them alphabetically
queryset = Page.objects.all().filter(archived=False).order_by("title")
# Get search query if applicable
query = request.GET.get("q")
if query:
queryset = queryset.filter(
Q(title__icontains=query) |
Q(content__icontains=query) |
Q(user__username__icontains=query) |
Q(user__first_name__icontains=query) |
Q(user__last_name__icontains=query)
).distinct()
</code></pre>
| 0 | 2016-09-30T17:37:57Z | 39,797,874 | <p>You're asking for something like the following, where you filter by each individual word in the query:</p>
<pre><code>import operator
queryset = Page.objects.all().filter(archived=False).order_by("title")
query = request.GET.get("q")
if query:
words = query.split()
fields = ["title__icontains", "content__icontains", "user__username__contains",
"user__first_name__icontains", "user__last_name__icontains"]
q_expression = [Q(f,w) for f in fields for w in words]
queryset = queryset.filter(reduce(operator.or_, q_expression))\
.distinct()
</code></pre>
<p>However, at this point doing search this way gets a little bit messy. If your app grows and you need to search over several models, consider looking into an external search package such as <a href="http://haystacksearch.org/" rel="nofollow">Haystack</a>.</p>
| 1 | 2016-09-30T18:28:48Z | [
"python",
"django",
"search",
"django-q"
]
|
Need uppate SQL in SQL within table | 39,797,096 | <p>I have 2 columns in my table <code>Office</code> (<code>Cust_id</code>, <code>customer</code>)</p>
<p>The data is like below, I want to update the <code>cust_id</code> for the customer who have nulls, because I got in late the <code>cust_id</code> in the table ,</p>
<p>EX: I need an update script to search the customer who has null <code>cust_id</code> and search the <code>cust_id</code> and update
Here DDD customers (<code>cust_id = 4</code>) so i need a script to update that </p>
<pre><code>cust_id, Customer
1 AAA
2 BBB
3 CCC
null DDD
null EEE
4 DDD
5 CCC
7 EEE
</code></pre>
| 0 | 2016-09-30T17:38:04Z | 39,797,233 | <p>Use <code>UPDATE</code> with a self-JOIN:</p>
<pre><code>UPDATE Office AS o1
JOIN Office AS o2 ON o1.Customer = o2.Customer
SET o1.cust_id = o2.cust_id
WHERE o1.cust_id IS NULL
AND o2.cust_id IS NOT NULL
</code></pre>
| 0 | 2016-09-30T17:47:14Z | [
"python"
]
|
Turn pandas series to series of lists or numpy array to array of lists | 39,797,206 | <p>I have a series <code>s</code></p>
<pre><code>s = pd.Series([1, 2])
</code></pre>
<p>What is an efficient way to make <code>s</code> look like</p>
<pre><code>0 [1]
1 [2]
dtype: object
</code></pre>
| 1 | 2016-09-30T17:45:54Z | 39,797,310 | <p>This does it: </p>
<pre><code>import numpy as np
np.array([[a] for a in s],dtype=object)
array([[1],
[2]], dtype=object)
</code></pre>
| 1 | 2016-09-30T17:51:52Z | [
"python",
"pandas",
"numpy"
]
|
Turn pandas series to series of lists or numpy array to array of lists | 39,797,206 | <p>I have a series <code>s</code></p>
<pre><code>s = pd.Series([1, 2])
</code></pre>
<p>What is an efficient way to make <code>s</code> look like</p>
<pre><code>0 [1]
1 [2]
dtype: object
</code></pre>
| 1 | 2016-09-30T17:45:54Z | 39,797,632 | <p>If you want the result to still be a pandas <code>Series</code> you can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>apply</code></a> method :</p>
<pre><code>In [1]: import pandas as pd
In [2]: s = pd.Series([1, 2])
In [3]: s.apply(lambda x: [x])
Out[3]:
0 [1]
1 [2]
dtype: object
</code></pre>
| 2 | 2016-09-30T18:14:29Z | [
"python",
"pandas",
"numpy"
]
|
Turn pandas series to series of lists or numpy array to array of lists | 39,797,206 | <p>I have a series <code>s</code></p>
<pre><code>s = pd.Series([1, 2])
</code></pre>
<p>What is an efficient way to make <code>s</code> look like</p>
<pre><code>0 [1]
1 [2]
dtype: object
</code></pre>
| 1 | 2016-09-30T17:45:54Z | 39,797,640 | <p>Adjusting atomh33ls' answer, here's a series of lists:</p>
<pre><code>output = pd.Series([[a] for a in s])
type(output)
>> pandas.core.series.Series
type(output[0])
>> list
</code></pre>
<p>Timings for a selection of the suggestions:</p>
<pre><code>import numpy as np, pandas as pd
s = pd.Series(np.random.randint(1,10,1000))
>> %timeit pd.Series(np.vstack(s.values).tolist())
100 loops, best of 3: 3.2 ms per loop
>> %timeit pd.Series([[a] for a in s])
1000 loops, best of 3: 393 µs per loop
>> %timeit s.apply(lambda x: [x])
1000 loops, best of 3: 473 µs per loop
</code></pre>
| 1 | 2016-09-30T18:15:10Z | [
"python",
"pandas",
"numpy"
]
|
Turn pandas series to series of lists or numpy array to array of lists | 39,797,206 | <p>I have a series <code>s</code></p>
<pre><code>s = pd.Series([1, 2])
</code></pre>
<p>What is an efficient way to make <code>s</code> look like</p>
<pre><code>0 [1]
1 [2]
dtype: object
</code></pre>
| 1 | 2016-09-30T17:45:54Z | 39,798,234 | <p>Here's one approach that extracts into array and extends to <code>2D</code> by introducing a new axis with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/arrays.indexing.html#numpy.newaxis" rel="nofollow"><code>None/np.newaxis</code></a> -</p>
<pre><code>pd.Series(s.values[:,None].tolist())
</code></pre>
<p>Here's a similar one, but extends to <code>2D</code> by reshaping -</p>
<pre><code>pd.Series(s.values.reshape(-1,1).tolist())
</code></pre>
<p>Runtime test using <a href="http://stackoverflow.com/a/39797640/3293881"><code>@P-robot's setup</code></a> -</p>
<pre><code>In [43]: s = pd.Series(np.random.randint(1,10,1000))
In [44]: %timeit pd.Series(np.vstack(s.values).tolist()) # @Nickil Maveli's soln
100 loops, best of 3: 5.77 ms per loop
In [45]: %timeit pd.Series([[a] for a in s]) # @P-robot's soln
1000 loops, best of 3: 412 µs per loop
In [46]: %timeit s.apply(lambda x: [x]) # @mgc's soln
1000 loops, best of 3: 551 µs per loop
In [47]: %timeit pd.Series(s.values[:,None].tolist()) # Approach1
1000 loops, best of 3: 307 µs per loop
In [48]: %timeit pd.Series(s.values.reshape(-1,1).tolist()) # Approach2
1000 loops, best of 3: 306 µs per loop
</code></pre>
| 4 | 2016-09-30T18:50:48Z | [
"python",
"pandas",
"numpy"
]
|
Playing music on loop until a key is released. Python | 39,797,210 | <p>I'm making a little GUI with python, using cocos2d and pyglet modules. The GUI should play a sound while the "h" is pressed and stop when it is released. The problem here is that I can't find a solution to this. After searching this site I've found this question - <a href="http://stackoverflow.com/questions/27391240/how-to-play-music-continuously-in-pyglet">How to play music continuously in pyglet</a>, the problem with this one is that I can't get the sound to stop after it starts. </p>
<p>EDIT: I found a way to play the sound until keyrelease, but ran into another problem</p>
<p>Right now the code that is supposed to play the music looks like this:</p>
<pre><code>class Heartbeat (cocos.layer.Layer):
is_event_handler=True
def __init__ (self):
super(Heartbeat, self).__init__()
global loop, music, player
music = pyglet.media.load('long_beep.wav')
loop=pyglet.media.SourceGroup(music.audio_format, None)
player=pyglet.media.Player()
loop.queue(music)
player.queue(loop)
def on_key_press(self, key, modifiers):
if chr(key)=='h':
loop.loop=True
player.play()
def on_key_release (self, key, modifiers):
if chr(key)=="h":
loop.loop=False
</code></pre>
<p>This code works when the "h" key is pressed and held down for the first time, it doesn't work in subsequent attempts. Python doesn't raise an exception, it just seems to ignore "h" key presses that occur after the first release.</p>
<p>NOTE: The statement - <code>if chr(key)=="h"</code> may not be the best solution to keypress handling, but I'm relitively new to using cocos2d and pyglet modules.</p>
| 0 | 2016-09-30T17:46:03Z | 39,807,492 | <p>Nevermind, I have figured this out, all I had to do was move the line <code>player.queue(loop)</code> from the initialization function to the function that handles keypresses. The updated code looks like this: </p>
<pre><code>class Heartbeat (cocos.layer.Layer):
is_event_handler=True
def __init__ (self):
super(Heartbeat, self).__init__()
global loop, music, player
music = pyglet.media.load('long_beep.wav')
loop=pyglet.media.SourceGroup(music.audio_format, None)
player=pyglet.media.Player()
loop.queue(music)
def on_key_press(self, key, modifiers):
if chr(key)=='h':
loop.loop=True
player.queue(loop) #This is the line that had to be moved
player.play()
def on_key_release (self, key, modifiers):
if chr(key)=="h":
loop.loop=False
</code></pre>
<p>NOTE: I ommited statements such as import and others, used for initialization as they are not relevant to this issue.</p>
| 0 | 2016-10-01T13:58:05Z | [
"python",
"python-3.x",
"audio",
"pyglet",
"keyrelease"
]
|
Resolving shift/reduce conflict for default label in switch block | 39,797,216 | <p>I'm writing a parser for Unrealscript using PLY, and I've run into (hopefully) one of the last ambiguities in the parsing rules that I've set up.</p>
<p>Unrealscript has a keyword, <code>default</code>, which is used differently depending on the context. In a regular statement line, you could use <code>default</code> like so:</p>
<pre><code>default.SomeValue = 3; // sets the "default" class property to 3
</code></pre>
<p>There is also, of course, the <code>default</code> case label for <code>switch</code> statements:</p>
<pre><code>switch (i) {
case 0:
break;
default:
break;
}
</code></pre>
<p>There is an ambiguity in the parsing when it encounters the <code>default</code> label within what it thinks is the <code>case</code>'s statement block. Here is an example file that runs into a parsing error:</p>
<h1>Input</h1>
<pre><code>class Example extends Object;
function Test() {
switch (A) {
case 0:
default.SomeValue = 3; // OK
default: // ERROR: Expected "default.IDENTIFIER"
break;
}
}
</code></pre>
<h1>Parsing Rules</h1>
<p>Here are the rules that are in conflict:</p>
<p>All of the rules can be seen in their entirety <a href="https://github.com/cmbasnett/ulex/blob/master/yucc.py" rel="nofollow">on GitHub</a>.</p>
<h2><code>default</code></h2>
<pre><code>def p_default(p):
'default : DEFAULT PERIOD identifier'
p[0] = ('default', p[3])
</code></pre>
<h2><code>switch</code></h2>
<pre><code>def p_switch_statement(p):
'switch_statement : SWITCH LPAREN expression RPAREN LCURLY switch_cases RCURLY'
p[0] = ('switch_statement', p[3], p[6])
def p_switch_case_1(p):
'switch_case : CASE primary COLON statements_or_empty'
p[0] = ('switch_case', p[2], p[4])
def p_switch_case_2(p):
'switch_case : DEFAULT COLON statements_or_empty'
p[0] = ('default_case', p[3])
def p_switch_cases_1(p):
'switch_cases : switch_cases switch_case'
p[0] = p[1] + [p[2]]
def p_switch_cases_2(p):
'switch_cases : switch_case'
p[0] = [p[1]]
def p_switch_cases_or_empty(p):
'''switch_cases_or_empty : switch_cases
| empty'''
p[0] = p[1]
</code></pre>
<p>Any help or guidance on how to resolve this conflict will be greatly appreciated! Thank you in advance.</p>
| 2 | 2016-09-30T17:46:17Z | 39,811,928 | <p>What you have here is a simple shift/reduce conflict (with the token <code>default</code> as lookahead) being resolved as a shift.</p>
<p>Let's reduce this all to a much smaller, if not minimal example. Here's the grammar, partly based on the one in the Github repository pointed to in the OP (but intended to be self-contained):</p>
<pre><code>statements: statements statement |
statement : assign SEMICOLON
| switch
assign : lvalue EQUALS expression
switch : SWITCH LPAREN expression RPAREN LCURLY cases RCURLY
cases : cases case |
case : CASE expression COLON statements
| DEFAULT COLON statements
expression: ID | INT
lvalue : ID | DEFAULT
</code></pre>
<p>The key here is that a <code>statement</code> might start with the token <code>DEFAULT</code>, and a <code>case</code> might also start with the token <code>DEFAULT</code>. Now, suppose we've reached the following point in the parse:</p>
<pre><code>switch ( <expression> ) { <cases> case <expression> : <statements>
</code></pre>
<p>so we're in the middle of a <code>switch</code> compound statement; we've seen <code>case 0:</code> and we're working on a list of statements. The current state includes the items (there are a few more; I only include the relevant ones):</p>
<pre><code>1. statements: statements · statement
2. case : CASE expression COLON statements ·
3. statement : · assign SEMICOLON
4. assign : · lvalue EQUALS expression
5. lvalue : · DEFAULT
</code></pre>
<p>The lookahead set for item 2 is <code>[ RCURLY, DEFAULT, ID ]</code>.</p>
<p>Now suppose the next token is <kbd>default</kbd>. We could be looking at the start of a statement, if the <kbd>default</kbd> is followed by <kbd>=</kbd>. Or we could be looking at a new case clause, if the <kbd>default</kbd> is followed by <kbd>:</kbd>. But we can't see two tokens into the future, only one; the next token is <kbd>default</kbd> and that is all we know.</p>
<p>But we need to make a decision:</p>
<ul>
<li><p>If the <kbd>default</kbd> is the beginning of a statement, we can just shift it (item 5). Then when we see the <kbd>=</kbd>, we'll reduce <kbd>default</kbd> to <code>lvalue</code> and continue to parse the <code>assign</code>.</p></li>
<li><p>If the <kbd>default</kbd> is the beginning of a case, we need to reduce <code>CASE expression COLON statements</code> to <code>case</code> (item 2). We will then reduce <code>cases case</code> to <code>cases</code> before we finally shift the <kbd>default</kbd>. We will then shift the <kbd>:</kbd> and continue with <code>DEFAULT COLON statements</code>.</p></li>
</ul>
<p>Like most LR parser generators, PLY resolves shift/reduce conflicts in favour of the shift, so it will always take the first of the two options above. If it then sees <kbd>:</kbd> instead of <kbd>=</kbd>, it will report a syntax error.</p>
<p>So what we have is just another example of an LR(2) grammar. LR(2) grammars can always be rewritten as LR(1) grammars, but the rewritten grammar is often ugly and bloated. Here is one possible solution, which is possibly less ugly than most. </p>
<p>The body of a switch, using EBNF operators <code>|</code>, <code>*</code> and <code>+</code> (alternation, optional repetition, and repetition) is:</p>
<pre><code>switch-body -> (("case" expression | "default") ":" statement*)+
</code></pre>
<p>Or, to make it a little less cumbersome:</p>
<pre><code>case-header -> ("case" expression | "default") ":"
switch-body -> (case-header statement*)+
</code></pre>
<p>From the perspective of accepted strings, that's exactly the same as</p>
<pre><code>switch-body -> case-header (case-header | statement)*
</code></pre>
<p>In other words, a sequence of things which are either <code>case-header</code>s or <code>statement</code>s, where the first one is a <code>case-header</code>.</p>
<p>This way of writing the rule does not generate the correct parse tree; it simplifies the structure of a switch statement into a soup of statements and case labels. But it does recognise exactly the same language.</p>
<p>On the plus side, it has the virtue of not forcing the parser to decide when a case cause has terminated. (The grammar no longer has case clauses.) So it is a simple LR(1) grammar:</p>
<pre><code>switch : SWITCH LPAREN expression RPAREN LCURLY switch_body RCURLY
switch_body : case_header
| switch_body statement
| switch_body case_header
case_header : CASE expr COLON
| DEFAULT COLON
</code></pre>
<p>Now, we could make the argument that the resulting parse tree is, in fact, accurate. Unrealscript shares the same design decision about <code>switch</code> statements as C, in which a <code>case</code> clause does not actually define a block in any real sense of the word. It is simply a label which can be jumped to, and a conditional jump to the next label.</p>
<p>But it is actually not particularly complicated to fix the parse tree as we go, because each reduction to <code>switch_body</code> clearly indicates what we're adding. If we're adding a case-header, we can append a new list to the accumulating list of case clauses; if it's a statement, we append the statement to the end of the last case clause.</p>
<p>So we could write the above rules in PLY roughly as follows:</p>
<pre><code>def p_switch_body_1(p):
''' switch_body : case_header '''
p[0] = [p[1]]
def p_switch_body_2(p):
''' switch_body : switch_body statement '''
# Append the statement to the list which is the last element of
# the tuple which is the last element of the list which is the
# semantic value of symbol 1, the switch_body.
p[1][-1][-1].append(p[2])
p[0] = p[1]
def p_switch_body_3(p):
''' switch_body : switch_body case_header '''
# Add the new case header (symbol 2), whose statement list
# is initially empty, to the list of switch clauses.
p[1].append(p[2])
p[0] = p[1]
def p_case_header_1(p):
''' case_header : CASE expr COLON '''
p[0] = ('switch_case', p[2], [])
def p_case_header_2(p):
''' case_header : DEFAULT COLON '''
p[0] = ('default_case', [])
</code></pre>
| 1 | 2016-10-01T22:10:35Z | [
"python",
"ply",
"lalr",
"unrealscript"
]
|
choosing correct form according to form input's name | 39,797,218 | <p>I want to submit forms in multiple websites. Usually I can't exactly know the form name or form id, but I know the input name that I want to submit.</p>
<p>Let's say there is a website which has couple of forms inside it. My code should check all of the forms, if one of them has a input value named "birthday" it will submit that form. If multiple forms has it, it will submit them all.</p>
<p>How can I achieve this?</p>
| -2 | 2016-09-30T17:46:31Z | 39,797,265 | <p>You can basically loop over all forms and skip forms that don't contain the desired input:</p>
<pre><code>for form in br.forms():
if not form.find_control(name="birthday"):
continue
# fill form and submit here
</code></pre>
<p>More about <code>find_control()</code> <a href="http://wwwsearch.sourceforge.net/mechanize/forms.html" rel="nofollow">here</a>.</p>
| 1 | 2016-09-30T17:49:42Z | [
"python",
"mechanize"
]
|
choosing correct form according to form input's name | 39,797,218 | <p>I want to submit forms in multiple websites. Usually I can't exactly know the form name or form id, but I know the input name that I want to submit.</p>
<p>Let's say there is a website which has couple of forms inside it. My code should check all of the forms, if one of them has a input value named "birthday" it will submit that form. If multiple forms has it, it will submit them all.</p>
<p>How can I achieve this?</p>
| -2 | 2016-09-30T17:46:31Z | 39,817,061 | <p>You are gonna need to use an <a href="http://stackoverflow.com/a/9884259/6209196">iterator</a> to check all the forms in the website. In this case we will be using <code>for</code>. But this doesn't let us know about which form we are working on, it just lets us use it. So we are going to assign 0(the first form's ID) to a variable and add 1 to it as we change forms when a new iteration/loop starts.</p>
<pre><code>currentForm = 0
for form in br.forms(): # For every form in the website
currentForm += 1 # Add 1 to the current form so that the script knows which form we will be working next
if not forms.find_control(name = "birthday"): # If the form isn't about birthday
continue # Go to the next iteration / loop ignoring the statements below
br.select_form(nr = currentForm) # Select the birthday form
br.form["birthday"] = "Fill this with what you want" # Writing to the form
br.submit() # Submit the working form
</code></pre>
<p>Note: <code>x += y</code> is equal to <code>x = x + y</code></p>
| 0 | 2016-10-02T12:36:13Z | [
"python",
"mechanize"
]
|
Process substitution not allowed by Python's subprocess with shell=True? | 39,797,234 | <p>Here is a toy example of process substitution that works fine in Bash:</p>
<pre><code>$ wc -l <(pwd)
1 /proc/self/fd/11
</code></pre>
<p>So why does the same command give a syntax error when invoked from Python's subprocess with shell=True? </p>
<pre><code>>>> subprocess.check_call('wc -l <(pwd)', shell=True)
/bin/sh: 1: Syntax error: "(" unexpected
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/to/my/python/lib/python3.5/subprocess.py", line 581, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'wc -l <(pwd)' returned non-zero exit status 2
</code></pre>
| 0 | 2016-09-30T17:47:17Z | 39,797,316 | <blockquote>
<p>/bin/sh: 1: Syntax error: "(" unexpected</p>
</blockquote>
<p>You have a <a href="https://en.wiktionary.org/wiki/bashism" rel="nofollow">bashism</a>. It is not valid according to POSIX, which is what <code>/bin/sh</code> implements.</p>
| 2 | 2016-09-30T17:52:15Z | [
"python",
"bash",
"shell",
"subprocess",
"process-substitution"
]
|
Process substitution not allowed by Python's subprocess with shell=True? | 39,797,234 | <p>Here is a toy example of process substitution that works fine in Bash:</p>
<pre><code>$ wc -l <(pwd)
1 /proc/self/fd/11
</code></pre>
<p>So why does the same command give a syntax error when invoked from Python's subprocess with shell=True? </p>
<pre><code>>>> subprocess.check_call('wc -l <(pwd)', shell=True)
/bin/sh: 1: Syntax error: "(" unexpected
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/to/my/python/lib/python3.5/subprocess.py", line 581, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'wc -l <(pwd)' returned non-zero exit status 2
</code></pre>
| 0 | 2016-09-30T17:47:17Z | 39,797,861 | <p>An alternate solution is to shift more of the shell code to Python itself. For example:</p>
<pre><code>from subprocess import Popen, PIPE, check_call
p1 = Popen(["pwd"], stdout=PIPE)
p2 = check_call(["wc", "-l"], stdin=p1.stdout)
</code></pre>
<p>This could often be the first step towards eliminating the need to use <code>subprocess</code> at all, as it decomposes the work into smaller chunks for which you may more readily see how to do in Python itself.</p>
| 1 | 2016-09-30T18:27:58Z | [
"python",
"bash",
"shell",
"subprocess",
"process-substitution"
]
|
How do I determine what ip range a device is using? | 39,797,245 | <p>This is kind of a weird problem, basically I have a computer connected to a machine via ethernet cable. There is no other network or internet access. The machine sets up a network which allows you to telnet into it. </p>
<p>I need the simplest way possible to determine the ip range the device is using. This would be turned into a python script. It is not just the obvious 192.168.x.x</p>
<p>I'm looking at the 'arp' command, but also a library called 'netifaces'. I'm not sure if there's something simpler I could use. It has to work for Linux, OSX and Windows. The machine is running an android OS</p>
<p>Basically, I just need to be able to determine what ip ranges the device is currently using in the simplest possible way. </p>
<p>The command 'arp -a' seems to be the most promising right now. </p>
| 0 | 2016-09-30T17:48:08Z | 39,797,482 | <p>Try this </p>
<pre><code>import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
get_ip_address('eth0') # '192.168.0.110'
</code></pre>
| 0 | 2016-09-30T18:03:32Z | [
"python",
"networking"
]
|
How do I determine what ip range a device is using? | 39,797,245 | <p>This is kind of a weird problem, basically I have a computer connected to a machine via ethernet cable. There is no other network or internet access. The machine sets up a network which allows you to telnet into it. </p>
<p>I need the simplest way possible to determine the ip range the device is using. This would be turned into a python script. It is not just the obvious 192.168.x.x</p>
<p>I'm looking at the 'arp' command, but also a library called 'netifaces'. I'm not sure if there's something simpler I could use. It has to work for Linux, OSX and Windows. The machine is running an android OS</p>
<p>Basically, I just need to be able to determine what ip ranges the device is currently using in the simplest possible way. </p>
<p>The command 'arp -a' seems to be the most promising right now. </p>
| 0 | 2016-09-30T17:48:08Z | 39,798,412 | <p>The IPv4 Link-Local range of <code>169.254.0.0/16</code> is used by APIPA for hosts to assign IP addresses when an interface has no other way to obtain an address. There are some rules about this range, e.g. you cannot subnet the range, it can't be routed, etc. See <a href="https://tools.ietf.org/html/rfc3927" rel="nofollow">RFC 3927, Dynamic Configuration of IPv4 Link-Local Addresses</a> for more information.</p>
<p>You really need to determine if the equipment on the other end of your link is using this range. If it is a specialized device, it probably does not, and it will have a fixed address which was manually assigned. If this is the case, you will not be able contact it with your Link-Local address.</p>
| 0 | 2016-09-30T19:01:22Z | [
"python",
"networking"
]
|
How can I properly parse a string into grapheme clusters using python 2.7? | 39,797,261 | <p>I'm trying to find a way using python 2.7.1 to parse a string into grapheme clusters. For example, the string:</p>
<pre><code>details = u"Hello í ¼í·¦í ¼í·¹í ¼í·»í ¼í·ª"
</code></pre>
<p>I believe should be parsed as:</p>
<pre><code>[u"H", u"e", u"l", u"l", u"o", u"\U0001f1e6\U0001f1f9", u"\U0001f1fb\U0001f1ea"]
</code></pre>
<p>I was using <code>grapheme_clusters</code> from the <a href="https://bitbucket.org/emptypage/uniseg-python" rel="nofollow">uniseg</a> library, but this produces:</p>
<pre><code>[u"H", u"e", u"l", u"l", u"o", u"\U0001f1e6\U0001f1f9\U0001f1fb\U0001f1ea"]
</code></pre>
<p>I have a hard requirement on using 2.7.1. I know unicode support is better in python 3.X.</p>
<p>1) Is my interpretation of the way this string should be parsed correct?<br>
2) Is there a way to do this with python 2.7?<br>
3) Is this actually any easier in python 3.X?</p>
<p>Thanks for any help.</p>
| 2 | 2016-09-30T17:49:26Z | 39,797,574 | <p>This behavior used to be correct, but the rules changed.</p>
<p>As of uniseg version 0.7.1 (current as of this post), the uniseg documentation refers to an outdated version of the Unicode grapheme cluster boundary rules, given in <a href="http://www.unicode.org/reports/tr29/tr29-21.html" rel="nofollow">Unicode Standard Annex #29 Version 21</a>. This version includes the rule</p>
<blockquote>
<p>Do not break between regional indicator symbols.</p>
</blockquote>
<p>where the most recent version of the Unicode grapheme cluster boundary rules, given in <a href="http://www.unicode.org/reports/tr29/tr29-29.html" rel="nofollow">Unicode Standard Annex #29 Version 29</a> says</p>
<blockquote>
<p>Do not break within emoji flag sequences. That is, do not break between regional indicator (RI) symbols if there is an odd number of RI characters before the break point.</p>
</blockquote>
<p>You could file a bug report with uniseg, or perhaps a different library would have a more up-to-date implementation. The uniseg bitbucket page links to a few alternatives, such as <a href="https://pypi.python.org/pypi/PyICU" rel="nofollow">PyICU</a>.</p>
| 2 | 2016-09-30T18:10:03Z | [
"python",
"python-2.7",
"python-3.x",
"unicode"
]
|
python, multthreading, safe to use pandas "to_csv" on common file? | 39,797,340 | <p>I've got some code that works pretty nicely. It's a while-loop that goes through a list of dates, finds files on my HDD that corresponds to those dates, does some calculations with those files, and then outputs to a "results.csv" file using the command:</p>
<pre><code>my_df.to_csv("results.csv",mode = 'a')
</code></pre>
<p>I'm wondering if it's safe to create a new thread for each date, and call the stuff in the while loop on several dates at a time?</p>
<p>MY CODE: </p>
<pre><code>import datetime, time, os
import sys
import threading
import helperPY #a python file containing the logic I need
class myThread (threading.Thread):
def __init__(self, threadID, name, counter,sn, m_date):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.sn = sn
self.m_date = m_date
def run(self):
print "Starting " + self.name
m_runThis(sn, m_date)
print "Exiting " + self.name
def m_runThis(sn, m_date):
helperPY.helpFn(sn,m_date) #this is where the "my_df.to_csv()" is called
sn = 'XXXXXX'
today=datetime.datetime(2016,9,22) #
yesterday=datetime.datetime(2016,6,13)
threadList = []
i_threadlist=0
while(today>yesterday):
threadList.append(myThread(i_threadlist, str(today), i_threadlist,sn,today))
threadList[i_threadlist].start()
i_threadlist = i_threadlist +1
today = today-datetime.timedelta(1)
</code></pre>
| 0 | 2016-09-30T17:53:45Z | 39,797,512 | <p>Writing the file in multiple threads is not safe. But you can create a <a href="https://docs.python.org/3.6/library/threading.html#threading.Lock" rel="nofollow">lock</a> to protect that one operation while letting the rest run in parallel. Your <code>to_csv</code> isn't shown, but you could create the lock</p>
<pre><code>csv_output_lock = threading.Lock()
</code></pre>
<p>and pass it to <code>helperPY.helpFn</code>. When you get to the operation, do</p>
<pre><code>with csv_output_lock:
my_df.to_csv("results.csv",mode = 'a')
</code></pre>
<p>You get parallelism for other operations - subject to the GIL of course - but the file access is protected.</p>
| 1 | 2016-09-30T18:05:58Z | [
"python",
"multithreading",
"pandas"
]
|
Python's string count function doesn't use regex | 39,797,369 | <p>when trying to count all letters in a string using the count function and the regex [A-Za-z], it returns a a value of zero.</p>
<p>For instance:</p>
<pre><code>string="Hi, everybody. Let's dance!"
string.count('[A-Za-z]') ## prints 0
</code></pre>
<p>any suggestions?</p>
| -3 | 2016-09-30T17:56:15Z | 39,797,394 | <p>Use regular expressions:</p>
<pre><code>len(re.findall('[A-Za-z]', string))
</code></pre>
| 3 | 2016-09-30T17:57:57Z | [
"python",
"regex",
"python-2.7",
"function"
]
|
Python's string count function doesn't use regex | 39,797,369 | <p>when trying to count all letters in a string using the count function and the regex [A-Za-z], it returns a a value of zero.</p>
<p>For instance:</p>
<pre><code>string="Hi, everybody. Let's dance!"
string.count('[A-Za-z]') ## prints 0
</code></pre>
<p>any suggestions?</p>
| -3 | 2016-09-30T17:56:15Z | 39,797,472 | <p>Because that's not how count works,look at this link <a href="https://www.tutorialspoint.com/python/string_count.htm" rel="nofollow">count</a></p>
<p>In that statement you are telling how much substrings of '[A-Za-z]' are in string
if you want to count all the letters in a string use len()</p>
| -1 | 2016-09-30T18:02:58Z | [
"python",
"regex",
"python-2.7",
"function"
]
|
Python's string count function doesn't use regex | 39,797,369 | <p>when trying to count all letters in a string using the count function and the regex [A-Za-z], it returns a a value of zero.</p>
<p>For instance:</p>
<pre><code>string="Hi, everybody. Let's dance!"
string.count('[A-Za-z]') ## prints 0
</code></pre>
<p>any suggestions?</p>
| -3 | 2016-09-30T17:56:15Z | 39,798,039 | <p>As indicated in brianpcks comment, there are alternatives that do not require using regular expressions:</p>
<pre><code>len(c for c in string if c.isalpha())
</code></pre>
<p>or</p>
<pre><code>from string import ascii_lowercase
len(c for c in string if c in string.ascii_lowercase)
</code></pre>
<p>Although these alternatives might be slower in CPython, your mileage may vary using other Python implementations (especially PyPy, who's JIT can optimize python loops very well).</p>
<p>As always, if speed is a concern, benchmark both approaches in your environment before deciding which to use.</p>
| 0 | 2016-09-30T18:38:18Z | [
"python",
"regex",
"python-2.7",
"function"
]
|
Code wars : Title Case with python | 39,797,434 | <pre><code>def title_case(title, minor_words = 0):
title = title.lower().split(" ")
title_change = []
temp = []
if minor_words != 0 :
minor_words = minor_words.lower().split(" ")
for i in range(len(title)):
if (i != 0 and title[i] not in minor_words) or (i == 0 and title[i] in minor_words):
temp = list(title[i].lower())
temp[0] = temp[0].upper()
title_change.append("".join(temp))
else:
title_change.append(title[i])
temp = []
else:
for i in range(len(title)):
temp = list(title[i])
temp[0] = temp[0].upper()
title_change.append("".join(temp))
temp = []
return " ".join(title_change)
</code></pre>
<p>Hello,this is my python code here.
This is the question:
A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.</p>
<p>Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed.</p>
<p>I am trying not to use capitalize() to do this.It seems my code works fine on my computer,but the code wars just prompted "IndexError: list index out of range".</p>
| 2 | 2016-09-30T18:00:17Z | 39,797,608 | <p>Your code will break if <code>title</code> has leading or trailing spaces, or two consecutive spaces, such as <code>"foo bar"</code>. It will also break on an empty string. That's because <code>title.lower().split(" ")</code> on any of those kinds of titles will give you an empty string as one of your "words", and then <code>temp[0]</code> will cause an <code>IndexError</code> later on.</p>
<p>You can avoid the issue by using <code>split()</code> with no argument. It will split on any kind of whitespace in any combinations. Multiple spaces will be treated just like one space, and leading or trailing whitespace will be ignored. An empty string will become an empty list when <code>split</code> is called, rather than a list with one empty string in it.</p>
| 2 | 2016-09-30T18:13:05Z | [
"python",
"indexing"
]
|
Code wars : Title Case with python | 39,797,434 | <pre><code>def title_case(title, minor_words = 0):
title = title.lower().split(" ")
title_change = []
temp = []
if minor_words != 0 :
minor_words = minor_words.lower().split(" ")
for i in range(len(title)):
if (i != 0 and title[i] not in minor_words) or (i == 0 and title[i] in minor_words):
temp = list(title[i].lower())
temp[0] = temp[0].upper()
title_change.append("".join(temp))
else:
title_change.append(title[i])
temp = []
else:
for i in range(len(title)):
temp = list(title[i])
temp[0] = temp[0].upper()
title_change.append("".join(temp))
temp = []
return " ".join(title_change)
</code></pre>
<p>Hello,this is my python code here.
This is the question:
A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.</p>
<p>Write a function that will convert a string into title case, given an optional list of exceptions (minor words). The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case of the minor words string -- it should behave in the same way even if the case of the minor word string is changed.</p>
<p>I am trying not to use capitalize() to do this.It seems my code works fine on my computer,but the code wars just prompted "IndexError: list index out of range".</p>
| 2 | 2016-09-30T18:00:17Z | 39,797,727 | <p>Just as a supplement to @Blckknght's explanation, here is an illuminating console session that steps through what's happening to your variable.</p>
<pre><code>>>> title = ''
>>> title = title.lower().split(' ')
>>> title
['']
>>> temp = list(title[0])
>>> temp
[]
>>> temp[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
</code></pre>
<p>I tried your solution on other (non-whitespace) inputs, and it works fine.</p>
| 0 | 2016-09-30T18:20:41Z | [
"python",
"indexing"
]
|
a valid element not in np.arange, though print() does show it, dtypes are also same | 39,797,454 | <pre><code>a = 1.25
if a in np.arange(1,2,0.05):
print(a)
</code></pre>
<p>but this if condition doesn't holds true,though</p>
<pre><code>print(np.arange(1,2,0.05))
[ 1. 1.05 1.1 1.15 1.2 1.25 1.3 1.35 1.4 1.45 1.5 1.55 1.6 1.65 1.7 1.75 1.8 1.85 1.9 1.95]
</code></pre>
<p>does have 1.25 in it.</p>
<p>I read that arange is not really consistent, but is there any workaround for this?</p>
| 2 | 2016-09-30T18:01:51Z | 39,797,661 | <p>That's because there is no <code>1.25</code> in that range it's actually <code>1.2500000000000002</code> and that's because numpy considers a double precision float for float numbers by default and in cases that decimal fractions cannot be represented exactly as binary fractions, they can hold the more accurate value for floats. And what you see in print result is just a formatted representation of the real value.</p>
<pre><code>In [58]: l = np.arange(1,2,0.05)
In [59]: l[5]
Out[59]: 1.2500000000000002
In [60]: type(l[5])
Out[60]: numpy.float64
</code></pre>
<p>One way for solving that is casting the type to <code>float32</code>:</p>
<pre><code>In [61]: l = np.arange(1,2,0.05).astype(np.float32)
In [62]: a = 1.25
In [63]: type(a)
Out[63]: float
In [64]: a in l
Out[64]: True
</code></pre>
| 1 | 2016-09-30T18:16:38Z | [
"python",
"numpy"
]
|
a valid element not in np.arange, though print() does show it, dtypes are also same | 39,797,454 | <pre><code>a = 1.25
if a in np.arange(1,2,0.05):
print(a)
</code></pre>
<p>but this if condition doesn't holds true,though</p>
<pre><code>print(np.arange(1,2,0.05))
[ 1. 1.05 1.1 1.15 1.2 1.25 1.3 1.35 1.4 1.45 1.5 1.55 1.6 1.65 1.7 1.75 1.8 1.85 1.9 1.95]
</code></pre>
<p>does have 1.25 in it.</p>
<p>I read that arange is not really consistent, but is there any workaround for this?</p>
| 2 | 2016-09-30T18:01:51Z | 39,798,698 | <p>Using <code>item</code> to print values in full splendor:</p>
<pre><code>In [83]: for i in np.arange(1,2,0.05):print(i.item())
1.0
1.05
1.1
1.1500000000000001
1.2000000000000002
1.2500000000000002
1.3000000000000003
1.3500000000000003
1.4000000000000004
1.4500000000000004
1.5000000000000004
1.5500000000000005
1.6000000000000005
1.6500000000000006
1.7000000000000006
1.7500000000000007
1.8000000000000007
1.8500000000000008
1.9000000000000008
1.9500000000000008
</code></pre>
<p>Even <code>linspace</code> has those extra digits off at the end:</p>
<pre><code>In [84]: for i in np.linspace(1,2,21):print(i.item())
1.0
1.05
1.1
1.15
1.2
1.25
1.3
1.35
1.4
1.45
1.5
1.55
1.6
1.65
1.7000000000000002
1.75
1.8
1.85
1.9
1.9500000000000002
2.0
</code></pre>
<p><code>in</code> and <code>==</code> tests are not a good idea when working with floats.</p>
<p><code>isclose</code> and <code>allclose</code> test for small differences rather than exact match</p>
<pre><code>In [89]: np.isclose(np.arange(1,2,0.05),1.25)
Out[89]:
array([False, False, False, False, False, True, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False], dtype=bool)
In [90]: np.isclose(np.arange(1,2,0.05),1.25).any()
Out[90]: True
</code></pre>
<p>Look at the <code>isclose</code> code to see all that is involved in comparing floats.</p>
| 0 | 2016-09-30T19:22:52Z | [
"python",
"numpy"
]
|
Glassdoor API Not Printing Custom Response | 39,797,495 | <p>I have the following problem when I try to print something from this api. I'm trying to set it up so I can access different headers, then print specific items from it. But instead when I try to print soup it gives me the entire api response in json format. </p>
<pre><code>import requests, json, urlparse, urllib2
from BeautifulSoup import BeautifulSoup
url = "apiofsomesort"
#Create Dict based on JSON response; request the URL and parse the JSON
#response = requests.get(url)
#response.raise_for_status() # raise exception if invalid response
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(url,headers=hdr)
response = urllib2.urlopen(req)
soup = BeautifulSoup(response)
print soup
</code></pre>
<p>When it prints it looks like the below:</p>
<pre><code>{
"success": true,
"status": "OK",
"jsessionid": "0541E6136E5A2D5B2A1DF1F0BFF66D03",
"response": {
"attributionURL": "http://www.glassdoor.com/Reviews/airbnb-reviews-SRCH_KE0,6.htm",
"currentPageNumber": 1,
"totalNumberOfPages": 1,
"totalRecordCount": 1,
"employers": [{
"id": 391850,
"name": "Airbnb",
"website": "www.airbnb.com",
"isEEP": true,
"exactMatch": true,
"industry": "Hotels, Motels, &amp; Resorts",
"numberOfRatings": 416,
"squareLogo": "https://media.glassdoor.com/sqll/391850/airbnb-squarelogo-1459271200583.png",
"overallRating": 4.3,
"ratingDescription": "Very Satisfied",
"cultureAndValuesRating": "4.4",
"seniorLeadershipRating": "4.0",
"compensationAndBenefitsRating": "4.3",
"careerOpportunitiesRating": "4.1",
"workLifeBalanceRating": "3.9",
"recommendToFriendRating": "0.9",
"sectorId": 10025,
"sectorName": "Travel &amp; Tourism",
"industryId": 200140,
"industryName": "Hotels, Motels, &amp; Resorts",
"featuredReview": {
"attributionURL": "http://www.glassdoor.com/Reviews/Employee-Review-Airbnb-RVW12111314.htm",
"id": 12111314,
"currentJob": false,
"reviewDateTime": "2016-09-28 16:44:00.083",
"jobTitle": "Employee",
"location": "",
"headline": "An amazing place to work!",
"pros": "Wonderful people and great culture. Airbnb really strives to make you feel at home as an employee, and everyone is genuinely excited about the company mission.",
"cons": "The limitations of Rails 3 and the company infrastructure make developing difficult sometimes.",
"overall": 5,
"overallNumeric": 5
},
"ceo": {
"name": "Brian Chesky",
"title": "CEO &amp; Co-Founder",
"numberOfRatings": 306,
"pctApprove": 95,
"pctDisapprove": 5,
"image": {
"src": "https://media.glassdoor.com/people/sqll/391850/airbnb-brian-chesky.png",
"height": 200,
"width": 200
}
}
}]
}
}
</code></pre>
<p>I want to print out specific items like employers":name, industry etc...</p>
| 0 | 2016-09-30T18:04:37Z | 39,799,536 | <p>You can load the JSON response into a dict then look for the values you want like you would in any other dict.</p>
<p>I took your data and saved it in an external JSON file to do a test since I don't have access to the API. This worked for me.</p>
<pre><code>import json
# Load JSON from external file
with open (r'C:\Temp\json\data.json') as json_file:
data = json.load(json_file)
# Print the values
print 'Name:', data['response']['employers'][0]['name']
print 'Industry:', data['response']['employers'][0]['industry']
</code></pre>
<p>Since you're getting your data from an API something like this should work.</p>
<pre><code>import json
import urlib2
url = "apiofsomesort"
# Load JSON from API
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(url, headers=hdr)
response = urllib2.urlopen(req)
data = json.load(response.read())
# Print the values
print 'Name:', data['response']['employers'][0]['name']
print 'Industry:', data['response']['employers'][0]['industry']
</code></pre>
| 0 | 2016-09-30T20:23:15Z | [
"python",
"json",
"api"
]
|
Glassdoor API Not Printing Custom Response | 39,797,495 | <p>I have the following problem when I try to print something from this api. I'm trying to set it up so I can access different headers, then print specific items from it. But instead when I try to print soup it gives me the entire api response in json format. </p>
<pre><code>import requests, json, urlparse, urllib2
from BeautifulSoup import BeautifulSoup
url = "apiofsomesort"
#Create Dict based on JSON response; request the URL and parse the JSON
#response = requests.get(url)
#response.raise_for_status() # raise exception if invalid response
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(url,headers=hdr)
response = urllib2.urlopen(req)
soup = BeautifulSoup(response)
print soup
</code></pre>
<p>When it prints it looks like the below:</p>
<pre><code>{
"success": true,
"status": "OK",
"jsessionid": "0541E6136E5A2D5B2A1DF1F0BFF66D03",
"response": {
"attributionURL": "http://www.glassdoor.com/Reviews/airbnb-reviews-SRCH_KE0,6.htm",
"currentPageNumber": 1,
"totalNumberOfPages": 1,
"totalRecordCount": 1,
"employers": [{
"id": 391850,
"name": "Airbnb",
"website": "www.airbnb.com",
"isEEP": true,
"exactMatch": true,
"industry": "Hotels, Motels, &amp; Resorts",
"numberOfRatings": 416,
"squareLogo": "https://media.glassdoor.com/sqll/391850/airbnb-squarelogo-1459271200583.png",
"overallRating": 4.3,
"ratingDescription": "Very Satisfied",
"cultureAndValuesRating": "4.4",
"seniorLeadershipRating": "4.0",
"compensationAndBenefitsRating": "4.3",
"careerOpportunitiesRating": "4.1",
"workLifeBalanceRating": "3.9",
"recommendToFriendRating": "0.9",
"sectorId": 10025,
"sectorName": "Travel &amp; Tourism",
"industryId": 200140,
"industryName": "Hotels, Motels, &amp; Resorts",
"featuredReview": {
"attributionURL": "http://www.glassdoor.com/Reviews/Employee-Review-Airbnb-RVW12111314.htm",
"id": 12111314,
"currentJob": false,
"reviewDateTime": "2016-09-28 16:44:00.083",
"jobTitle": "Employee",
"location": "",
"headline": "An amazing place to work!",
"pros": "Wonderful people and great culture. Airbnb really strives to make you feel at home as an employee, and everyone is genuinely excited about the company mission.",
"cons": "The limitations of Rails 3 and the company infrastructure make developing difficult sometimes.",
"overall": 5,
"overallNumeric": 5
},
"ceo": {
"name": "Brian Chesky",
"title": "CEO &amp; Co-Founder",
"numberOfRatings": 306,
"pctApprove": 95,
"pctDisapprove": 5,
"image": {
"src": "https://media.glassdoor.com/people/sqll/391850/airbnb-brian-chesky.png",
"height": 200,
"width": 200
}
}
}]
}
}
</code></pre>
<p>I want to print out specific items like employers":name, industry etc...</p>
| 0 | 2016-09-30T18:04:37Z | 39,800,521 | <pre><code>import json, urlib2
url = "http..."
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(url, headers=hdr)
response = urllib2.urlopen(req)
data = json.loads(response.read())
# Print the values
print 'numberOfRatings:', data['response']['employers'][0]['numberOfRatings']
</code></pre>
| 0 | 2016-09-30T21:47:07Z | [
"python",
"json",
"api"
]
|
Basic Anagram VS more advanced one | 39,797,552 | <p>I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; <em>two words are an anagram if you can rearrange the letters from one to spell the other</em>).</p>
<p>The easier solution that comes to mind is:</p>
<pre><code>def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dog')
</code></pre>
<p>It works, but it doesn't really satisfy me. If we were in this situation for example:</p>
<pre><code>def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dyog') #extra letter 'd' in second argument
>>> False
</code></pre>
<p>Return is False, although we should be able to to build the word <code>'god'</code> out of <code>'dyog'</code>. Perhaps this game/problem isn't called an anagram, but I've been trying to figure it out anyway.</p>
<p><strong>Technically my solution is to:</strong><br>
1- Iterate through every element of b.<br>
2- As I do, I check if that element exists in a.<br>
3- If all of them do; then we can create a out of b.<br>
4- Otherwise, we can't.</p>
<p>I just can't seem to get it to work. <strong>For the record, I do not know how to use <code>lambda</code></strong></p>
<p><strong>Some tests:</strong></p>
<pre><code>print is_anagram('god', 'ddog') #should return True
print is_anagram('god', '9d8s0og') #should return True
print is_anagram('god', '_@10d_o g') #should return True
</code></pre>
<p>Thanks :)</p>
| 2 | 2016-09-30T18:08:47Z | 39,797,628 | <p>Try that:</p>
<pre><code>def is_anagram(a, b):
word = [filter(lambda x: x in a, sub) for sub in b]
return ''.join(word)[0:len(a)]
</code></pre>
<p>Example:</p>
<pre><code>>>> is_anagram('some','somexcv')
'some'
</code></pre>
<p><strong>Note:</strong> This code returns the <code>common word</code> if there is any or <code>''</code> otherwise. (it doesn't return <code>True/False</code> as the OP asked - realized that after, but anyway this code can easily change to adapt the <code>True/False</code> type of result - I won't fix it now such there are great answers in this post that already do :) )</p>
<blockquote>
<p>Brief explanation:</p>
</blockquote>
<p>This code takes(<code>filter</code>) every letter(<code>sub</code>) on <code>b</code> word that exists in <code>a</code> word also. Finally returns the word which must have the same length as a(<code>[0:len(a)]</code>). The last part with <code>len</code> needs for cases like this:
<code>is_anagram('some','somenothing')</code> </p>
| 0 | 2016-09-30T18:14:18Z | [
"python",
"python-2.7",
"python-3.x"
]
|
Basic Anagram VS more advanced one | 39,797,552 | <p>I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; <em>two words are an anagram if you can rearrange the letters from one to spell the other</em>).</p>
<p>The easier solution that comes to mind is:</p>
<pre><code>def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dog')
</code></pre>
<p>It works, but it doesn't really satisfy me. If we were in this situation for example:</p>
<pre><code>def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dyog') #extra letter 'd' in second argument
>>> False
</code></pre>
<p>Return is False, although we should be able to to build the word <code>'god'</code> out of <code>'dyog'</code>. Perhaps this game/problem isn't called an anagram, but I've been trying to figure it out anyway.</p>
<p><strong>Technically my solution is to:</strong><br>
1- Iterate through every element of b.<br>
2- As I do, I check if that element exists in a.<br>
3- If all of them do; then we can create a out of b.<br>
4- Otherwise, we can't.</p>
<p>I just can't seem to get it to work. <strong>For the record, I do not know how to use <code>lambda</code></strong></p>
<p><strong>Some tests:</strong></p>
<pre><code>print is_anagram('god', 'ddog') #should return True
print is_anagram('god', '9d8s0og') #should return True
print is_anagram('god', '_@10d_o g') #should return True
</code></pre>
<p>Thanks :)</p>
| 2 | 2016-09-30T18:08:47Z | 39,797,740 | <p>If you need to check if <code>a</code> word could be created from <code>b</code> you can do this</p>
<pre><code>def is_anagram(a,b):
b_list = list(b)
for i_a in a:
if i_a in b_list:
b_list.remove(i_a)
else:
return False
return True
</code></pre>
<p><strong>UPDATE(Explanation)</strong></p>
<p><code>b_list = list(b)</code> makes a <code>list</code> of <code>str</code> objects(characters). </p>
<pre><code>>>> b = 'asdfqwer'
>>> b_list = list(b)
>>> b_list
['a', 's', 'd', 'f', 'q', 'w', 'e', 'r']
</code></pre>
<p>What basically is happening in the answer: We check if every character in <code>a</code> listed in <code>b_list</code>, when occurrence happens we remove that character from <code>b_list</code>(we do that to eliminate possibility of returning <code>True</code> with input <code>'good'</code>, <code>'god'</code>). So if there is no occurrence of another character of <code>a</code> in rest of <code>b_list</code> then it's not advanced anagram.</p>
| 1 | 2016-09-30T18:21:29Z | [
"python",
"python-2.7",
"python-3.x"
]
|
Basic Anagram VS more advanced one | 39,797,552 | <p>I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; <em>two words are an anagram if you can rearrange the letters from one to spell the other</em>).</p>
<p>The easier solution that comes to mind is:</p>
<pre><code>def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dog')
</code></pre>
<p>It works, but it doesn't really satisfy me. If we were in this situation for example:</p>
<pre><code>def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dyog') #extra letter 'd' in second argument
>>> False
</code></pre>
<p>Return is False, although we should be able to to build the word <code>'god'</code> out of <code>'dyog'</code>. Perhaps this game/problem isn't called an anagram, but I've been trying to figure it out anyway.</p>
<p><strong>Technically my solution is to:</strong><br>
1- Iterate through every element of b.<br>
2- As I do, I check if that element exists in a.<br>
3- If all of them do; then we can create a out of b.<br>
4- Otherwise, we can't.</p>
<p>I just can't seem to get it to work. <strong>For the record, I do not know how to use <code>lambda</code></strong></p>
<p><strong>Some tests:</strong></p>
<pre><code>print is_anagram('god', 'ddog') #should return True
print is_anagram('god', '9d8s0og') #should return True
print is_anagram('god', '_@10d_o g') #should return True
</code></pre>
<p>Thanks :)</p>
| 2 | 2016-09-30T18:08:47Z | 39,797,746 | <pre><code>def is_anagram(a, b):
test = sorted(a) == sorted(b)
testset = b in a
testset1 = a in b
if testset == True:
return True
if testset1 == True:
return True
else:
return False
</code></pre>
<p>No better than the other solution. But if you like verbose code, here's mine. </p>
| 0 | 2016-09-30T18:21:45Z | [
"python",
"python-2.7",
"python-3.x"
]
|
Basic Anagram VS more advanced one | 39,797,552 | <p>I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; <em>two words are an anagram if you can rearrange the letters from one to spell the other</em>).</p>
<p>The easier solution that comes to mind is:</p>
<pre><code>def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dog')
</code></pre>
<p>It works, but it doesn't really satisfy me. If we were in this situation for example:</p>
<pre><code>def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dyog') #extra letter 'd' in second argument
>>> False
</code></pre>
<p>Return is False, although we should be able to to build the word <code>'god'</code> out of <code>'dyog'</code>. Perhaps this game/problem isn't called an anagram, but I've been trying to figure it out anyway.</p>
<p><strong>Technically my solution is to:</strong><br>
1- Iterate through every element of b.<br>
2- As I do, I check if that element exists in a.<br>
3- If all of them do; then we can create a out of b.<br>
4- Otherwise, we can't.</p>
<p>I just can't seem to get it to work. <strong>For the record, I do not know how to use <code>lambda</code></strong></p>
<p><strong>Some tests:</strong></p>
<pre><code>print is_anagram('god', 'ddog') #should return True
print is_anagram('god', '9d8s0og') #should return True
print is_anagram('god', '_@10d_o g') #should return True
</code></pre>
<p>Thanks :)</p>
| 2 | 2016-09-30T18:08:47Z | 39,798,160 | <p>Since the other answers do not, at time of writing, support reversing the order:</p>
<p>Contains <a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">type hints</a> for convenience, because why not?</p>
<pre><code># Just strip hints out if you're in Python < 3.5.
def is_anagram(a: str, b: str) -> bool:
long, short = (a, b) if len(a) > len(b) else (b, a)
cut = [x for x in long if x in short]
return sorted(cut) == sorted(short)
</code></pre>
<p>If, in future, you do learn to use <code>lambda</code>, an equivalent is:</p>
<pre><code># Again, strip hints out if you're in Python < 3.5.
def is_anagram(a: str, b: str) -> bool:
long, short = (a, b) if len(a) > len(b) else (b, a)
# Parentheses around lambda are not necessary, but may help readability
cut = filter((lambda x: x in short), long)
return sorted(cut) == sorted(short)
</code></pre>
| 1 | 2016-09-30T18:45:40Z | [
"python",
"python-2.7",
"python-3.x"
]
|
Basic Anagram VS more advanced one | 39,797,552 | <p>I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; <em>two words are an anagram if you can rearrange the letters from one to spell the other</em>).</p>
<p>The easier solution that comes to mind is:</p>
<pre><code>def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dog')
</code></pre>
<p>It works, but it doesn't really satisfy me. If we were in this situation for example:</p>
<pre><code>def is_anagram(a, b):
return sorted(a) == sorted(b)
print is_anagram('god', 'dyog') #extra letter 'd' in second argument
>>> False
</code></pre>
<p>Return is False, although we should be able to to build the word <code>'god'</code> out of <code>'dyog'</code>. Perhaps this game/problem isn't called an anagram, but I've been trying to figure it out anyway.</p>
<p><strong>Technically my solution is to:</strong><br>
1- Iterate through every element of b.<br>
2- As I do, I check if that element exists in a.<br>
3- If all of them do; then we can create a out of b.<br>
4- Otherwise, we can't.</p>
<p>I just can't seem to get it to work. <strong>For the record, I do not know how to use <code>lambda</code></strong></p>
<p><strong>Some tests:</strong></p>
<pre><code>print is_anagram('god', 'ddog') #should return True
print is_anagram('god', '9d8s0og') #should return True
print is_anagram('god', '_@10d_o g') #should return True
</code></pre>
<p>Thanks :)</p>
| 2 | 2016-09-30T18:08:47Z | 39,798,666 | <p>I think all this sorting is a red herring; the letters should be counted instead.</p>
<pre><code>def is_anagram(a, b):
return all(a.count(c) <= b.count(c) for c in set(a))
</code></pre>
<p>If you want efficiency, you can construct a dictionary that counts all the letters in <code>b</code> and decrements these counts for each letter in <code>a</code>. If any count is below 0, there are not enough instances of the character in <code>b</code> to create <code>a</code>. This is an <code>O(a + b)</code> algorithm.</p>
<pre><code>from collections import defaultdict
def is_anagram(a, b):
b_dict = defaultdict(int)
for char in b:
b_dict[char] += 1
for char in a:
b_dict[char] -= 1
if b_dict[char] < 0:
return False
return True
</code></pre>
<p>Iterating over <code>b</code> is inevitable since you need to count all the letters there. This will exit as soon as a character in <code>a</code> is not found, so I don't think you can improve this algorithm much.</p>
| 0 | 2016-09-30T19:20:34Z | [
"python",
"python-2.7",
"python-3.x"
]
|
scipy.optimize compact constraints | 39,797,606 | <p>I have a np.array A of length 9 and it is the variable in the objective function. </p>
<pre><code>A = [ a1, a2, a3,
b1, b2, b3,
c1, c2, c3], where a1...c3 are real numbers.
with constraints: a1 > a2, a2 > a3,
b1 > b2, b2 > b3,
c1 > c2, c2 > c3
</code></pre>
<p>Is there any easy way to write the constraints? currently I have the following code, but as the array size gets larger, it is difficult to write them all.</p>
<pre><code>cons = (
{'type':'ineq',
'fun': lambda x : np.array([x[0]-x[1]])
}
,
{'type':'ineq',
'fun': lambda x : np.array([x[1]-x[2]])
}
,
{'type':'ineq',
'fun': lambda x : np.array([x[3]-x[4]])
}
,
{'type':'ineq',
'fun': lambda x : np.array([x[4]-x[5]])
}
,
{'type':'ineq',
'fun': lambda x : np.array([x[6]-x[7]])
}
,
{'type':'ineq',
'fun': lambda x : np.array([x[7]-x[8]])
}
)
</code></pre>
| 2 | 2016-09-30T18:12:52Z | 39,798,108 | <p>I would imagine scipy likes a numeric output from each of these functions rather than boolean, so that rules out more than two inputs per function... (degrees of freedom and all that isht) what you can do is write a list comprehension to make the functions for you...</p>
<pre><code>cons = ({'type':'ineq', 'fun': lambda x: x[i] - x[i+1]} for i in range(len(A)-1))
</code></pre>
<p>I'm not sure why you would need to cast the result of subtraction to a 1-length array, so I left it out.. it's easy to put back in</p>
| 0 | 2016-09-30T18:42:35Z | [
"python",
"optimization",
"scipy"
]
|
scipy.optimize compact constraints | 39,797,606 | <p>I have a np.array A of length 9 and it is the variable in the objective function. </p>
<pre><code>A = [ a1, a2, a3,
b1, b2, b3,
c1, c2, c3], where a1...c3 are real numbers.
with constraints: a1 > a2, a2 > a3,
b1 > b2, b2 > b3,
c1 > c2, c2 > c3
</code></pre>
<p>Is there any easy way to write the constraints? currently I have the following code, but as the array size gets larger, it is difficult to write them all.</p>
<pre><code>cons = (
{'type':'ineq',
'fun': lambda x : np.array([x[0]-x[1]])
}
,
{'type':'ineq',
'fun': lambda x : np.array([x[1]-x[2]])
}
,
{'type':'ineq',
'fun': lambda x : np.array([x[3]-x[4]])
}
,
{'type':'ineq',
'fun': lambda x : np.array([x[4]-x[5]])
}
,
{'type':'ineq',
'fun': lambda x : np.array([x[6]-x[7]])
}
,
{'type':'ineq',
'fun': lambda x : np.array([x[7]-x[8]])
}
)
</code></pre>
| 2 | 2016-09-30T18:12:52Z | 39,798,604 | <p>Apparently, your constraint is that each column of <code>A</code> should be (element-wise) greater than or equal to the column to its right. </p>
<p>You can formulate a single, vector-outpur constraint as follows:</p>
<pre><code>def cons_fun(x):
A = x.reshape(3,3) # change "(3,3)" according to the dimensions of A
return np.array([A[:,i]-A[:,i+1] for i in range(3-1)]).ravel() # change "3" accordingly
cons = ({'type':'ineq',
'fun' : cons_fun},)
</code></pre>
<p>From my experience with <code>SLSQP</code>, vector-output constraints result in a faster optimization time than providing multiple scalar-output constraints.</p>
| 1 | 2016-09-30T19:15:39Z | [
"python",
"optimization",
"scipy"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.