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 |
|---|---|---|---|---|---|---|---|---|---|
Zero date in mysql select using python
| 39,363,548
|
<p>I have a python script which selects some rows from a table and insert them into another table. One field has type of date and there is a problem with its data when its value is '0000-00-00'. python converts this value to None and so gives an error while inserting it into the second table.</p>
<p>How can I solve this problem? Why python converts that value to None?</p>
<p>Thank you in advance.</p>
| 0
|
2016-09-07T07:18:36Z
| 39,364,372
|
<p>This is actually a None value in the data base, in a way. MySQL treats '0000-00-00' specially.
From <a href="http://dev.mysql.com/doc/refman/5.7/en/date-and-time-types.html" rel="nofollow">MySQL documentation</a>:</p>
<blockquote>
<p>MySQL permits you to store a âzeroâ value of '0000-00-00' as a âdummy
date.â This is in some cases more convenient than using NULL values,
and uses less data and index space. To disallow '0000-00-00', enable
the NO_ZERO_DATE mode.</p>
</blockquote>
<p>It seems that Python's MySQL library is trying to be nice to you and converts this to None.</p>
<p>When writing, it cannot guess that you wanted '0000-00-00' and uses NULL instead. You should convert it yourself. For example, this might work:</p>
<pre><code>if value_read_from_one_table is not None:
value_written_to_the_other_table = value_read_from_one_table
else:
value_written_to_the_other_table = '0000-00-00'
</code></pre>
| 0
|
2016-09-07T08:01:44Z
|
[
"python",
"mysql",
"date",
"select"
] |
javascript-POST request using ajax in Django issue
| 39,363,590
|
<p>I am a beginner and self learned programmer and have written a code on my own. I am attempting to use Javascript post request using ajax and facing some continuous problem. There are lot of mistakes in code and want you guys to correct it with an explanation. Here is my base.js file:</p>
<pre><code>var user = {
signup : function() {
var firstname = document.signupform.first_name.value;
var lastname = document.signupform.last_name.value;
var username = document.signupform.username.value;
var email = document.signupform.email.value;
var password = document.signupform.password.value;
var confirmpassword = document.signupform.confirmpassword.value;
if (firstname == "")
{
alert("Please provide your first name!")
document.signupform.first_name.focus();
}
else if (username == "")
{
alert("Please provide the username!")
document.signupform.username.focus();
}
else if (email == "")
{
alert("Please provide your Email!")
document.signupform.email.focus() ;
}
else if (password == "")
{
alert("Please enter a valid password")
document.signupform.password.focus() ;
}
else if (password != confirmpassword)
{
alert("Passwords do not match.");
document.signupform.confirmpassword.focus() ;
}
else
{
data = {"firstname":firstname, "lastname":lastname, "username":username, "email":email,"password":password};
this.postRequest(data);
}
return false
},
postRequest:function(data,url,form)
{
$.ajax({
type: "POST",
url: '',
data: data,
success: function(data){
if(data["success"])
{
window.location.href = '{% url home %}'
}
else
{
alert(data["error"])
}
}
});
},
</code></pre>
<p>views.py:</p>
<pre><code>class UserFormView (TemplateView):
template_name = "signup.html"
#display signup blank form
def get(self, request,*args,**kwargs):
context = super(UserFormView,self).get_context_data(**kwargs)
return self.render_to_response(context)
#process form data
def post(self, request,*args,**kwargs):
context = {}
data = request.POST
user = get_user_model().objects.create(username=data["username"],first_name=data["firstname"],email=data["email"],last_name=data["lastname"])
user.set_password(data["password"])
user.save()
user.backend = "django.contrib.auth.backends.ModelBackend"
if user is not None:
login(request, user)
context["success"] = True
# return redirect("home")
else:
context["success"] = False
context["error"] = "The username is already taken!"
return self.render_to_response(context)
</code></pre>
<p>I am putting 'onclick' function in my signup.html:</p>
<pre><code><a class="btn btn-success" href="javascript:void(0)" onclick="user.signup()">Sign Up</a>
</code></pre>
<p>I am getting an error of csrf as well.</p>
| 1
|
2016-09-07T07:20:20Z
| 39,363,779
|
<p>if you direct pass the data to the server you need to pass csrf token, or else just put {% csrf_token %} inside the form and submit the form data after the validation.</p>
<pre><code>var formData = new FormData($(this)[0]); ## Active
$.ajax({
url: "{% url 'apply_job' %}",
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function (returndata)
{
if(returndata.status == 'success')
{document.getElementById('result').innerHTML = returndata.result
Callback();
}
else if(returndata.status == 'error')
{
document.getElementById('result').innerHTML = returndata.result
Callback();
}
}
});
</code></pre>
| 1
|
2016-09-07T07:29:59Z
|
[
"javascript",
"jquery",
"python",
"ajax",
"django"
] |
cx_freeze and docx - problems when freezing
| 39,363,615
|
<p>I have a simple program that takes input from the user and then does scraping with selenium. Since the user doesn't have Python environment installed I would like to convert it to *.exe. I usually use cx_freeze for that and I have successfully converted .py programs to .exe. At first it was missing some modules (like lxml) but I was able to solve it. Now I think I only have problem with docx package.</p>
<p>This is how I initiate the new document in my program (I guess this is what causes me problems):</p>
<pre><code>doc = Document()
#then I do some stuff to it and add paragraph and in the end...
doc.save('results.docx')
</code></pre>
<p>When I run it from python everything works fine but when I convert to exe I get this error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\tyszkap\AppData\Local\Continuum\Anaconda3\lib\site-packages\cx_Freeze\initscripts\Console.py", line 27, in <module>
exec(code, m.__dict__)
File "tribunalRio.py", line 30, in <module>
File "C:\Users\tyszkap\AppData\Local\Continuum\Anaconda3\lib\site-packages\docx\api.py", line 25, in Document
document_part = Package.open(docx).main_document_part
File "C:\Users\tyszkap\AppData\Local\Continuum\Anaconda3\lib\site-packages\docx\opc\package.py", line 116, in open
pkg_reader = PackageReader.from_file(pkg_file)
File "C:\Users\tyszkap\AppData\Local\Continuum\Anaconda3\lib\site-packages\docx\opc\pkgreader.py", line 32, in from_file
phys_reader = PhysPkgReader(pkg_file)
File "C:\Users\tyszkap\AppData\Local\Continuum\Anaconda3\lib\site-packages\docx\opc\phys_pkg.py", line 31, in __new__
"Package not found at '%s'" % pkg_file
docx.opc.exceptions.PackageNotFoundError: Package not found at 'C:\Users\tyszkap\Dropbox (Dow Jones)\Python Projects\build\exe.win-a
md64-3.4\library.zip\docx\templates\default.docx'
</code></pre>
<p>This is my setup.py program:</p>
<pre><code>from cx_Freeze import setup, Executable
executable = Executable( script = "tribunalRio.py" )
# Add certificate to the build
options = {
"build_exe": {'include_files' : ['default.docx'],
'packages' : ["lxml._elementpath", "inspect", "docx", "selenium"]
}
}
setup(
version = "0",
requires = [],
options = options,
executables = [executable])
</code></pre>
<p>I thought that explicitly adding default.docx to the package would solve the problem (I have even tried adding it to the library.zip but it gives me even more errors) but it didn't. I have seen this <a href="http://stackoverflow.com/questions/30543169/cx-freeze-exe-failing-to-completely-import-docx">post</a> but I don't know what they mean by:</p>
<blockquote>
<p>copying the docx document.py module inside my function (instead of
using Document()</p>
</blockquote>
<p>Any ideas? I know that freezing is not the best solution but I really don't want to build a web interface for such a simple program...</p>
<p>EDIT:</p>
<p>I have just tried <a href="http://cx-freeze.readthedocs.io/en/latest/faq.html#using-data-files" rel="nofollow">this solution</a> :</p>
<pre><code>def find_data_file(filename):
if getattr(sys, 'frozen', False):
# The application is frozen
datadir = os.path.dirname(sys.executable)
else:
# The application is not frozen
# Change this bit to match where you store your data files:
datadir = os.path.dirname(__file__)
return os.path.join(datadir, filename)
doc = Document(find_data_file('default.docx'))
</code></pre>
<p>but again receive Traceback error (but the file is in this location...):</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\tyszkap\AppData\Local\Continuum\Anaconda3\lib\site-packages\cx_Freeze\initscripts\Console.py", line 27, in <module>
exec(code, m.__dict__)
File "tribunalRio.py", line 43, in <module>
File "C:\Users\tyszkap\AppData\Local\Continuum\Anaconda3\lib\site-packages\docx\api.py", line 25, in Document
document_part = Package.open(docx).main_document_part
File "C:\Users\tyszkap\AppData\Local\Continuum\Anaconda3\lib\site-packages\docx\opc\package.py", line 116, in open
pkg_reader = PackageReader.from_file(pkg_file)
File "C:\Users\tyszkap\AppData\Local\Continuum\Anaconda3\lib\site-packages\docx\opc\pkgreader.py", line 32, in from_file
phys_reader = PhysPkgReader(pkg_file)
File "C:\Users\tyszkap\AppData\Local\Continuum\Anaconda3\lib\site-packages\docx\opc\phys_pkg.py", line 31, in __new__
"Package not found at '%s'" % pkg_file
docx.opc.exceptions.PackageNotFoundError: Package not found at 'C:\Users\tyszkap\Dropbox (Dow Jones)\Python Projects\build\exe.win-a
md64-3.4\default.docx'
</code></pre>
<p>What am I doing wrong?</p>
| 0
|
2016-09-07T07:21:39Z
| 39,381,577
|
<p>I expect you'll find the problem has to do with your freezing operation not placing the default Document() template in the expected location. It's stored as package data in the python-docx package as <code>docx/templates/default.docx</code> (see setup.py here: <a href="https://github.com/python-openxml/python-docx/blob/master/setup.py#L37" rel="nofollow">https://github.com/python-openxml/python-docx/blob/master/setup.py#L37</a>)</p>
<p>I don't know how to fix that in your case, but that's where the problem is it looks like.</p>
| 0
|
2016-09-08T02:14:00Z
|
[
"python",
"python-3.x",
"cx-freeze",
"python-docx"
] |
python subprocess Popen behaving differently on local and remote system
| 39,363,629
|
<p>I am using django and sending a build to travis-ci which is failing the build on my tests. The line that is in question is in this function...</p>
<pre><code>from subprocess import Popen, PIPE
def make_mp3(path, blob):
process = Popen(
['lame', '-', '--comp', '40', path], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout_data = process.communicate(input=blob.read())
return stdout_data
</code></pre>
<p>the line that calls the function is here:</p>
<pre><code>make_mp3(mp3_path, request.FILES['audio_file'])
</code></pre>
<p>on my local system the tests run fine and pass. I have been using this function for a while and it always behaves as expected. But when I send it to travis-ci for a build it gives me this traceback...</p>
<pre><code>======================================================================
ERROR: test_post_upload_audio_word (define.tests.ViewTests)
Testing the audio upload function for word audio
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/build/deltaskelta/langalang/define/tests.py", line 827, in test_post_upload_audio_word
'audio_file': audio_file})
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/test/client.py", line 541, in post
secure=secure, **extra)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/test/client.py", line 343, in post
secure=secure, **extra)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/test/client.py", line 409, in generic
return self.request(**r)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/test/client.py", line 494, in request
six.reraise(*exc_info)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/utils/decorators.py", line 63, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(*args, **kwargs)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/utils/decorators.py", line 63, in bound_func
return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/travis/build/deltaskelta/langalang/define/views.py", line 21, in dispatch
return super(Define, self).dispatch(*args, **kwargs)
File "/home/travis/virtualenv/python2.7.12/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/home/travis/build/deltaskelta/langalang/define/views.py", line 89, in post
return upload_audio(request, context)
File "/home/travis/build/deltaskelta/langalang/define/views_func.py", line 251, in upload_audio
make_mp3(mp3_path, request.FILES['audio_file'])
File "/home/travis/build/deltaskelta/langalang/define/views_func.py", line 25, in make_mp3
['lame', '-', '--comp', '40', path], stdin=PIPE, stdout=PIPE, stderr=PIPE)
File "/opt/python/2.7.12/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/opt/python/2.7.12/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
</code></pre>
<p>I cannot see why this would pass the test on my system and fail on the build. The input file is obviously there because <code>request.FILES</code> found it. The directory exists..I checked. So what is it telling me doesn't exist? </p>
| 2
|
2016-09-07T07:22:02Z
| 39,364,401
|
<p>Reason it fails: execution command can't execute non-existent file. It's <code>lame</code> in your example. Quote from <a href="https://docs.python.org/2/library/subprocess.html#exceptions" rel="nofollow">doc section</a>:</p>
<blockquote>
<p>The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSError exceptions.</p>
</blockquote>
<p>You also could check source code for <code>_execute_child</code> method in <code>subprocess.py</code> near the end.</p>
| 2
|
2016-09-07T08:02:48Z
|
[
"python",
"django",
"travis-ci"
] |
Replace userinput list elements from master dictionary?
| 39,363,762
|
<p>Here, i have a master dic whose value consist of list of list.</p>
<p>Whenever user inputs the value as a list of list, i want my program to replace those user input list from the master list.</p>
<p>I have tried and it is giving me expected output but it consists of lot of temporary lists which is annoying , Is there any other pythonic way to achieve the same without using unwanted temporary list ?</p>
<p>Input dic :</p>
<pre><code>master_dic = {
'First': [[{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}], [{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}],
[{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}], [{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}]],
'Second': [[{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}], [{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}],
[{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}], [{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}]],
'Third': [[{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}], [{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}],
[{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}], [{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}]],
'Forth': [[{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}], [{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}],
[{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}], [{'A': '#d8', 'B': '#d7'}, {'C': '#d8', 'D': '#d7'}]]
}
</code></pre>
<p>My Code : </p>
<pre><code>userinput = [[['First'], ['Forth']], [['Second'], ['First']], ['Third'], ['Forth']]
outer = []
for i in userinput:
new = []
if len(i) > 1:
temp = []
for j in i:
jj = master_dic[j[0]]
temp.append(jj)
new.append(temp)
outer.append(new)
else:
for k in i:
kk = master_dic[k]
new.append(kk)
outer.append(new)
data_join = [i[0] for i in outer]
</code></pre>
<p>Output :</p>
<pre><code>[
[[[{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}]], [[{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}]]],
[[[{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}]], [[{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}]]],
[[{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}]],
[[{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}], [{'A': '#d8', 'B': '#d7'}, {'D': '#d7', 'C': '#d8'}]]
]
</code></pre>
<p>No of list to be maintained </p>
<pre><code>[
[[[ {First value} ]], [[ {Forth value} ]]],
[[[ {Second value} ]],[[ {First value} ]]],
[[ {Third value} ]],
[[ {Forth value} ]]
]
</code></pre>
| 2
|
2016-09-07T07:29:01Z
| 39,377,442
|
<p>I think this is what you want</p>
<pre><code>def array_replace(userinput,master_dic):
for i,data in enumerate(userinput):
if isinstance(data, list):
found=array_replace(data,master_dic)
if not isinstance(found, list):
userinput[i]=master_dic[found]
else:
return data
return userinput
</code></pre>
<p><strong><a href="https://repl.it/DUks" rel="nofollow">DEMO</a></strong></p>
<p>Hope this helps</p>
| 1
|
2016-09-07T19:09:34Z
|
[
"python",
"list",
"dictionary"
] |
Encoding/Decoding AES CTR between php and python
| 39,363,782
|
<p>I am connecting to an php API.
In their examples they encode everything with the following:</p>
<blockquote>
<p>$data=AesCtr::encrypt($data, 'api_key_for_project', 256)</p>
</blockquote>
<p>I would like to connect via pythons pycrypto module and do the equivalent to the above.</p>
<p>I have tried a few different things although the server is unable to decode the message.</p>
<p>I know the 'counter' is not correct by being random however i cant think of an alternative.</p>
<pre><code>from Crypto.Cipher import AES
cipher = AES.new(api_key, AES.MODE_CTR, counter=lambda: os.urandom(16))
data = cipher.encrypt(b'{"name": "Test"}'))
</code></pre>
| 0
|
2016-09-07T07:30:08Z
| 39,366,163
|
<p>Commonly, the counter values in CTR mode consist of:</p>
<ul>
<li>a prefix/nonce which must be unique for each message to be encrypted, but stays the same between blocks of one message. E.g. <code>os.urandom(8)</code> is a decent nonce (unless you encrypt more than about 2^32 messages with the same key).</li>
<li>the actual counter, which is 0 for the first block, 1 for the second, and so on.</li>
</ul>
<p>See <a href="https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29" rel="nofollow">Wikipedia</a> for an illustration and details. The prefix/counter split could be 96/32 bits, 64/64 bits, etc. Other variations, such as a postfix nonce, are possible but rare. Note that the receiver must learn the nonce somehow, the easiest way is to send it with the ciphertext (the nonce does not have to be encrypted).</p>
<p>So, how do you do this with pycrypto? Well, the <code>counter</code> function should be a stateful function (closure) that returns <code>prefix</code> plus the current counter value and increments the counter. Fortunately you don't have to write that yourself, pycrypto has a utility for it: <code>Crypto.Util.Counter</code>.</p>
<pre><code>import os
from Crypto.Cipher import AES
from Crypto.Util import Counter
nonce = os.urandom(8)
counter = Counter.new(64, prefix=nonce)
cipher = AES.new(api_key, AES.MODE_CTR, counter=counter)
data = nonce + cipher.encrypt(b'{"name": "Test"}')
</code></pre>
<p>Here, I prepended the nonce to the ciphertext. The receiver will need to strip the first 64 bits from the data and use them as the prefix for the counter.</p>
<p>I don't know how exactly the <code>AesCtr</code> PHP class is implemented. If it is the same as the one in <a href="http://stackoverflow.com/questions/10220271/php-class-declarations-may-not-be-nested">this question</a>, then it looks like it also prepends the 64-bit nonce to the ciphertext. So the above code might already Just Work (tm) for talking to the PHP API.</p>
<p>Side note: The <code>AesCtr</code> class from that question also creates a timestamp-based nonce instead of a completely random one (see <code>AesCtr::encrypt</code>), with the aim to ensure uniqueness. You could consider using the same approach to generate nonces.</p>
| 1
|
2016-09-07T09:29:20Z
|
[
"php",
"python",
"encryption"
] |
Python: regular expressions in url
| 39,363,786
|
<p>I have some url like</p>
<pre><code>https://www.avito.ru/chelyabinsk/avtomobili/audi_a4_2014_818414044
</code></pre>
<p>And I need to get pattern from this. I know, that * is the symbol, that can replace any symbol, but when I try <code>https://www.avito.ru/*/avtomobili</code> it doesn't open this url.
How can I fix that?</p>
| -4
|
2016-09-07T07:30:19Z
| 39,363,874
|
<p><code>*</code> means match the last symbol zero or more times.</p>
<p>For example, <code>x*</code> matches 'xxxxxxx....', and <code>[a-z]*</code> matches 'abcsiiwdqhwid...'.</p>
<p>Why not try </p>
<pre><code>https://www.avito.ru/[a-z]*/avtomobili
</code></pre>
<p>or</p>
<pre><code>https://www.avito.ru/.*?/avtomobili
</code></pre>
| 0
|
2016-09-07T07:34:48Z
|
[
"python",
"regex"
] |
Python: regular expressions in url
| 39,363,786
|
<p>I have some url like</p>
<pre><code>https://www.avito.ru/chelyabinsk/avtomobili/audi_a4_2014_818414044
</code></pre>
<p>And I need to get pattern from this. I know, that * is the symbol, that can replace any symbol, but when I try <code>https://www.avito.ru/*/avtomobili</code> it doesn't open this url.
How can I fix that?</p>
| -4
|
2016-09-07T07:30:19Z
| 39,365,240
|
<p>From your example, to match </p>
<pre><code>https://www.avito.ru/chelyabinsk/avtomobili/audi_a4_2014_818414044
</code></pre>
<p>you would need to have a regex of</p>
<pre><code>https://www\.avito\.ru/.*?/avtomobili
</code></pre>
<p>in <code>https://www.avito.ru/XXXXXX/avtomobili</code> : <code>XXXXXX</code> can be anything</p>
<p><code>.*?</code> means match anything (as little as possible) until you get to /avtomobili</p>
<p>You also need to escape any DOT like this <code>\.</code></p>
| 0
|
2016-09-07T08:47:16Z
|
[
"python",
"regex"
] |
reportlab add font with registerFont
| 39,363,800
|
<p>I've to use the registerFontFamily method from reportlab.pdfbase.pdfmetrics.
I tried to add two fonts to a family but I can't use the bold font with "<<em>b>sometext<</em>/b>". I need this feature for my report. I can only use the regular one and I don't know why. </p>
<p>Here's the code.</p>
<pre><code>registerFont(TTFont('Own_Font', os.path.dirname(os.path.abspath(__file__)) + '\\OwnSans-Regular.ttf'))
registerFont(TTFont('OwnBold_Font', os.path.dirname(os.path.abspath(__file__)) + '\\OwnSans-Bold.ttf'))
registerFontFamily('Own_Font',normal='Own_Font',bold='OwnBold_Font')
# define parameter for the page and paragraph font
PAGE_WIDTH, PAGE_HEIGHT = landscape(A4)
STYLES = getSampleStyleSheet()
STYLES.add( ParagraphStyle(name='Text', fontName = 'Own_Font', fontSize = 10 ))
STYLES.add( ParagraphStyle(name='Centered', fontName = 'Own_Font', fontSize = 10, alignment=TA_CENTER ))
STYLES.add( ParagraphStyle(name='CenteredBig', parent=STYLES['Centered'], fontSize=18, spaceAfter=10) )
STYLES.add( ParagraphStyle(name='CenteredMedium', parent=STYLES['Centered'], fontSize=15, spaceAfter=10) )
</code></pre>
<p>I've got the following error message:</p>
<pre><code> File "X:\tools\Python2\lib\site-packages\reportlab-2.7-py2.7-win32.egg\reportlab\platypus\paragraph.py", line 916, in __init__
self._setup(text, style, bulletText or getattr(style,'bulletText',None), frags, cleanBlockQuotedText)
File "X:\tools\Python2\lib\site-packages\reportlab-2.7-py2.7-win32.egg\reportlab\platypus\paragraph.py", line 938, in _setup
style, frags, bulletTextFrags = _parser.parse(text,style)
File "X:\tools\Python2\lib\site-packages\reportlab-2.7-py2.7-win32.egg\reportlab\platypus\paraparser.py", line 1083, in parse
self.feed(text)
File "X:\tools\Python2\lib\site-packages\reportlab-2.7-py2.7-win32.egg\reportlab\lib\xmllib.py", line 562, in finish_starttag
self.handle_starttag(tag, method, attrs)
File "X:\tools\Python2\lib\site-packages\reportlab-2.7-py2.7-win32.egg\reportlab\lib\xmllib.py", line 596, in handle_starttag
method(attrs)
File "X:\tools\Python2\lib\site-packages\reportlab-2.7-py2.7-win32.egg\reportlab\platypus\paraparser.py", line 823, in start_para
self._stack = [self._initial_frag(attr,_paraAttrMap)]
File "X:\tools\Python2\lib\site-packages\reportlab-2.7-py2.7-win32.egg\reportlab\platypus\paraparser.py", line 817, in _initial_frag
frag.fontName, frag.bold, frag.italic = ps2tt(style.fontName)
File "X:\tools\Python2\lib\site-packages\reportlab-2.7-py2.7-win32.egg\reportlab\lib\fonts.py", line 75, in ps2tt
raise ValueError("Can't map determine family/bold/italic for %s" % psfn)
ValueError: Can't map determine family/bold/italic for Own_Font
</code></pre>
<p>Thank you in advance.</p>
| 0
|
2016-09-07T07:30:56Z
| 39,368,866
|
<p>The first problem is that you made a typo in the <code>registerFontFamily</code>. To be more specific you register the normal font as being the bold by doing <code>bold='Own_Font'</code>.</p>
<p>The second problem is that your font family doesn't have fonts for all types (in this case italic and boldItalic). According to the manual, if you read Vera as <code>Own_font</code>:</p>
<blockquote>
<p>If we only have a Vera regular font, no bold or italic then we must map all to the same internal fontname. <code><b></code> and <code><i></code> tags may now be used safely, but have no effect. After registering and mapping the Vera font as</p>
</blockquote>
<p>Thus to fix it you should replace the affected line like this:</p>
<pre><code>registerFontFamily('Own_Font',normal='Own_Font',bold='OwnrBold_Font',italic='Own_Font',boldItalic='OwnrBold_Font')
</code></pre>
<p>This should make <code><b></b></code> function as expected.</p>
| 0
|
2016-09-07T11:37:11Z
|
[
"python",
"pdf",
"fonts",
"reportlab"
] |
Merging rows into one with same column cells and keep data from all into the merged row using python script
| 39,363,836
|
<p>I need to merge more rows into one but in the way i can keep all data in all columns into the merged row in my .csv file. The rows which i need to merge are one who have same email cells. The first table in the picture is how i have now and the second how should be.</p>
<p><a href="http://i.stack.imgur.com/tgpuh.png" rel="nofollow">enter image description here</a></p>
<p>I need to do this with Python script. Can anyone help me?</p>
<p>Thank you Igor</p>
| 0
|
2016-09-07T07:33:09Z
| 39,364,218
|
<p>my idea: start at row 1, take the email and store it in a list. </p>
<p>Now compare each entry of the the hole email column with the email from row 1. If its equal then find out which fields in your row are empty and if the found entry has one of these filled out. </p>
<p>Write the concatenated row down and go on with the second row/email. </p>
<p>Dont forget to check if the new email has already checked (see if there is a entry in the list from start) and go on.</p>
<p>A bit of work but very low level, im pretty sure there is a smarter solution, but this should work too.</p>
| 0
|
2016-09-07T07:54:16Z
|
[
"python",
"csv",
"merge",
"rows"
] |
Mimicing glib.spawn_async with Popenâ¦
| 39,364,128
|
<p>The function <a href="http://www.pygtk.org/docs/pygobject/glib-functions.html#function-glib--spawn-async" rel="nofollow">glib.spawn_async</a> allows you to hook three callbacks which are called on event on <code>stdout</code>, <code>stderr</code>, and on process completion.</p>
<p><em>How can I mimic the same functionality with <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">subprocess</a> with either threads or asyncio?</em></p>
<p>I am more interested in the functionality rather than threading/asynio but an answer that contains both will earn a bounty.</p>
<p>Here is a toy program that shows what I want to do:</p>
<pre><code>import glib
import logging
import os
import gtk
class MySpawn(object):
def __init__(self):
self._logger = logging.getLogger(self.__class__.__name__)
def execute(self, cmd, on_done, on_stdout, on_stderr):
self.pid, self.idin, self.idout, self.iderr = \
glib.spawn_async(cmd,
flags=glib.SPAWN_DO_NOT_REAP_CHILD,
standard_output=True,
standard_error=True)
fout = os.fdopen(self.idout, "r")
ferr = os.fdopen(self.iderr, "r")
glib.child_watch_add(self.pid, on_done)
glib.io_add_watch(fout, glib.IO_IN, on_stdout)
glib.io_add_watch(ferr, glib.IO_IN, on_stderr)
return self.pid
if __name__ == '__main__':
logging.basicConfig(format='%(thread)d %(levelname)s: %(message)s',
level=logging.DEBUG)
cmd = '/usr/bin/git ls-remote https://github.com/DiffSK/configobj'.split()
def on_done(pid, retval, *args):
logging.info("That's all folks!â¦")
def on_stdout(fobj, cond):
"""This blocks which is fine for this toy exampleâ¦"""
for line in fobj.readlines():
logging.info(line.strip())
return True
def on_stderr(fobj, cond):
"""This blocks which is fine for this toy exampleâ¦"""
for line in fobj.readlines():
logging.error(line.strip())
return True
runner = MySpawn()
runner.execute(cmd, on_done, on_stdout, on_stderr)
try:
gtk.main()
except KeyboardInterrupt:
print('')
</code></pre>
<p>I should add that since <code>readlines()</code> is blocking, the above will buffer all the output and send it at once. If this is not what one wants, then you have to use <code>readline()</code> and make sure that on end of command you finish reading all the lines you did not read before.</p>
| 13
|
2016-09-07T07:48:44Z
| 39,485,708
|
<p>asyncio has <a href="https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.AbstractEventLoop.subprocess_exec" rel="nofollow">subprocess_exec</a>, there is no need to use the subprocess module at all:</p>
<pre><code>import asyncio
class Handler(asyncio.SubprocessProtocol):
def pipe_data_received(self, fd, data):
# fd == 1 for stdout, and 2 for stderr
print("Data from /bin/ls on fd %d: %s" % (fd, data.decode()))
def pipe_connection_lost(self, fd, exc):
print("Connection lost to /bin/ls")
def process_exited(self):
print("/bin/ls is finished.")
loop = asyncio.get_event_loop()
coro = loop.subprocess_exec(Handler, "/bin/ls", "/")
loop.run_until_complete(coro)
loop.close()
</code></pre>
<p>With subprocess and threading, it's simple as well. You can just spawn a thread per pipe, and one to <code>wait()</code> for the process:</p>
<pre><code>import subprocess
import threading
class PopenWrapper(object):
def __init__(self, args):
self.process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.DEVNULL)
self.stdout_reader_thread = threading.Thread(target=self._reader, args=(self.process.stdout,))
self.stderr_reader_thread = threading.Thread(target=self._reader, args=(self.process.stderr,))
self.exit_watcher = threading.Thread(target=self._exit_watcher)
self.stdout_reader_thread.start()
self.stderr_reader_thread.start()
self.exit_watcher.start()
def _reader(self, fileobj):
for line in fileobj:
self.on_data(fileobj, line)
def _exit_watcher(self):
self.process.wait()
self.stdout_reader_thread.join()
self.stderr_reader_thread.join()
self.on_exit()
def on_data(self, fd, data):
return NotImplementedError
def on_exit(self):
return NotImplementedError
def join(self):
self.process.wait()
class LsWrapper(PopenWrapper):
def on_data(self, fd, data):
print("Received on fd %r: %s" % (fd, data))
def on_exit(self):
print("Process exited.")
LsWrapper(["/bin/ls", "/"]).join()
</code></pre>
<p>However, mind that glib does <em>not</em> use threads to asynchroneously execute your callbacks. It uses an event loop, just as asyncio does. The idea is that at the core of your program is a loop that waits until something happens, and then synchronously executes an associated callback. In your case, that's "data becomes available for reading on one of the pipes", and "the subprocess has exited". In general, its also stuff like "the X11-server reported mouse movement", "there's incoming network traffic", etc. You can emulate glib's behaviour by writing your own event loop. Use the <a href="https://docs.python.org/3/library/select.html?highlight=select#module-select" rel="nofollow"><code>select</code> module</a> on the two pipes. If select reports that the pipes are readable, but <code>read</code> returns no data, the process likely exited - call the <code>poll()</code> method on the subprocess object in this case to check whether it is completed, and call your exit callback if it has, or an error callback elsewise.</p>
| 4
|
2016-09-14T08:22:13Z
|
[
"python",
"multithreading",
"gtk",
"glib",
"python-asyncio"
] |
How to compile and package a python file into an execution file under windows 64bit
| 39,364,224
|
<p>Recently, I started to use theano to do some basic BP network. The theano was installed and my network based on theano works well in my PC.
In order to share my code among my colleagues, I am looking for a method to package the theano python file to one execution file which can be run under windows without python environment.</p>
<p>I am trying py2exe to finish the packaging work and I found that, the packaged exe can only work in my PC. When I copy the exe to other PCs without python, it does not work. Only warning message is giving as:</p>
<pre><code>âWARNING (theano.configdefaults): g++ not detected !
Theano will be unable to execute optimized C-implementations (for both CPU and GPU) and will default to Python implementations. Performance will be severely degraded. To remove this warning, set Theano flags cxx to an empty string.â
</code></pre>
<p>My <strong>working environment</strong> is:
<strong>Win10 64bit + Anaconda2</strong></p>
<p>Could anyone give me some advice to generate the exe file based on theano python file?</p>
<p>Thank you a lot.</p>
| 0
|
2016-09-07T07:54:29Z
| 39,365,047
|
<p>Try <a href="http://www.pyinstaller.org/" rel="nofollow">PyInstaller</a></p>
<p>PyInstaller is a program that freezes (packages) Python programs into stand-alone executables, under Windows, Linux, Mac OS X, FreeBSD, Solaris and AIX.</p>
| 0
|
2016-09-07T08:37:07Z
|
[
"python",
"package",
"exe",
"theano",
"py2exe"
] |
How to compile and package a python file into an execution file under windows 64bit
| 39,364,224
|
<p>Recently, I started to use theano to do some basic BP network. The theano was installed and my network based on theano works well in my PC.
In order to share my code among my colleagues, I am looking for a method to package the theano python file to one execution file which can be run under windows without python environment.</p>
<p>I am trying py2exe to finish the packaging work and I found that, the packaged exe can only work in my PC. When I copy the exe to other PCs without python, it does not work. Only warning message is giving as:</p>
<pre><code>âWARNING (theano.configdefaults): g++ not detected !
Theano will be unable to execute optimized C-implementations (for both CPU and GPU) and will default to Python implementations. Performance will be severely degraded. To remove this warning, set Theano flags cxx to an empty string.â
</code></pre>
<p>My <strong>working environment</strong> is:
<strong>Win10 64bit + Anaconda2</strong></p>
<p>Could anyone give me some advice to generate the exe file based on theano python file?</p>
<p>Thank you a lot.</p>
| 0
|
2016-09-07T07:54:29Z
| 39,365,182
|
<p>I use <code>cxFreeze</code> to convert my Python scripts to <code>.exe</code> Its a really good module. You can see its working <a href="https://www.youtube.com/watch?v=HosXxXE24hA" rel="nofollow">here</a>. </p>
| 0
|
2016-09-07T08:43:52Z
|
[
"python",
"package",
"exe",
"theano",
"py2exe"
] |
Spark join throws 'function' object has no attribute '_get_object_id' error. How could I fix it?
| 39,364,283
|
<p>I am making a query in Spark in Databricks, and I have a problema when I am trying to make a join between two dataframes. The two dataframes that I have are the next ones:</p>
<ul>
<li><p>"names_df" which has 2 columns: "ID", "title" that refer to the id and the title of films.</p>
<pre><code>+-------+-----------------------------+
|ID |title |
+-------+-----------------------------+
|1 |Toy Story |
|2 |Jumanji |
|3 |Grumpier Old Men |
+-------+-----------------------------+
</code></pre></li>
<li><p>"info" which has 3 columns: "movieId", "count", "average" that refer to the id of the film, the number of ranks that it has, and the average of those ratings.</p>
<pre><code>+-------+-----+------------------+
|movieId|count|average |
+-------+-----+------------------+
|1831 |7463 |2.5785207021305103|
|431 |8946 |3.695059244355019 |
|631 |2193 |2.7273141814865483|
+-------+-----+------------------+
</code></pre></li>
</ul>
<p>This "info" dataframe was created this way:</p>
<pre><code>info = ratings_df.groupBy('movieId').agg(F.count(ratings_df.rating).alias("count"), F.avg(ratings_df.rating).alias("average"))
</code></pre>
<p>Where "ratings_df" is another dataframe that contains 3 columns: "userId", "movieId" and "rating", that refer to the id of the user that voted, the id of the film that the user voted to, and the rating for that film:</p>
<pre><code>+-------+-------+-------------+
|userId |movieId|rating |
+-------+-------+-------------+
|1 |2 |3.5 |
|1 |29 |3.5 |
|1 |32 |3.5 |
+-------+-------+-------------+
</code></pre>
<p>I am trying to make a join between these two dataframes to get another one with those columns: "movieId", "title", "count", "average":</p>
<pre><code>+-------+-----------------------------+-----+-------+
|average|title |count|movieId|
+-------+-----------------------------+-----+-------+
|5.0 |Ella Lola, a la Trilby (1898)|1 |94431 |
|5.0 |Serving Life (2011) |1 |129034 |
|5.0 |Diplomatic Immunity (2009? ) |1 |107434 |
+-------+-----------------------------+-----+-------+
</code></pre>
<p>So the operation I did was the next one:</p>
<pre><code>movie_names_df = info.join(movies_df, info.movieId == movies_df.ID, "inner").select(movies_df.title, info.average, info.movieId, info.count).show()
</code></pre>
<p>The problem is that I get the next error message:</p>
<pre><code>AttributeError: 'function' object has no attribute '_get_object_id'
</code></pre>
<p>And I know that this error occurs because it consider that info.count is a function, and not an attribute, as I defined previously.</p>
<p>So, how could I make that join correctly to get what I want?</p>
<p>Thank you so much!</p>
| 0
|
2016-09-07T07:57:39Z
| 39,369,797
|
<p>Adding comment as answer since it solved the problem. <code>count</code> is somewhat of a protected keyword in DataFrame API, so naming columns <em>count</em> is dangerous. In your case you could circumvent the error by not using the dot notation, but bracket based column access, e.g.</p>
<pre><code>info["count"]
</code></pre>
| 2
|
2016-09-07T12:19:10Z
|
[
"python",
"sql",
"function",
"join",
"apache-spark"
] |
Python multiprocessing start method doesn't run the process
| 39,364,485
|
<p>I'm new to multiprocessing and I'm trying to check that I can run two process simultaneously with the following code :</p>
<pre><code>import random, time, multiprocessing as mp
def printer():
"""print function"""
z = random.randit(0,60)
for i in range(5):
print z
wait = 0.2
wait += random.randint(1,60)/100
time.sleep(wait)
return
if __name__ == '__main__':
p1 = mp.Process(target=printer)
p2 = mp.Process(target=printer)
p1.start()
p2.start()
</code></pre>
<p>This code does not print anything on the console although I checked that the process are running thanks to the is.alive() method.</p>
<p>However, I can print something using :</p>
<pre><code>p1.run()
p2.run()
</code></pre>
<p><strong>Question 1 :</strong> Why doesn't the start() method run the process ?</p>
<p><strong>Question 2 :</strong> While running the code with run() method, why do I get a sequence like</p>
<p>25,25,25,25,25,11,11,11,11,11</p>
<p>instead of something like</p>
<p>25,25,11,25,11,11,11,25,11,25 ?</p>
<p>It seems that the process run one after the other.</p>
<p>I would like to use multiprocessing for using the same function on multiple files to parallelize file conversion.</p>
| 0
|
2016-09-07T08:08:16Z
| 39,508,146
|
<p>I made the script run by adding </p>
<pre><code>from multiprocessing import Process
</code></pre>
<p>However, I don't have a random sequence of two numbers, the pattern is always A,B,A,B.. If you know how to show that the two process run simultaneously, any ideas are welcome !</p>
| 0
|
2016-09-15T09:56:17Z
|
[
"python",
"multithreading",
"python-2.7",
"multiprocessing"
] |
Keras - Fitting Neural Net with different Epoch number in a loop without starting over each time
| 39,364,516
|
<p>I am fitting a recurrent neural net in <code>python</code> using <code>keras</code> library. I am fitting the model with different <code>epoch</code> number by changing parameter <code>nb_epoch</code> in <code>Sequential.fit()</code> function. Currently I'm using <code>for</code> loop which starts over fitting each time I change <code>nb_epoch</code> which is lots of repeating work. Here is my code (the loop is in the bottom of the code, if you want to skip other parts of the code details):</p>
<pre><code>from __future__ import division
import numpy as np
import pandas
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.learning_curve import learning_curve
####################################
###
### Here I do the data processing to create trainX, testX
###
####################################
#model create:
model = Sequential()
#this is the epoch array for different nb_epoch
####################################
###
### Here I define model architecture
###
####################################
model.compile(loss="mse", optimizer="rmsprop")
#################################################
#### Defining arrays for different epoch number
#################################################
epoch_array = range(100, 2100,100)
# I create the following arrays/matrices to store the result of NN fit
# different epoch number.
train_DBN_fitted_Y = np.zeros(shape=(len(epoch_array),trainX.shape[0]))
test_DBN_fitted_Y = np.zeros(shape=(len(epoch_array),testX.shape[0]))
###############################################
###
### Following loop is the heart of the question
###
##############################################
i = 0
for epoch in epoch_array:
model.fit( trainX, trainY,
batch_size = 16, nb_epoch = epoch, validation_split = 0.05, verbose = 2)
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)
trainPredict = trainPredict.reshape(trainPredict.shape[0])
testPredict = testPredict.reshape(testPredict.shape[0])
train_DBN_fitted_Y[i] = trainPredict
test_DBN_fitted_Y[i] = testPredict
i = i + 1
</code></pre>
<p>Now this loops is very inefficient. Because for example, when it sets, say, <code>nb_epoch</code> = 100, it starts training from <code>epoch = 1</code> and finishes at <code>epoch = 100</code> like following : </p>
<pre><code>Epoch 1/100
0s - loss: 1.9508 - val_loss: 296.7801
.
.
.
Epoch 100/100
0s - loss: 7.6575 - val_loss: 366.2218
</code></pre>
<p>In the next iteration of loop, where it says <code>nb_epoch = 200</code> it starts training from <code>epoch = 1</code> again and finishes at <code>epoch = 200</code>. But what I want to do is, in this iteration, start training from where it left in the last iteration of the loop i.e. <code>epoch = 100</code> and then <code>epoch = 101</code> and so on....</p>
<p>How can I modify this loop to achieve this? </p>
| 2
|
2016-09-07T08:09:53Z
| 39,371,723
|
<p>Continuously calling <code>fit</code> is training your model further, starting from the state it was left from the previous call. For it to <strong>not</strong> continue it would have to reset the weights of your model, which <code>fit</code> does not do. You are just not seeing that it does that, as it is always starting to count epochs beginning at 1.</p>
<p>So in the end the problem is just that it does not print the correct number of epochs (which you cannot change).</p>
<p>If this is bothering you, you can implement your own <code>fit</code> by calling <a href="https://keras.io/models/model/#train_on_batch" rel="nofollow"><code>model.train_on_batch</code></a> periodically.</p>
| 1
|
2016-09-07T13:48:56Z
|
[
"python",
"loops",
"neural-network",
"deep-learning",
"keras"
] |
Elasticsearch fix date field value. (change field value from int to string)
| 39,364,625
|
<p>I used python ship data from mongodb to elasticsearch.</p>
<p>There is a timestamp field named <code>update_time</code>, mapping like:</p>
<pre><code> "update_time" : {
"type": "date",
"format": "yyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
},
</code></pre>
<p><code>epoch_millis</code> is used for timestamp.</p>
<p>After everything done, I used <code>range</code> to query doc in date range. But nothing return. After some researching, I thought the problem was: python timestamp <code>int(time.time())</code> is 10 digit, but it is 13 digit in elasticsearch , <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-timestamp-field.html" rel="nofollow">official example</a> :</p>
<blockquote>
<p>PUT my_index/my_type/2?timestamp=1420070400000.</p>
</blockquote>
<p>so I tried to update the update_time field by multiple 1000:</p>
<pre><code>{
"script": {
"inline": "ctx._source.update_time=ctx._source.update_time*1000"
}
}
</code></pre>
<p>Unfortunately, I found all <code>update_time</code> become minus. Then I come up with that Java int type is <code>pow(2,32) -1</code> , much lower than <code>1420070400000</code>. So I guess timestamp field should not be int ?</p>
<p>Then I want to update the field value from int to string(I don't want ot change field mapping type, I know change mapping type need reindex, but here only need change value )</p>
<p>But I can't figure out what script I can use, official script document not mention about this</p>
| 0
|
2016-09-07T08:15:55Z
| 39,442,509
|
<p>I didn't know groovy was a lauguage and thought it only used for math method because ES doc only wrote about that.</p>
<p>The sulotion is simple, just convert int to long.</p>
<pre><code>curl -XPOST http://localhost:9200/my_index/_update_by_query -d '
{
"script": {
"inline": "ctx._source.update_time=(long)ctx._source.update_time*1000"
}
}'
</code></pre>
| 0
|
2016-09-12T02:08:05Z
|
[
"python",
"elasticsearch",
"elasticsearch-query"
] |
Program won't run
| 39,364,796
|
<p>I have this exercise and the first part of the program was running fine but I must've done something because now when I try to run it will just show <code>None</code> and and nothing seems to be 'wrong'. I don't know enough to even figure out what's wrong.</p>
<pre><code>def main():
"""Gets the job done"""
#this program returns the value according to the colour
def re_start():
#do the work
return read_colour
def read_names():
"""prompt user for their name and returns in a space-separaded line"""
PROMPT_NAMES = input("Enter names: ")
users_names = '{}'.format(PROMPT_NAMES)
print (users_names)
return users_names
def read_colour():
"""prompt user for a colour letter if invalid colour enter retry"""
ALLOWED_COLOURS = ["whero",
"kowhai",
"kikorangi",
"parauri",
"kiwikiwi",
"karaka",
"waiporoporo",
"pango"]
PROMPT_COLOUR = input("Enter letter colour: ").casefold()
if PROMPT_COLOUR in ALLOWED_COLOURS:
return read_names()
else:
print("Invalid colour...")
print(*ALLOWED_COLOURS,sep='\n')
re_start()
main()
</code></pre>
| -2
|
2016-09-07T08:24:44Z
| 39,415,032
|
<p>The only function you call is <code>main()</code>, but that has no statements in it, so your code will do nothing. To fix this, put some statements in your <code>main()</code> and rerun your code.</p>
| 1
|
2016-09-09T15:28:37Z
|
[
"python",
"python-3.x"
] |
Python index function
| 39,364,804
|
<p>I am writing a simple Python program which grabs a webpage and finds all the URL links in it. However I try to index the starting and ending delimiter (") of each href link but the ending one always indexed wrong.</p>
<pre><code># open a url and find all the links in it
import urllib2
url=urllib2.urlopen('right.html')
urlinfo = url.info()
urlcontent = url.read()
bodystart = urlcontent.index('<body')
print 'body starts at',bodystart
bodycontent = urlcontent[bodystart:].lower()
print bodycontent
linklist = []
n = bodycontent.index('<a href=')
while n:
print n
bodycontent = bodycontent[n:]
a = bodycontent.index('"')
b = bodycontent[(a+1):].index('"')
print a, b
linklist.append(bodycontent[(a+1):b])
n = bodycontent[b:].index('<a href=')
print linklist
</code></pre>
| 0
|
2016-09-07T08:25:04Z
| 39,364,876
|
<p><code>b</code> is relative to the substring from <code>a+1</code>, hence the access to the array should be:</p>
<pre><code>linklist.append(bodycontent[(a+1):(a+1+b)])
</code></pre>
<p>As mentioned in other answers, it's usually preferable to work with a designated library, like <a href="https://pypi.python.org/pypi/beautifulsoup4" rel="nofollow">BeautifulSoup</a>.</p>
| 0
|
2016-09-07T08:28:49Z
|
[
"python"
] |
Python index function
| 39,364,804
|
<p>I am writing a simple Python program which grabs a webpage and finds all the URL links in it. However I try to index the starting and ending delimiter (") of each href link but the ending one always indexed wrong.</p>
<pre><code># open a url and find all the links in it
import urllib2
url=urllib2.urlopen('right.html')
urlinfo = url.info()
urlcontent = url.read()
bodystart = urlcontent.index('<body')
print 'body starts at',bodystart
bodycontent = urlcontent[bodystart:].lower()
print bodycontent
linklist = []
n = bodycontent.index('<a href=')
while n:
print n
bodycontent = bodycontent[n:]
a = bodycontent.index('"')
b = bodycontent[(a+1):].index('"')
print a, b
linklist.append(bodycontent[(a+1):b])
n = bodycontent[b:].index('<a href=')
print linklist
</code></pre>
| 0
|
2016-09-07T08:25:04Z
| 39,364,878
|
<p>I would suggest using a html parsing library instead of manually searching the DOM String.</p>
<p>Beautiful Soup is an excellent library for this purpose. Here is the reference <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">link</a></p>
<p>With bs your link searching functionality could look like:</p>
<pre><code>from bs4 import BeautifulSoup
soup = BeautifulSoup(bodycontent, 'html.parser')
linklist = [a.get('href') for a in soup.find_all('a')]
</code></pre>
| 3
|
2016-09-07T08:28:51Z
|
[
"python"
] |
Convert hashed password to string werkuzeug python
| 39,364,819
|
<p>I am using Werkzeug for password hashing so that the passwords entered by users will be safe(atleast).</p>
<p>Lets say my application is as follows:</p>
<p>When a user gets logged in I will use check_password_hash and then login the user inside.</p>
<p>After the user is logged in, I want to show them their password.</p>
<p>The problem I am encountering:</p>
<p>How do I convert the hashed password back to string to show the user their password?</p>
<p>My code is as follows:</p>
<pre><code>>>> import werkzeug.security as ws
>>> ws.generate_password_hash('abcdefg')
'pbkdf2:sha1:1000$fYAXLNA6$637528ae2fa195304c328d585e805b164f1c718f'
>>> ws._hash_internal('pbkdf2:sha1:1000', 'fYAXLNA6', 'abcdefg')
('637528ae2fa195304c328d585e805b164f1c718f', 'pbkdf2:sha1:1000')
</code></pre>
<p>Now how do I convert this '6375.....' back to 'abcdefg'? </p>
<p>I have access to database and the all the other stuff required. Basically I am the admin!</p>
<p>Note: I cannot use the password which user entered while logging in. I can only use the password from database.</p>
| -1
|
2016-09-07T08:26:00Z
| 39,364,875
|
<blockquote>
<p>After the user is logged in, I want to show them their password.</p>
</blockquote>
<p>The whole purpose and reason of hashing a password is that you can never do this. Not you, not anyone else. </p>
<p>If someone has access or steals the database with the list of passwords, converting the hash back to the original password is really, really expensive. You will need a million years to break and reverse one single password. </p>
| 2
|
2016-09-07T08:28:45Z
|
[
"python",
"security",
"hash",
"werkzeug"
] |
Convert hashed password to string werkuzeug python
| 39,364,819
|
<p>I am using Werkzeug for password hashing so that the passwords entered by users will be safe(atleast).</p>
<p>Lets say my application is as follows:</p>
<p>When a user gets logged in I will use check_password_hash and then login the user inside.</p>
<p>After the user is logged in, I want to show them their password.</p>
<p>The problem I am encountering:</p>
<p>How do I convert the hashed password back to string to show the user their password?</p>
<p>My code is as follows:</p>
<pre><code>>>> import werkzeug.security as ws
>>> ws.generate_password_hash('abcdefg')
'pbkdf2:sha1:1000$fYAXLNA6$637528ae2fa195304c328d585e805b164f1c718f'
>>> ws._hash_internal('pbkdf2:sha1:1000', 'fYAXLNA6', 'abcdefg')
('637528ae2fa195304c328d585e805b164f1c718f', 'pbkdf2:sha1:1000')
</code></pre>
<p>Now how do I convert this '6375.....' back to 'abcdefg'? </p>
<p>I have access to database and the all the other stuff required. Basically I am the admin!</p>
<p>Note: I cannot use the password which user entered while logging in. I can only use the password from database.</p>
| -1
|
2016-09-07T08:26:00Z
| 39,365,023
|
<p>We cannot get the original text back while using hashing. Generally all the passwords are stored as hash value, in order to make the passwords private (known only to the user). All the servers implement this. If you want to get the password back then you should use symmetric key cryptography. Where a secret key will be shared between the clients and the server <strong>(But it is a very bad practice)</strong> It better that you go with hashing.</p>
| 1
|
2016-09-07T08:35:29Z
|
[
"python",
"security",
"hash",
"werkzeug"
] |
How can I write 1 byte to a binary file in python
| 39,364,905
|
<p>I've tried everything to write just one byte to a file in python. </p>
<pre><code>i=10
fh.write( six.int2byte(i) )
</code></pre>
<p>will output '0x00 0x0a'</p>
<pre><code>fh.write( struct.pack('i', i) )
</code></pre>
<p>will output '0x00 0x0a 0x00 0x00'</p>
<p>I can't understand why this is so hard to do.</p>
| 0
|
2016-09-07T08:30:13Z
| 39,364,994
|
<p>You can just build a <code>bytes</code> object with that value:</p>
<pre><code>with open('my_file', 'wb') as f:
f.write(bytes([10]))
</code></pre>
<p>This works only in python3. If you replace <code>bytes</code> with <code>bytearray</code> it works in both python2 and 3.</p>
<p>Also: remember to open the file in binary mode to write bytes to it.</p>
| 4
|
2016-09-07T08:34:29Z
|
[
"python",
"filehandle",
"writing"
] |
How can I write 1 byte to a binary file in python
| 39,364,905
|
<p>I've tried everything to write just one byte to a file in python. </p>
<pre><code>i=10
fh.write( six.int2byte(i) )
</code></pre>
<p>will output '0x00 0x0a'</p>
<pre><code>fh.write( struct.pack('i', i) )
</code></pre>
<p>will output '0x00 0x0a 0x00 0x00'</p>
<p>I can't understand why this is so hard to do.</p>
| 0
|
2016-09-07T08:30:13Z
| 39,365,081
|
<p><code>struct.pack("=b",i)</code> (signed) and <code>struct.pack("=B",i)</code> (unsigned) pack an integer as a single byte which you can see in the <a href="https://docs.python.org/3/library/struct.html#format-characters" rel="nofollow">docs for struct</a>. (<code>"="</code> is for using standard size and ignoring alignment - just in case) so you can do</p>
<pre><code>import struct
i=10
with open('binfile', 'wb') as f:
f.write(struct.pack("=B",i))
</code></pre>
| 0
|
2016-09-07T08:39:01Z
|
[
"python",
"filehandle",
"writing"
] |
pymc3: how to model correlated intercept and slope in multilevel linear regression
| 39,364,919
|
<p>In the Pymc3 example for multilevel linear regression (the example is <a href="http://pymc-devs.github.io/pymc3/notebooks/GLM-hierarchical.html" rel="nofollow">here</a>, with the <code>radon</code> data set from Gelman et al.âs (2007)), the intercepts (for different counties) and slopes (for apartment with and without basement) each have a Normal prior. How can I model them together with a multivariate normal prior, so that I can examine the correlation between them?</p>
<p>The hierarchical model given in the example is like this:</p>
<pre><code>with pm.Model() as hierarchical_model:
# Hyperpriors for group nodes
mu_a = pm.Normal('mu_a', mu=0., sd=100**2)
sigma_a = pm.HalfCauchy('sigma_a', 5)
mu_b = pm.Normal('mu_b', mu=0., sd=100**2)
sigma_b = pm.HalfCauchy('sigma_b', 5)
# Intercept for each county, distributed around group mean mu_a
# Above we just set mu and sd to a fixed value while here we
# plug in a common group distribution for all a and b (which are
# vectors of length n_counties).
a = pm.Normal('a', mu=mu_a, sd=sigma_a, shape=n_counties)
# Intercept for each county, distributed around group mean mu_a
b = pm.Normal('b', mu=mu_b, sd=sigma_b, shape=n_counties)
# Model error
eps = pm.HalfCauchy('eps', 5)
radon_est = a[county_idx] + b[county_idx] * data.floor.values
# Data likelihood
radon_like = pm.Normal('radon_like', mu=radon_est, sd=eps, observed=data.log_radon)
hierarchical_trace = pm.sample(2000)
</code></pre>
<p>And I'm trying to make some change to the priors</p>
<pre><code> with pm.Model() as correlation_model:
# Hyperpriors for group nodes
mu_a = pm.Normal('mu_a', mu=0., sd=100**2)
mu_b = pm.Normal('mu_b', mu=0., sd=100**2)
# here I want to model a and b together
# I borrowed some code from a multivariate normal model
# but the code does not work
sigma = pm.HalfCauchy('sigma', 5, shape=2)
C_triu = pm.LKJCorr('C_triu', n=2, p=2)
C = T.fill_diagonal(C_triu[np.zeros((2,2), 'int')], 1)
cov = pm.Deterministic('cov', T.nlinalg.matrix_dot(sigma, C, sigma))
tau = pm.Deterministic('tau', T.nlinalg.matrix_inverse(cov))
a, b = pm.MvNormal('mu', mu=(mu_a, mu_b), tau=tau,
shape=(n_counties, n_counties))
# Model error
eps = pm.HalfCauchy('eps', 5)
radon_est = a[county_idx] + b[county_idx] * data.floor.values
# Data likelihood
radon_like = pm.Normal('radon_like', mu=radon_est, sd=eps, observed=data.log_radon)
correlation_trace = pm.sample(2000)
</code></pre>
<p>Here is the error message I got:</p>
<pre><code> File "<ipython-input-108-ce400c54cc39>", line 14, in <module>
tau = pm.Deterministic('tau', T.nlinalg.matrix_inverse(cov))
File "/home/olivier/anaconda3/lib/python3.5/site-packages/theano/gof/op.py", line 611, in __call__
node = self.make_node(*inputs, **kwargs)
File "/home/olivier/anaconda3/lib/python3.5/site-packages/theano/tensor/nlinalg.py", line 73, in make_node
assert x.ndim == 2
AssertionError
</code></pre>
<p>Clearly I've made some mistakes about the covariance matrix, but I'm new to <code>pymc3</code> and completely new to <code>theano</code> so have no idea how to fix it. I gather this should be a rather common use case so maybe there have been some examples on it? I just can't find them.</p>
<p>The full replicable code and data can be seen on the example page (link given above). I didn't include it here because it's too long and also I thought those familiar with <code>pymc3</code> are very likely already quite familiar with it:)</p>
| 0
|
2016-09-07T08:31:09Z
| 39,386,592
|
<p>You forgot to add one line when creating the covariance matrix you miss-specified the shape of the MvNormal. Your model should look something like this:</p>
<pre><code>with pm.Model() as correlation_model:
mu = pm.Normal('mu', mu=0., sd=10, shape=2)
sigma = pm.HalfCauchy('sigma', 5, shape=2)
C_triu = pm.LKJCorr('C_triu', n=2, p=2)
C = tt.fill_diagonal(C_triu[np.zeros((2,2), 'int')], 1.)
sigma_diag = tt.nlinalg.diag(sigma) # this line
cov = tt.nlinalg.matrix_dot(sigma_diag, C, sigma_diag)
tau = tt.nlinalg.matrix_inverse(cov)
ab = pm.MvNormal('ab', mu=mu, tau=tau, shape=(n_counties, 2))
eps = pm.HalfCauchy('eps', 5)
radon_est = ab[:,0][county_idx] + ab[:,1][county_idx] * data.floor.values
radon_like = pm.Normal('radon_like', mu=radon_est, sd=eps, observed=data.log_radon)
trace = pm.sample(2000)
</code></pre>
<p>Notice that alternatively, you can evaluate the correlation of the intercept and the slope from the posterior of <code>hierarchical_model</code>. You can use a frequentist method or build another Bayesian model, that takes as the observed data the result of <code>hierarchical_model</code>. May be this could be faster.</p>
<p>EDIT</p>
<p>If you want to evaluate the correlation of two variables from the posterior you can do something like.</p>
<pre><code>chain = hierarchical_trace[100:]
x_0 = chain['mu_a']
x_1 = chain['mu_b']
X = np.vstack((x_0, x_1)).T
</code></pre>
<p>and then you can run the following model:</p>
<pre><code>with pm.Model() as correlation:
mu = pm.Normal('mu', mu=0., sd=10, shape=2)
sigma = pm.HalfCauchy('sigma', 5, shape=2)
C_triu = pm.LKJCorr('C_triu', n=2, p=2)
C = tt.fill_diagonal(C_triu[np.zeros((2,2), 'int')], 1.)
sigma_diag = tt.nlinalg.diag(sigma)
cov = tt.nlinalg.matrix_dot(sigma_diag, C, sigma_diag)
tau = tt.nlinalg.matrix_inverse(cov)
yl = pm.MvNormal('yl', mu=mu, tau=tau, shape=(2, 2), observed=X)
trace = pm.sample(5000, pm.Metropolis())
</code></pre>
<p>You can replace x_0 and x_1 according to your needs. For example you may want to do:</p>
<pre><code>x_0 = np.random.normal(chain['mu_a'], chain['sigma_a'])
x_1 = np.random.normal(chain['mu_b'], chain['sigma_b'])
</code></pre>
| 1
|
2016-09-08T08:55:23Z
|
[
"python",
"pymc",
"pymc3"
] |
Urllib2: how to get content of page
| 39,364,933
|
<p>I have some urls:</p>
<pre><code>http://www.avito.ru/ryazan/avtomobili?pmax=50000&f=188_893b13978
http://www.avito.ru/ryazan/avtomobili?pmax=50000&f=188_898b13978
http://www.avito.ru/ryazanskaya_oblast/avtomobili?pmax=50000&f=188_898b13978
http://www.avito.ru/ryazanskaya_oblast/avtomobili?pmax=50000&f=188_898b13978
http://www.avito.ru/ryazanskaya_oblast/avtomobili?pmax=100000&pmin=50000&f=188_898b13978
</code></pre>
<p>I try to get content of this page I get an error <code>urllib2.URLError: <urlopen error [Errno 10060]</code>
I use code
<code>urllib2.urlopen(url).read()</code>
What I do wrong?</p>
| 1
|
2016-09-07T08:31:32Z
| 39,365,123
|
<p>Its working fine for me. I used <code>requests</code> module to get the page. Python <code>requests</code> is better. If you dont have <code>requests</code> module installed you can install it by <code>pip install requests</code></p>
<pre><code>import requests
for url in urls: # if you are using a list to hold your urls
r = requests.get(url)
r.content # will display the entire page content
</code></pre>
<p>If this also doesnt work, its better to check your proxy connection.</p>
| 0
|
2016-09-07T08:41:02Z
|
[
"python",
"urllib2"
] |
pandas group by ALL functionality?
| 39,365,003
|
<p>I'm using the <code>pandas groupby+agg</code> functionality to generate nice reports</p>
<pre><code>aggs_dict = {'a':['mean', 'std'], 'b': 'size'}
df.groupby('year').agg(aggs_dict)
</code></pre>
<p>I would like to use the same <code>aggs_dict</code> on the entire dataframe as a single group, with no division to years, something like:</p>
<pre><code>df.groupall().agg(aggs_dict)
</code></pre>
<p>or:</p>
<pre><code>df.agg(aggs_dict)
</code></pre>
<p>But couldn't find any elegant way to do it.. Note that in my real code <code>aggs_dict</code> is quite complex so it's rather cumbersome to do:</p>
<pre><code>df.a.mean()
df.a.std()
df.b.size()
....
</code></pre>
<p>am I missing something simple and nice?</p>
| 1
|
2016-09-07T08:34:54Z
| 39,365,089
|
<p>You could add a dummy column:</p>
<pre><code>df['dummy'] = 1
</code></pre>
<p>Then groupby + agg on it:</p>
<pre><code>df.groupby('dummy').agg(aggs_dict)
</code></pre>
<p>and then <a href="http://stackoverflow.com/questions/13411544/delete-column-from-pandas-dataframe">delete it</a> when you're done.</p>
| 2
|
2016-09-07T08:39:27Z
|
[
"python",
"pandas",
"group-by"
] |
pandas group by ALL functionality?
| 39,365,003
|
<p>I'm using the <code>pandas groupby+agg</code> functionality to generate nice reports</p>
<pre><code>aggs_dict = {'a':['mean', 'std'], 'b': 'size'}
df.groupby('year').agg(aggs_dict)
</code></pre>
<p>I would like to use the same <code>aggs_dict</code> on the entire dataframe as a single group, with no division to years, something like:</p>
<pre><code>df.groupall().agg(aggs_dict)
</code></pre>
<p>or:</p>
<pre><code>df.agg(aggs_dict)
</code></pre>
<p>But couldn't find any elegant way to do it.. Note that in my real code <code>aggs_dict</code> is quite complex so it's rather cumbersome to do:</p>
<pre><code>df.a.mean()
df.a.std()
df.b.size()
....
</code></pre>
<p>am I missing something simple and nice?</p>
| 1
|
2016-09-07T08:34:54Z
| 39,370,321
|
<p>Ami Tavory's answer is a great way to do it but just in case you wanted a solution that doesn't require creating new columns and deleting them afterwards you could do something like:</p>
<pre><code>df.groupby([True]*len(df)).agg(aggs_dict)
</code></pre>
| 3
|
2016-09-07T12:45:02Z
|
[
"python",
"pandas",
"group-by"
] |
pip install --editable with a VCS url
| 39,365,080
|
<p>In <code>man pip</code> it says under <code>--editable <path/url></code>, </p>
<blockquote>
<p>Install a project in editable mode (i.e. setuptools "develop mode")
from a local project path or a VCS url</p>
</blockquote>
<p>What does that mean? Can I give it a repo branch on Github, and it'll go get it and install it and keep it updated as the branch changes?</p>
| 0
|
2016-09-07T08:39:00Z
| 39,365,347
|
<p>If you just want to install package from git repo <a href="http://stackoverflow.com/questions/20101834/pip-install-from-github-repo-branch?rq=1">read</a></p>
<p><code>-e</code> or <code>--editable</code> is little bit different, it is used, as stated in docs, for setuptools's <a href="https://setuptools.readthedocs.io/en/latest/setuptools.html?highlight=develop%20mode#development-mode" rel="nofollow">development mode</a>. It makes installed packages editable.</p>
<p>Yes you can give it link to github. Read this <a href="http://stackoverflow.com/questions/4830856/is-it-possible-to-use-pip-to-install-a-package-from-a-private-github-repository#4837571">answer</a> for more info. But this link will only work if this repository contains <code>setup.py</code> with all installation instructions. And this package will be updated when you call</p>
<pre><code>pip install -U -e <url>
</code></pre>
<p>But only if version of package in <code>setup.py</code> is higher than the one in your environment.</p>
<p>You can forcefully reinstall this package if you need to, when source did change but version didn't.</p>
<pre><code>pip install -I -e <url>
</code></pre>
| 0
|
2016-09-07T08:52:08Z
|
[
"python",
"git",
"package",
"pip"
] |
Running Multiple spiders in scrapy for 1 website in parallel?
| 39,365,131
|
<p>I want to crawl a website with 2 parts and my script is not as fast as i need.</p>
<p>is it possible to luanch 2 spiders, one for scraping the first part and the second one for the second part? </p>
<p>i tried to have 2 diffrent classes, and run them</p>
<pre><code>scrapy crwal firstSpider
scrapy crawl secondSpider
</code></pre>
<p>but i think that it is not smart.</p>
<p>i read the <a href="http://scrapyd.readthedocs.io/en/latest/api.html" rel="nofollow">documentation of scrapyd</a> but i don't know if it's good for my case.</p>
| 0
|
2016-09-07T08:41:25Z
| 39,366,885
|
<p>I think what you are looking for is something like this:</p>
<pre><code>import scrapy
from scrapy.crawler import CrawlerProcess
class MySpider1(scrapy.Spider):
# Your first spider definition
...
class MySpider2(scrapy.Spider):
# Your second spider definition
...
process = CrawlerProcess()
process.crawl(MySpider1)
process.crawl(MySpider2)
process.start() # the script will block here until all crawling jobs are finished
</code></pre>
<p>You can read more at: <a href="http://doc.scrapy.org/en/1.1/topics/practices.html#running-multiple-spiders-in-the-same-process" rel="nofollow">running-multiple-spiders-in-the-same-process</a>.</p>
| 1
|
2016-09-07T10:03:36Z
|
[
"python",
"web-scraping",
"scrapy",
"web-crawler",
"scrapy-spider"
] |
Iterating over a nested dictionary
| 39,365,148
|
<p>Purpose this code that works to iterate over a <code>nested dictionary</code> but I'm looking for an output that gives a tuple or <code>list</code> of [keys] and then [values]. Here's the code:</p>
<pre><code>from collections import Mapping, Set, Sequence
string_types = (str, unicode) if str is bytes else (str, bytes)
iteritems = lambda mapping: getattr(mapping, 'iteritems', mapping.items)()
def recurse(obj, path=(), memo=None):
if memo is None:
memo = set()
iterator = None
if isinstance(obj, Mapping):
iterator = iteritems
elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types):
iterator = enumerate
if iterator:
if id(obj) not in memo:
memo.add(id(obj))
for path_component, value in iterator(obj):
for result in recurse(value, path + (path_component,), memo):
yield result
memo.remove(id(obj))
else:
yield path, obj
class addNestedDict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
loansDict=addNestedDict()
loansDict[15]['A']['B']=[1,2,3,4]
for k,v in recurse(loansDict):
print(k,v)
</code></pre>
<p>The output I'm looking for is one line <code>(15 ,'A','B') [1,2,3,4]</code> so that I can be able to reference <code>k[0]</code>,<code>k[1]</code> and <code>v[0]</code> etc...</p>
| 0
|
2016-09-07T08:42:10Z
| 39,365,862
|
<p>This seems to work:</p>
<pre><code>results = AddNestedDict()
for k,v in recurse(loansDict):
results.setdefault(k[:-1], []).append(v)
result_key, result_value = results.items()[0]
print('{} {}'.format(result_key, result_value)) # -> (15, 'A', 'B') [1, 2, 3, 4]
</code></pre>
<p>I renamed your class <code>AddNestedDict</code> so it follows <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> guidelines.</p>
| 1
|
2016-09-07T09:16:05Z
|
[
"python",
"python-3.x"
] |
Find in which of multiple sets a value belongs to
| 39,365,365
|
<p>I have several sets of values, and need to check in which of some of them a given value is located, and return the name of that set.</p>
<pre><code>value = 'a'
set_1 = {'a', 'b', 'c'}
set_2 = {'d', 'e', 'f'}
set_3 = {'g', 'h', 'i'}
set_4 = {'a', 'e', 'i'}
</code></pre>
<p>I'd like to check if value exists in sets 1-3, without including set_4 in the method, and return the set name. So something like:</p>
<pre><code>find_set(value in set_1, set_2, set_3)
</code></pre>
<p>should return</p>
<pre><code>set_1
</code></pre>
<p>Maybe some neat lambda function? I tried </p>
<pre><code>w = next(n for n,v in filter(lambda t: isinstance(t[1],set), globals().items()) if value in v)
</code></pre>
<p>from <a href="http://stackoverflow.com/questions/34783084/find-if-value-exists-in-multiple-lists">Find if value exists in multiple lists</a> but that approach checks ALL local/global sets. That won't work here, because the value can exist in several of them. I need to be able to specify in which sets to look.</p>
| 0
|
2016-09-07T08:52:57Z
| 39,365,637
|
<p><em>Don't</em> use an ugly hackish lambda which digs in <code>globals</code> so you can get a name; that will confuse anyone reading your code including yourself after a few weeks :-).</p>
<p>You want to be able to get a name for sets you have defined, well, this is why we have dictionaries. Make a dictionary out of your sets and then you can create handy/readable set/list comprehensions to get what you want in a compact readable fashion:</p>
<pre><code>>>> d = {'set_1': set_1, 'set_2': set_2, 'set_3': set_3, 'set_4': set_4}
</code></pre>
<p>To catch all sets in which <code>'a'</code> is located:</p>
<pre><code>>>> {name for name, items in d.items() if 'a' in items}
{'set_1', 'set_4'}
</code></pre>
<p>To exclude some name add another the required clause to the <code>if</code> for filtering:</p>
<pre><code>>>> {name for name, items in d.items() if 'a' in items and name != 'set_4'}
{'set_1'}
</code></pre>
<p>You can of course factor this into a function and be happy you'll be able to understand it if you bump into it in the future:</p>
<pre><code>def find_sets(val, *excludes, d=d):
return {n for n, i in d.items() if val in i and n not in excludes}
</code></pre>
<p>This behaves in a similar way as the previous. <code>d=d</code> is probably not the way you want to do it, you'll probably be better of using some <code>**d</code> syntax for this.</p>
<hr>
<p>If you just want to get the first value, return the <code>next(comprehension)</code> from your function like this:</p>
<pre><code>def find_sets(val, *excludes, d=d):
return next((n for n, i in d.items() if val in i and n not in excludes), '')
</code></pre>
<p>The <code>''</code> just indicates a default value to be returned if no elements are actually found, that is, when called with a value that isn't present, an empty string will be returned (subject to change according to your preferences):</p>
<pre><code>>>> find_sets('1')
''
</code></pre>
| 2
|
2016-09-07T09:05:31Z
|
[
"python",
"python-3.x",
"set"
] |
pypi not finding registered package
| 39,365,424
|
<p>I have a package that I submitted to Pypi using the <code>python setup.py register</code> command:
<a href="https://bitbucket.org/lskibinski/et3" rel="nofollow">https://bitbucket.org/lskibinski/et3</a></p>
<p>You can see it here:
<a href="https://pypi.python.org/pypi?name=et3&version=1.0&:action=display" rel="nofollow">https://pypi.python.org/pypi?name=et3&version=1.0&:action=display</a></p>
<p>However, for some mysterious reason, <code>pip install et3</code> doesn't work. The error I get is:</p>
<p><code>
$ pip install et3 -vvv --no-cache-dir
Collecting et3
1 location(s) to search for versions of et3:
* https://pypi.python.org/simple/et3/
Getting page https://pypi.python.org/simple/et3/
Starting new HTTPS connection (1): pypi.python.org
"GET /simple/et3/ HTTP/1.1" 200 111
Analyzing links from page https://pypi.python.org/simple/et3/
Could not find a version that satisfies the requirement et3 (from versions: )
Cleaning up...
No matching distribution found for et3
Exception information:
Traceback (most recent call last):
File "/home/luke/dev/python/lax/venv/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/home/luke/dev/python/lax/venv/lib/python2.7/site-packages/pip/commands/install.py", line 299, in run
requirement_set.prepare_files(finder)
File "/home/luke/dev/python/lax/venv/lib/python2.7/site-packages/pip/req/req_set.py", line 370, in prepare_files
ignore_dependencies=self.ignore_dependencies))
File "/home/luke/dev/python/lax/venv/lib/python2.7/site-packages/pip/req/req_set.py", line 522, in _prepare_file
finder, self.upgrade, require_hashes)
File "/home/luke/dev/python/lax/venv/lib/python2.7/site-packages/pip/req/req_install.py", line 268, in populate_link
self.link = finder.find_requirement(self, upgrade)
File "/home/luke/dev/python/lax/venv/lib/python2.7/site-packages/pip/index.py", line 491, in find_requirement
'No matching distribution found for %s' % req
DistributionNotFound: No matching distribution found for et3
</code></p>
<p>It seems like it can't find any versions to download. Do I need to specify something more than <code>download_url</code>? Are further manual steps required? </p>
| 0
|
2016-09-07T08:55:49Z
| 39,366,998
|
<p>ok, figured it out. <code>download_url</code> doesn't appear to do much at all. I had to do:</p>
<ul>
<li><code>python setup.py register</code></li>
<li><code>python setup.py sdist upload</code></li>
</ul>
<p>... and it now works. The documentation for all of this is terrible.</p>
| 0
|
2016-09-07T10:09:31Z
|
[
"python",
"pypi"
] |
Create a in-browser Python application with a GUI
| 39,365,445
|
<p>I am teaching a class soon and I want to have users try my platform without the need of installing Python in their computers and to run everything online. I have searched for platforms such as Skulpt, CodeMirror and Trinket and they seem ok for what I want to do. However, I want to develop a GUI for the users to input parameters since there are a lot of options and I don't want users with no Python experience to run the programs from the command line like I do and hide the Python code behind the GUI. I have learnt simplegui recently but I think the GUIs you can create are not visually pleasant and for me this is a big no. I also saw in another post that using Tkinker with a in-browser python implementation is not possible.</p>
<p>So, I would like to know what would be the best combination of in-browser Python implementation and GUI module to reach my goal please?</p>
<p>Thank you so much!</p>
| 0
|
2016-09-07T08:56:28Z
| 39,369,084
|
<p>I guess <a href="http://jupyter.org/" rel="nofollow">Jupyter</a> could meet your needs. <a href="http://jupyter.readthedocs.io/en/latest/install.html" rel="nofollow">Getting started here</a>.</p>
<blockquote>
<p>The Jupyter Notebook is a web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, machine learning and much more.</p>
<p>The Notebook has support for over 40 programming languages, including those popular in Data Science such as Python, R, Julia and Scala.</p>
</blockquote>
| 0
|
2016-09-07T11:47:04Z
|
[
"python",
"user-interface",
"browser"
] |
How to drop duplicated rows using pandas in a big data file?
| 39,365,568
|
<p>I have a csv file that too big to load to memory.I need to drop duplicated rows of the file.So I follow this way:</p>
<pre><code>chunker = pd.read_table(AUTHORS_PATH, names=['Author ID', 'Author name'], encoding='utf-8', chunksize=10000000)
for chunk in chunker:
chunk.drop_duplicates(['Author ID'])
</code></pre>
<p>But if duplicated rows distribute in different chunk seems like above script can't get the expected results.</p>
<p>Is there any better wayï¼</p>
| 2
|
2016-09-07T09:02:23Z
| 39,365,740
|
<p>You could try something like this.</p>
<p>First, create your chunker.</p>
<pre><code>chunker = pd.read_table(AUTHORS_PATH, names=['Author ID', 'Author name'], encoding='utf-8', chunksize=10000000)
</code></pre>
<p>Now create a set of ids:</p>
<pre><code>ids = set()
</code></pre>
<p>Now iterate over the chunks:</p>
<pre><code>for chunk in chunker:
chunk.drop_duplicates(['Author ID'])
</code></pre>
<p>However, now, within the body of the loop, drop also ids already in the set of known ids:</p>
<pre><code> chunk = chunk[~chunk['Author ID'].isin(ids)]
</code></pre>
<p>Finally, still within the body of the loop, add the new ids</p>
<pre><code> ids.update(chunk['Author ID'].values)
</code></pre>
<hr>
<p>If <code>ids</code> is too large to fit into main memory, you might need to use some disk-based database.</p>
| 1
|
2016-09-07T09:10:15Z
|
[
"python",
"database",
"pandas",
"bigdata"
] |
Execute Jobs using Spark + Cassandra utilizing data locality
| 39,365,641
|
<p>I have an exec, which accepts a cassandra primary key as input.</p>
<pre><code>Cassandra Row: (id, date), clustering_key, data
./exec id date
</code></pre>
<p>Each exec can access multiple rows for given primary key. After performing execution on data, it stores results in a DB.</p>
<p>I have multiple such execs and I want to run exec on a node which stores data. How can I achieve this using spark?</p>
<p>Also, how do I receive node ip in which the exec has run [For verification purposes].</p>
<p>Note: In exec I am accessing data by executing query:</p>
<pre><code>select data from table where id = t_id and date = t_date and clustering_key = t_clustering_key
</code></pre>
| 0
|
2016-09-07T09:05:45Z
| 39,395,795
|
<p>If you want to use Spark (with data locality), you have to write Spark program to do the same thing <code>exec</code> is doing. Spark driver (you can use DataStax Cassandra/Spark Connector) takes care of locality issues automatically. </p>
<p>If you want to exploit the data locality without writing Spark program, then it's going to be difficult and I don't know if you need Spark at all, in that case.</p>
<p>P.S. If you are doing a shuffle operation in Spark (which I don't think you are doing), then writing a Spark program is also not going to help with data locality.</p>
<p>References:
<a href="http://events.linuxfoundation.org/sites/events/files/slides/Spark-Cassandra%20Integration,%20theory%20and%20practice%20ApacheBigData%202015_0.pdf?bcsi_scan_fd86d3dd427d821e=0&bcsi_scan_filename=Spark-Cassandra%20Integration,%20theory%20and%20practice%20ApacheBigData%202015_0.pdf" rel="nofollow">Presentation by Datastax employee about Spark and Cassandra data locality</a></p>
| 0
|
2016-09-08T16:13:21Z
|
[
"python",
"apache-spark",
"cassandra"
] |
Find eigenvalues of Complex valued matrix in python
| 39,365,697
|
<p>I need to find the eigenvvalues of of this matrix, and similar such matrices (spaces denote separators):</p>
<pre><code>[[1.0000 -0.7071*I 0 -0.7071*I 0 0 0 0 0]
[0.7071*I 0.5000 -0.7071*I 0 -0.70710*I 0 0 0 0]
[0 0.7071*I 1.0000 0 0 -0.7071*I 0 0 0]
[0.7071*I 0 0 0.5000 -0.7071*I 0 -0.7071*I 0 0]
[0 0.7071*I 0 0.7071*I 0 -0.7071*I 0 -0.7071*I 0]
[0 0 0.7071*I 0 0.7071*I 0.5000 0 0 -0.7071*I]
[0 0 0 0.7071*I 0 0 1.0000 -0.7071*I 0]
[0 0 0 0 0.7071*I 0 0.7071*I 0.5000 -0.7071*I]
[0 0 0 0 0 0.7071*I 0 0.7071*I 1.000]]
</code></pre>
<p><strong>Error:</strong>
<code>numpy.linalg.eigvalsh()</code> gives error "can't convert complex to float".</p>
<p>What could be the reason, and how do I find eigenvalues?</p>
| 0
|
2016-09-07T09:08:06Z
| 39,365,774
|
<p>In numpy you get this for free</p>
<pre><code>import numpy as np
matrix = np.array([[1+1j,0+1j],[0+1j,1+1j]])
eingenvalues,eigenvectors=np.linalg.eig(matrix)
</code></pre>
<p>will give you both, eigenvalues and corresponding eigenvectosr</p>
<p>If you are really only interested in the eigen values you can use</p>
<pre><code>eingenvalues=np.linalg.eigvals(matrix)
</code></pre>
| -1
|
2016-09-07T09:11:39Z
|
[
"python",
"numpy",
"matrix",
"linear-algebra",
"eigenvalue"
] |
Find eigenvalues of Complex valued matrix in python
| 39,365,697
|
<p>I need to find the eigenvvalues of of this matrix, and similar such matrices (spaces denote separators):</p>
<pre><code>[[1.0000 -0.7071*I 0 -0.7071*I 0 0 0 0 0]
[0.7071*I 0.5000 -0.7071*I 0 -0.70710*I 0 0 0 0]
[0 0.7071*I 1.0000 0 0 -0.7071*I 0 0 0]
[0.7071*I 0 0 0.5000 -0.7071*I 0 -0.7071*I 0 0]
[0 0.7071*I 0 0.7071*I 0 -0.7071*I 0 -0.7071*I 0]
[0 0 0.7071*I 0 0.7071*I 0.5000 0 0 -0.7071*I]
[0 0 0 0.7071*I 0 0 1.0000 -0.7071*I 0]
[0 0 0 0 0.7071*I 0 0.7071*I 0.5000 -0.7071*I]
[0 0 0 0 0 0.7071*I 0 0.7071*I 1.000]]
</code></pre>
<p><strong>Error:</strong>
<code>numpy.linalg.eigvalsh()</code> gives error "can't convert complex to float".</p>
<p>What could be the reason, and how do I find eigenvalues?</p>
| 0
|
2016-09-07T09:08:06Z
| 39,370,732
|
<p>As more than one commenter has explained, your matrix works fine with <code>eigvalsh</code>.</p>
<pre><code>import numpy as np
from numpy.linalg import eigvalsh
I = 1j
arr = np.array([[1.0000, -0.7071*I, 0, -0.7071*I, 0, 0, 0, 0, 0],
[0.7071*I, 0.5000, -0.7071*I, 0, -0.70710*I, 0, 0, 0, 0],
[0, 0.7071*I, 1.0000, 0, 0, -0.7071*I, 0, 0, 0],
[0.7071*I, 0, 0, 0.5000, -0.7071*I, 0, -0.7071*I, 0, 0],
[0, 0.7071*I, 0, 0.7071*I, 0, -0.7071*I, 0, -0.7071*I, 0],
[0, 0, 0.7071*I, 0, 0.7071*I, 0.5000, 0, 0, -0.7071*I],
[0, 0, 0, 0.7071*I, 0, 0, 1.0000, -0.7071*I, 0],
[0, 0, 0, 0, 0.7071*I, 0, 0.7071*I, 0.5000, -0.7071*I],
[0, 0, 0, 0, 0, 0.7071*I, 0, 0.7071*I, 1.000]])
# Ensure hermitian
assert(np.all(0 == (arr - np.conj(arr.T))))
print(eigvalsh(arr))
# outputs:
# [-1.56153421 -0.2807671 -0.2807671 0.5 0.5 1. 1.7807671 1.7807671 2.56153421]
</code></pre>
| 1
|
2016-09-07T13:04:59Z
|
[
"python",
"numpy",
"matrix",
"linear-algebra",
"eigenvalue"
] |
How can I change outfile path? outfile = join(basename(image))
| 39,365,733
|
<p>I can't figure out how to change the filepath on this code?</p>
<pre><code>import os
import glob
import time
import traceback
from time import sleep
import RPi.GPIO as GPIO
import picamera
import atexit
import sys
import socket
import pygame
from pygame.locals import QUIT, KEYDOWN, K_ESCAPE
import pytumblr
import config
from signal import alarm, signal, SIGALRM, SIGKILL
from os.path import join, basename, expanduser
from PIL import Image
def watermark(image):
""" Apply a watermark to an image """
mark = Image.open(watermark_img)
im = Image.open(image)
if im.mode != 'RGBA':
im = im.convert('RGBA')
layer = Image.new('RGBA', im.size, (0,0,0,0))
position = (im.size[0] - mark.size[0], im.size[1] - mark.size[1])
layer.paste(mark, position)
outfile = join(basename(image))
Image.composite(layer, im, layer).save(outfile)
return outfile
</code></pre>
<p>I want it to go to either: <code>/home/pi/photobooth/pics/</code> or a <code>config.file_path</code> which is the same location.</p>
| 0
|
2016-09-07T09:09:51Z
| 39,378,887
|
<p>Ok, so I have read the doc of PIL (all as expected) and You should try :</p>
<pre><code>outfile = join( <your_path> , basename(image) ) # replace your_path to actual path
Image.composite(layer, im, layer).save(outfile)
</code></pre>
| 0
|
2016-09-07T20:57:53Z
|
[
"python",
"path",
"filepath"
] |
MultiValueDictKeyError after trying to log in
| 39,365,840
|
<p>I'm getting a MultiValueDictKey error.</p>
<p>This is my view:</p>
<pre><code>from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.http import HttpResponse, HttpResponseRedirect
from bookonshelf import settings
def Login(request):
next = request.GET.get('next', '/home/')
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(next)
else:
return HttpResponse("Inactive user.")
else:
return HttpResponseRedirect(settings.LOGIN_URL)
return render(request, "index/login.html", {'redirect_to': next})
</code></pre>
<p>And my login.html:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Admin panel</title>
<!-- Bootstrap core CSS -->
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="/static/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="/static/css/signin.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file- warning.js"></script><![endif]-->
<script src="/static/assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"> </script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<form class="form-signin" method="post" action=".?next={{ redirect_to }}"> {% csrf_token %}
<h2 class="form-signin-heading">Admin panel</h2>
<label for="username" class="sr-only">Username</label>
<input type="text" id="username" class="form-control" placeholder="Username" required autofocus>
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/static/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
</code></pre>
<p>I already tried changing request.POST to request.POST.get after reading some similar problems online, but that's not working for me.</p>
<pre><code>def Login(request):
next = request.GET.get('next', '/home/')
if request.method == "POST":
username = request.POST.get('username', False)
password = request.POST.get('password', False)
user = authenticate(username=username, password=password)
</code></pre>
<p>How do I solve this?</p>
| -1
|
2016-09-07T09:14:50Z
| 39,366,186
|
<p>You never give your inputs a name so they are never added to the post data</p>
<pre><code><input type="text" id="username" name="username">
<input type="password" id="password" name="password">
</code></pre>
<p><sub><sub>I removed some attributes for brevity</sub></sub></p>
<p>Also note:</p>
<ul>
<li><p>You should import settings from <code>django.conf</code> (<code>from django.conf import settings</code>), this isn't a module, its a class that does magic to always get the right <code>DJANGO_SETTINGS_MODULE</code>.</p></li>
<li><p>You should just use a django form which can stop these kind of errors from ever occuring</p></li>
<li><p>You should give better defaults than <code>False</code>, these values are strings and False doesn't make sense here.</p></li>
</ul>
| 1
|
2016-09-07T09:30:17Z
|
[
"python",
"django"
] |
MultiValueDictKeyError after trying to log in
| 39,365,840
|
<p>I'm getting a MultiValueDictKey error.</p>
<p>This is my view:</p>
<pre><code>from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.http import HttpResponse, HttpResponseRedirect
from bookonshelf import settings
def Login(request):
next = request.GET.get('next', '/home/')
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(next)
else:
return HttpResponse("Inactive user.")
else:
return HttpResponseRedirect(settings.LOGIN_URL)
return render(request, "index/login.html", {'redirect_to': next})
</code></pre>
<p>And my login.html:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Admin panel</title>
<!-- Bootstrap core CSS -->
<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="/static/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="/static/css/signin.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file- warning.js"></script><![endif]-->
<script src="/static/assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"> </script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<form class="form-signin" method="post" action=".?next={{ redirect_to }}"> {% csrf_token %}
<h2 class="form-signin-heading">Admin panel</h2>
<label for="username" class="sr-only">Username</label>
<input type="text" id="username" class="form-control" placeholder="Username" required autofocus>
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/static/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
</code></pre>
<p>I already tried changing request.POST to request.POST.get after reading some similar problems online, but that's not working for me.</p>
<pre><code>def Login(request):
next = request.GET.get('next', '/home/')
if request.method == "POST":
username = request.POST.get('username', False)
password = request.POST.get('password', False)
user = authenticate(username=username, password=password)
</code></pre>
<p>How do I solve this?</p>
| -1
|
2016-09-07T09:14:50Z
| 39,366,203
|
<p>Put <code>name=</code> for both fields. Ex</p>
<pre><code><input type="text" name="username" id="username" class="form-control" placeholder="Username" required autofocus>
</code></pre>
| 1
|
2016-09-07T09:30:48Z
|
[
"python",
"django"
] |
Download all attachments received in the past 30 days
| 39,365,885
|
<p>Below is my code.</p>
<pre><code>import win32com.client,datetime
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders('Paper & CD')
messages = inbox.Items
date_now = datetime.datetime.now().date()
date_before = (datetime.datetime.now() + datetime.timedelta(-30)).date()
for msg in messages:
for att in msg.Attachments:
if att.FileName == 'list.csv':
att.SaveAsFile('C:\\My\\temp\\' + msg.subject + att.FileName)
att.SaveAsFile('C:\\My\\temp\\' + att.FileName)
</code></pre>
<p>It downloads all attachments from the particular folder.</p>
<p>I need to download only attachments not more than 30 days old.</p>
<p>I tried with <code>msg.LastModificationTime</code> but it gives last modified time of mail.</p>
<p>I want to know the received date for each mail so I can compare it with current date.</p>
| 0
|
2016-09-07T09:17:08Z
| 39,376,069
|
<p>Use <code>Items.Restrict</code> or <code>Items.Find/FindNext</code> with a restriction based on the <code>ReceivedTime</code> property.</p>
| 0
|
2016-09-07T17:32:54Z
|
[
"python",
"outlook"
] |
django inspectdb 'unique_together' refers to the non-existent field
| 39,366,071
|
<p>I have a legacy database that I wish to use as a second database in my django project. I added the database to my settings file, and ran:</p>
<pre><code>python manage.py inspectdb --database=images
</code></pre>
<p>The script finished in less than a second, and the results were astounding. It understood all my tables - or so I thought at first. When I tried to run:</p>
<pre><code>python manage.py migrate --database=images
</code></pre>
<p>I got errors like this:</p>
<pre><code>'unique_together' refers to the non-existent field 'commentaryId'.
</code></pre>
<p>All of the tables that raised errors were many-to-many linking tables containing two id fields that together formed the primary key (and thus had to be 'unique together').</p>
<p>Here is one of the models, created by inspectdb, that raised this error:</p>
<pre><code>class Pagescanannotationscommentaries(models.Model):
pagescanannotationid = models.IntegerField(db_column='pageScanAnnotationId') # Field name made lowercase.
commentaryid = models.IntegerField(db_column='commentaryId') # Field name made lowercase.
class Meta:
managed = False
db_table = 'PageScanAnnotationsCommentaries'
unique_together = (('pageScanAnnotationId', 'commentaryId'),)
</code></pre>
<p>I found several questions like mine in stackoverflow, but the suggestions did not help me, or were obviously not relevant. But I did find a post in google groups that gave me the tip that fixed it: <a href="https://groups.google.com/forum/#!topic/django-users/_phTiifN3K0" rel="nofollow">https://groups.google.com/forum/#!topic/django-users/_phTiifN3K0</a></p>
<p>But even then, my problem was a bit different, I found, and I explain in the answer below.</p>
| 0
|
2016-09-07T09:25:31Z
| 39,366,072
|
<p>django's inspectdb took my legacy field names as the field names for unique_together. I changed this so it used the properties in the model, and that solved the problem. I also added the _ before the id, as stated in the google groups post listed above. But I am not sure if that underscore was relevant. Right now, I don't want to mess with my set up, so I leave the test with the underscores (or rather without underscores) to someone else. :-) If I have time to test that, I will post what I find here.</p>
<p>Here is my working model code:</p>
<pre><code>class Pagescanannotationscommentaries(models.Model):
pagescanannotation_id = models.IntegerField(db_column='pageScanAnnotationId') # Field name made lowercase.
commentary_id = models.IntegerField(db_column='commentaryId') # Field name made lowercase.
class Meta:
managed = False
db_table = 'PageScanAnnotationsCommentaries'
unique_together = (('pagescanannotation_id', 'commentary_id'),)
</code></pre>
<p>This change made the error message disappear.</p>
| 0
|
2016-09-07T09:25:31Z
|
[
"python",
"django",
"inspectdb"
] |
django inspectdb 'unique_together' refers to the non-existent field
| 39,366,071
|
<p>I have a legacy database that I wish to use as a second database in my django project. I added the database to my settings file, and ran:</p>
<pre><code>python manage.py inspectdb --database=images
</code></pre>
<p>The script finished in less than a second, and the results were astounding. It understood all my tables - or so I thought at first. When I tried to run:</p>
<pre><code>python manage.py migrate --database=images
</code></pre>
<p>I got errors like this:</p>
<pre><code>'unique_together' refers to the non-existent field 'commentaryId'.
</code></pre>
<p>All of the tables that raised errors were many-to-many linking tables containing two id fields that together formed the primary key (and thus had to be 'unique together').</p>
<p>Here is one of the models, created by inspectdb, that raised this error:</p>
<pre><code>class Pagescanannotationscommentaries(models.Model):
pagescanannotationid = models.IntegerField(db_column='pageScanAnnotationId') # Field name made lowercase.
commentaryid = models.IntegerField(db_column='commentaryId') # Field name made lowercase.
class Meta:
managed = False
db_table = 'PageScanAnnotationsCommentaries'
unique_together = (('pageScanAnnotationId', 'commentaryId'),)
</code></pre>
<p>I found several questions like mine in stackoverflow, but the suggestions did not help me, or were obviously not relevant. But I did find a post in google groups that gave me the tip that fixed it: <a href="https://groups.google.com/forum/#!topic/django-users/_phTiifN3K0" rel="nofollow">https://groups.google.com/forum/#!topic/django-users/_phTiifN3K0</a></p>
<p>But even then, my problem was a bit different, I found, and I explain in the answer below.</p>
| 0
|
2016-09-07T09:25:31Z
| 39,366,324
|
<p>This was a bug in Django 1.8, see <a href="https://code.djangoproject.com/ticket/25274" rel="nofollow">#25274</a>. It has been fixed in 1.8.8. You should upgrade to the latest 1.8.x version. </p>
<p>Note that minor version upgrades, from 1.8.x to 1.8.x+1, only include bugfixes and security updates. You should always aim to use the latest minor version. Only major version upgrades, from 1.Y to 1.Y+1, may break compatibility as outlined in the deprecation timeline. </p>
| 2
|
2016-09-07T09:36:11Z
|
[
"python",
"django",
"inspectdb"
] |
Python: can't instantiate my object from inside another object: 'global name not defined'
| 39,366,082
|
<p>Hi all and thanks in advance for any help. </p>
<p>I am learning Python and working on a Zork style adventure game to practise.</p>
<p>Once I've defined classes my first actual instruction is</p>
<pre><code>ourGame = Game('githyargi.txt')
</code></pre>
<p>where githyargi.txt is a file containing all the game's strings. method Game.parseText() works as documented.</p>
<p>Traceback shows the problem:</p>
<pre><code>Traceback (most recent call last):
File "githyargi.py", line 237, in <module>
ourGame = Game('githyargi.txt')
File "githyargi.py", line 12, in __init__
self.scenes[0] = Start()
File "githyargi.py", line 166, in __init__
for string in ourGame.strings['FIRST']:
NameError: global name 'ourGame' is not defined
</code></pre>
<p>If I do <code>ourGame.scenes[0] = Start()</code> from the execution block it works great- no name error, and <code>self.scenes[0].flavStr</code> gets filled up with the appropriate flavour text. However I want to create a method <code>Game.makeScenes()</code> that will create all the scenes in the game and store them in list <code>ourGame.scenes</code>. Why can't the <strong>init</strong> of Start() see ourGame.strings when instantiated from the <strong>init</strong> of Game(), when it can see the same dict when instantiated from the execution block?</p>
<pre><code>class Game(object):
def __init__(self, filename):
'''creates a new map, calls parseText, initialises the game status dict.'''
self.strings = self.parseText(filename)
self.sceneIndex = 0
self.scenes = []
self.scenes[0] = Start()
self.status = {
"Health": 100,
"Power": 10,
"Weapon": "Unarmed",
"Gizmo": "None",
"Turn": 0,
"Alert": 0,
"Destruct": -1
}
def parseText(self, filename):
'''Parses the text file and extracts strings into a dict of
category:[list of strings.]'''
textFile = open(filename)
#turn the file into a flat list of strings and reverse it
stringList = []; catList = [] ; textParsed = {}
for string in textFile.readlines():
stringList.append(string.strip())
stringList.reverse()
#make catList by popping strings off stringList until we hit '---'
for i in range(0, len(stringList)):
string = stringList.pop()
if string == '---':
break
else:
catList.append(string)
#Fill categories
for category in catList:
newList = []
for i in range(0, len(stringList)):
string = stringList.pop()
if string == '---':
break
else:
newList.append(string)
textParsed[category] = newList
return textParsed
class Scene(object):
def __init__(self):
'''sets up variables with null values'''
self.sceneType = 'NULL'
self.flavStr = "null"
self.optStr = "null"
self.scenePaths = []
class Start(Scene):
def __init__(self):
self.flavStr = ""
for string in ourGame.strings['FIRST']:
self.flavStr += '\n'
self.flavStr += string
self.optStr = "\nBefore you lies a dimly lit corridor. (1) to boldly go."
self.scenePaths = [1]
</code></pre>
| -1
|
2016-09-07T09:25:59Z
| 39,366,170
|
<p>It's a timing thing. When you do</p>
<pre><code>ourGame = Game('githyargi.txt')
</code></pre>
<p>Then first the Game instance is created, and only then is it assigned to ourGame.</p>
<p>Instead, pass the Game to use to the constructor of Scene, and pass <code>self</code> so it becomes something like</p>
<pre><code>self.scenes.append(Start(self))
</code></pre>
<p>Note that you also can't do <code>scenes = []</code> and then set <code>scenes[0]</code> on the next line -- an empty list doesn't have an element 0.</p>
| 0
|
2016-09-07T09:29:31Z
|
[
"python",
"nameerror"
] |
Numpy Cosine Similarity difference over big collections
| 39,366,120
|
<p>I need to use the Scikit-learn <strong>sklearn.metric.pairwise.cosine_similarity</strong> over big matrixes.
For some optimizations i need to compute only some rows of the matrixes, and so i tried different methods.</p>
<p>I found that in some cases <strong>the results were different depending on the size of the vectors</strong>, and I saw this strange behaviour on this test case (big vectors, transpose and estimate cosine):</p>
<pre><code>from sklearn.metrics.pairwise import cosine_similarity
from scipy import spatial
import numpy as np
from scipy.sparse import csc_matrix
size=200
a=np.array([[1,0,1,0]]*size)
sparse_a=csc_matrix(a.T)
#standard cosine similarity between the whole transposed matrix, take only the first row
res1=cosine_similarity(a.T,a.T)[0]
#take the row obtained by the multiplication of the first row of the transposed matrix with transposed matrix itself (optimized for the first row calculus only)
res2=cosine_similarity([a.T[0]],a.T)[0]
#sparse matrix implementation with the transposed, which should be faster
res3=cosine_similarity(sparse_a,sparse_a)[0]
print("res1: ",res1)
print("res2: ",res2)
print("res3: ",res3)
print("res1 vs res2: ",res1==res2)
print("res1 vs res3: ",res1==res3)
print("res2 vs res3: ", res2==res3)
</code></pre>
<p>If "<strong>size</strong>" is set to <strong>200</strong> I got this result, that is ok:</p>
<pre><code>res1: [ 1. 0. 1. 0.]
res2: [ 1. 0. 1. 0.]
res3: [ 1. 0. 1. 0.]
res1 vs res2: [ True True True True]
res1 vs res3: [ True True True True]
res2 vs res3: [ True True True True]
</code></pre>
<p>But if "<strong>size</strong>" is set to <strong>2000</strong> or more, some strange things happen:</p>
<pre><code>res1: [ 1. 0. 1. 0.]
res2: [ 1. 0. 1. 0.]
res3: [ 1. 0. 1. 0.]
res1 vs res2: [False True False True]
res1 vs res3: [False True False True]
res2 vs res3: [ True True True True]
</code></pre>
<p>Does anybody know what am I missing?</p>
<p>Thanks in advance</p>
| 2
|
2016-09-07T09:27:38Z
| 39,370,113
|
<p>In order to compare <code>numpy.array</code> you have to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.isclose.html" rel="nofollow"><code>np.isclose</code></a> instead of equality operator. Try:</p>
<pre><code>from sklearn.metrics.pairwise import cosine_similarity
from scipy import spatial
import numpy as np
from scipy.sparse import csc_matrix
size=2000
a=np.array([[1,0,1,0]]*size)
sparse_a=csc_matrix(a.T)
#standard cosine similarity between the whole transposed matrix, take only the first row
res1=cosine_similarity(a.T,a.T)[0]
#take the row obtained by the multiplication of the first row of the transposed matrix with transposed matrix itself (optimized for the first row calculus only)
res2=cosine_similarity([a.T[0]],a.T)[0]
#sparse matrix implementation with the transposed, which should befaster
res3=cosine_similarity(sparse_a,sparse_a)[0]
print("res1: ",res1)
print("res2: ",res2)
print("res3: ",res3)
print("res1 vs res2: ", np.isclose(res1, res2))
print("res1 vs res3: ", np.isclose(res1, res3))
print("res2 vs res3: ", np.isclose(res2, res2))
</code></pre>
<p>The results are:</p>
<pre><code>res1: [ 1. 0. 1. 0.]
res2: [ 1. 0. 1. 0.]
res3: [ 1. 0. 1. 0.]
res1 vs res2: [ True True True True]
res1 vs res3: [ True True True True]
res2 vs res3: [ True True True True]
</code></pre>
<p>as expected.</p>
| 0
|
2016-09-07T12:34:27Z
|
[
"python",
"numpy",
"scikit-learn",
"cosine-similarity"
] |
How to store values retrieved from a loop in different variables in Python?
| 39,366,134
|
<p>Just a quick question.<br>
Suppose, I have a simple for-loop like </p>
<pre><code>for i in range(1,11):
x = raw_input()
</code></pre>
<p>and I want to store all the values of <em>x</em> that I will be getting throughout the loop in <em>different variables</em> such that I can use all these <em>different variables</em> later on when the loop is over.</p>
| -1
|
2016-09-07T09:28:16Z
| 39,366,187
|
<p>You can store each input in a list, then access them later when you want.</p>
<pre><code>inputs = []
for i in range(1,11);
x = raw_input()
inputs.append(x)
# print all inputs
for inp in inputs:
print(inp)
# Access a specific input
print(inp[0])
print(inp[1])
</code></pre>
| 3
|
2016-09-07T09:30:19Z
|
[
"python",
"python-2.7",
"for-loop",
"iteration"
] |
How to store values retrieved from a loop in different variables in Python?
| 39,366,134
|
<p>Just a quick question.<br>
Suppose, I have a simple for-loop like </p>
<pre><code>for i in range(1,11):
x = raw_input()
</code></pre>
<p>and I want to store all the values of <em>x</em> that I will be getting throughout the loop in <em>different variables</em> such that I can use all these <em>different variables</em> later on when the loop is over.</p>
| -1
|
2016-09-07T09:28:16Z
| 39,366,192
|
<p>You can form a list with them.</p>
<pre><code>your_list = [raw_input() for _ in range(1, 11)]
</code></pre>
<p>To print the list, do:</p>
<pre><code>print your_list
</code></pre>
<p>To iterate through the list, do:</p>
<pre><code>for i in your_list:
#do_something
</code></pre>
| 3
|
2016-09-07T09:30:23Z
|
[
"python",
"python-2.7",
"for-loop",
"iteration"
] |
How to store values retrieved from a loop in different variables in Python?
| 39,366,134
|
<p>Just a quick question.<br>
Suppose, I have a simple for-loop like </p>
<pre><code>for i in range(1,11):
x = raw_input()
</code></pre>
<p>and I want to store all the values of <em>x</em> that I will be getting throughout the loop in <em>different variables</em> such that I can use all these <em>different variables</em> later on when the loop is over.</p>
| -1
|
2016-09-07T09:28:16Z
| 39,366,217
|
<p>Create a list before the loop and store x in the list as you iterate:</p>
<pre><code>l=[]
for i in range(1,11):
x = raw_input()
l.append(x)
print(l)
</code></pre>
| 3
|
2016-09-07T09:31:26Z
|
[
"python",
"python-2.7",
"for-loop",
"iteration"
] |
inherited function odoo python
| 39,366,140
|
<p>i want to inherit function in module 'hr_holidays' that calculate remaining leaves the function is :</p>
<h2>hr_holiday.py:</h2>
<pre><code>def _get_remaining_days(self, cr, uid, ids, name, args, context=None):
cr.execute("""SELECT
sum(h.number_of_days) as days,
h.employee_id
from
hr_holidays h
join hr_holidays_status s on (s.id=h.holiday_status_id)
where
h.state='validate' and
s.limit=False and
h.employee_id in %s
group by h.employee_id""", (tuple(ids),))
res = cr.dictfetchall()
remaining = {}
for r in res:
remaining[r['employee_id']] = r['days']
for employee_id in ids:
if not remaining.get(employee_id):
remaining[employee_id] = 0.0
return remaining
</code></pre>
<p>i had create my own module that inherited to <code>hr_holidays</code> and try this code to inherit but it isnt work </p>
<hr>
<p>myclass.py</p>
<pre><code>class HrHolidays(models.Model):
_inherit = 'hr.holidays'
interim = fields.Many2one(
'hr.employee',
string="Interim")
partner_id = fields.Many2one('res.partner', string="Customer")
remaining_leaves = fields.Char(string='Leaves remaining')
def _get_remaining_days(self, cr, uid, ids, name, args, context=None):
res = super(hr_holidays,self)._get_remaining_days(cr, uid, ids, name, args, context)
return res
</code></pre>
<hr>
<p>please help me </p>
| 1
|
2016-09-07T09:28:30Z
| 39,366,945
|
<p>You have to call the right Class in super():</p>
<pre class="lang-py prettyprint-override"><code>res = super(HrHolidays, self)._get_remaining_days(
cr, uid, ids, name, args, context)
</code></pre>
| 0
|
2016-09-07T10:06:47Z
|
[
"python",
"openerp"
] |
inherited function odoo python
| 39,366,140
|
<p>i want to inherit function in module 'hr_holidays' that calculate remaining leaves the function is :</p>
<h2>hr_holiday.py:</h2>
<pre><code>def _get_remaining_days(self, cr, uid, ids, name, args, context=None):
cr.execute("""SELECT
sum(h.number_of_days) as days,
h.employee_id
from
hr_holidays h
join hr_holidays_status s on (s.id=h.holiday_status_id)
where
h.state='validate' and
s.limit=False and
h.employee_id in %s
group by h.employee_id""", (tuple(ids),))
res = cr.dictfetchall()
remaining = {}
for r in res:
remaining[r['employee_id']] = r['days']
for employee_id in ids:
if not remaining.get(employee_id):
remaining[employee_id] = 0.0
return remaining
</code></pre>
<p>i had create my own module that inherited to <code>hr_holidays</code> and try this code to inherit but it isnt work </p>
<hr>
<p>myclass.py</p>
<pre><code>class HrHolidays(models.Model):
_inherit = 'hr.holidays'
interim = fields.Many2one(
'hr.employee',
string="Interim")
partner_id = fields.Many2one('res.partner', string="Customer")
remaining_leaves = fields.Char(string='Leaves remaining')
def _get_remaining_days(self, cr, uid, ids, name, args, context=None):
res = super(hr_holidays,self)._get_remaining_days(cr, uid, ids, name, args, context)
return res
</code></pre>
<hr>
<p>please help me </p>
| 1
|
2016-09-07T09:28:30Z
| 39,370,623
|
<p>You need to call super with <code>HrHolidays</code> and pass just name and args to <code>_get_remaining_days</code> method and override <code>remaining_leaves</code> field: </p>
<p><strong>Python</strong> </p>
<pre><code>class HrHolidays(models.Model):
_inherit = 'hr.employee'
@api.model
def _get_remaining_days(self):
res = super(HrHolidays, self)._get_remaining_days(name='', args={})
for record in self:
if record.id in res:
record.remaining_leaves = res.get(record.id)
return res
remaining_leaves = fields.Float(compute='_get_remaining_days',
string='Remaining Legal Leaves')
</code></pre>
| 0
|
2016-09-07T12:59:45Z
|
[
"python",
"openerp"
] |
inherited function odoo python
| 39,366,140
|
<p>i want to inherit function in module 'hr_holidays' that calculate remaining leaves the function is :</p>
<h2>hr_holiday.py:</h2>
<pre><code>def _get_remaining_days(self, cr, uid, ids, name, args, context=None):
cr.execute("""SELECT
sum(h.number_of_days) as days,
h.employee_id
from
hr_holidays h
join hr_holidays_status s on (s.id=h.holiday_status_id)
where
h.state='validate' and
s.limit=False and
h.employee_id in %s
group by h.employee_id""", (tuple(ids),))
res = cr.dictfetchall()
remaining = {}
for r in res:
remaining[r['employee_id']] = r['days']
for employee_id in ids:
if not remaining.get(employee_id):
remaining[employee_id] = 0.0
return remaining
</code></pre>
<p>i had create my own module that inherited to <code>hr_holidays</code> and try this code to inherit but it isnt work </p>
<hr>
<p>myclass.py</p>
<pre><code>class HrHolidays(models.Model):
_inherit = 'hr.holidays'
interim = fields.Many2one(
'hr.employee',
string="Interim")
partner_id = fields.Many2one('res.partner', string="Customer")
remaining_leaves = fields.Char(string='Leaves remaining')
def _get_remaining_days(self, cr, uid, ids, name, args, context=None):
res = super(hr_holidays,self)._get_remaining_days(cr, uid, ids, name, args, context)
return res
</code></pre>
<hr>
<p>please help me </p>
| 1
|
2016-09-07T09:28:30Z
| 39,371,067
|
<p>thanks for all ,
but i got problem in the field ,i want to award my function to my field i have done that but isn't work :</p>
<pre><code> remaining_leaves = fields.Function(_get_remaining_days,string='Leaves')
</code></pre>
<p>i got this error
<a href="http://i.stack.imgur.com/acICN.png" rel="nofollow"><img src="http://i.stack.imgur.com/acICN.png" alt="enter image description here"></a></p>
| 0
|
2016-09-07T13:20:49Z
|
[
"python",
"openerp"
] |
inherited function odoo python
| 39,366,140
|
<p>i want to inherit function in module 'hr_holidays' that calculate remaining leaves the function is :</p>
<h2>hr_holiday.py:</h2>
<pre><code>def _get_remaining_days(self, cr, uid, ids, name, args, context=None):
cr.execute("""SELECT
sum(h.number_of_days) as days,
h.employee_id
from
hr_holidays h
join hr_holidays_status s on (s.id=h.holiday_status_id)
where
h.state='validate' and
s.limit=False and
h.employee_id in %s
group by h.employee_id""", (tuple(ids),))
res = cr.dictfetchall()
remaining = {}
for r in res:
remaining[r['employee_id']] = r['days']
for employee_id in ids:
if not remaining.get(employee_id):
remaining[employee_id] = 0.0
return remaining
</code></pre>
<p>i had create my own module that inherited to <code>hr_holidays</code> and try this code to inherit but it isnt work </p>
<hr>
<p>myclass.py</p>
<pre><code>class HrHolidays(models.Model):
_inherit = 'hr.holidays'
interim = fields.Many2one(
'hr.employee',
string="Interim")
partner_id = fields.Many2one('res.partner', string="Customer")
remaining_leaves = fields.Char(string='Leaves remaining')
def _get_remaining_days(self, cr, uid, ids, name, args, context=None):
res = super(hr_holidays,self)._get_remaining_days(cr, uid, ids, name, args, context)
return res
</code></pre>
<hr>
<p>please help me </p>
| 1
|
2016-09-07T09:28:30Z
| 39,372,443
|
<p>i think that function work but i couldnt show it by fields.function </p>
<pre><code> remaining_leaves = fields.Function(_get_remaining_days,string='Leaves')
</code></pre>
| 0
|
2016-09-07T14:20:14Z
|
[
"python",
"openerp"
] |
Trying to add two matrices with numbers entered as a string and then display solution, but trouble with stdin and stdout
| 39,366,209
|
<p>It's a programming task to enter two matrices using stdin and then display the result in stdout. I often found runtime error or no stdin or stdout to display while the program is running good.</p>
<p>This is my code for addition of two matrices.</p>
<pre><code> """The constraint is the numbers will be entered only without any
string to be seen on console and also that to be in the same
fashion being each number input separated by a white space."""
import sys
def main():
num1 = []
num2 = []
rc1 = raw_input().split(' ')
rc1_arr = [int(z) for z in rc1]
r1 = rc1_arr[0]
c1 = rc1_arr[1]
while(r1 != 0):
mat1 = raw_input().split(' ')
arr1 = [int(z1) for z1 in mat1]
num1.append(arr1)
r1=r1-1
rc2 = raw_input().split(' ')
rc2_arr = [int(z) for z in rc2]
r2 = rc2_arr[0]
c2 = rc2_arr[1]
while(r2 != 0):
mat2 = raw_input().split(' ')
arr2 = [int(z2) for z2 in mat2]
num2.append(arr2)
r2=r2-1
for i in range(max(rc1_arr[0],rc2_arr[0])):
for j in range(max(rc1_arr[1],rc2_arr[1])):
su = num1[i][j]+num2[i][j]
sys.stdout.write(str(su))
sys.stdout.write(" ")
sys.stdout.write("\n")
main()
""" while running in idle it looks like this
##The input part is:
3 3 ## represents no. of rows and columns
1 2 3 ## This is the matrix 1 of 3*3
4 5 6
7 8 9
3 3 ## represents no. of rows and columns for second matrix
1 1 1 ## This is the matrix 2 of 3*3
1 1 1
1 1 1
## And the output is like:
2 3 4 ## Sum of the above two matrices.
5 6 7
8 9 10
"""
</code></pre>
<p>Please help.</p>
| 0
|
2016-09-07T09:30:59Z
| 39,368,245
|
<p>You could have some problem with the indentation... I did not touch a line (other than adjust the indentation and it work as expected!)</p>
<pre><code>#!/usr/bin/env pyhton2
import sys
def main():
num1 = []
num2 = []
rc1 = raw_input().split(' ')
rc1_arr = [int(z) for z in rc1]
r1 = rc1_arr[0]
c1 = rc1_arr[1]
while(r1 != 0):
mat1 = raw_input().split(' ')
arr1 = [int(z1) for z1 in mat1]
num1.append(arr1)
r1=r1-1
rc2 = raw_input().split(' ')
rc2_arr = [int(z) for z in rc2]
r2 = rc2_arr[0]
c2 = rc2_arr[1]
while(r2 != 0):
mat2 = raw_input().split(' ')
arr2 = [int(z2) for z2 in mat2]
num2.append(arr2)
r2=r2-1
for i in range(max(rc1_arr[0],rc2_arr[0])):
for j in range(max(rc1_arr[1],rc2_arr[1])):
su = num1[i][j]+num2[i][j]
sys.stdout.write(str(su))
sys.stdout.write(" ")
sys.stdout.write("\n")
main()
</code></pre>
| 0
|
2016-09-07T11:07:17Z
|
[
"python",
"matrix",
"stdout",
"stdin",
"sys"
] |
raising error does not prevent try-except clause to get executed?
| 39,366,264
|
<p>I've got surprised while testing a piece of code that looked a bit like that:</p>
<pre><code>if x:
try:
obj = look-for-item-with-id==x in a db
if obj is None:
# print debug message
raise NotFound('No item with this id')
return obj
except Exception, e:
raise Error(e.message)
</code></pre>
<p>I expected that if there was no item with a provided id (x) in a db, the NotFound exception would be raised. But instead, after getting to if clause and printing debug message it gets to the except clause and raises the Exception (exc message is Item not found...). Could someone be so kind and enlighten me here?</p>
| 1
|
2016-09-07T09:33:19Z
| 39,366,340
|
<p>if obj is array please check if length or count of items is zero
this mean obj not none but not contain items</p>
| -1
|
2016-09-07T09:36:58Z
|
[
"python",
"exception",
"try-except",
"raise"
] |
raising error does not prevent try-except clause to get executed?
| 39,366,264
|
<p>I've got surprised while testing a piece of code that looked a bit like that:</p>
<pre><code>if x:
try:
obj = look-for-item-with-id==x in a db
if obj is None:
# print debug message
raise NotFound('No item with this id')
return obj
except Exception, e:
raise Error(e.message)
</code></pre>
<p>I expected that if there was no item with a provided id (x) in a db, the NotFound exception would be raised. But instead, after getting to if clause and printing debug message it gets to the except clause and raises the Exception (exc message is Item not found...). Could someone be so kind and enlighten me here?</p>
| 1
|
2016-09-07T09:33:19Z
| 39,372,621
|
<p>When you say <code>except Exception, e:</code>, you are explicitly catching (almost) <em>any</em> exception that might get raised within that block -- including your <code>NotFound</code>. </p>
<p>If you want the <code>NotFound</code> itself to propagate further up, you don't need to have a <code>try/except</code> block at all.</p>
<p>Alternatively, if you want to do something specific when you detect the <code>NotFound</code> but then continue propagating the same exception, you can use a blank <code>raise</code> statement to re-raise it instead of raising a new exception like you're doing; something like:</p>
<pre><code>try:
# .. do stuff
if blah:
raise NotFound(...)
except NotFound, e:
# print something
raise
</code></pre>
<p>Also note that I've changed the exception block to <code>except NotFound</code> -- it's generally not a good idea to use <code>except Exception</code> because it catches everything, which can hide errors you may not have expected. Basically, you want to use <code>except</code> to catch <em>specific</em> things which you know how to handle right there. </p>
| 1
|
2016-09-07T14:27:32Z
|
[
"python",
"exception",
"try-except",
"raise"
] |
JSON escape double quotes
| 39,366,291
|
<p>I know this title seems rather popular on here, but a quick browse through them usually involves situations where the asker has one isolated section of JSON.</p>
<p>There are situations where <code>"</code> is used to signify inches, or it wraps a phrase to signify a nickname of some sort, either way it appears in the value string of a JS object which is already wrapped in double quotes.</p>
<p>Here is an example of the JS object string I am having trouble with (I have working regex to double quote the keys and remove extra whitespace, but this is the scraped string in all of its glory):</p>
<pre><code>'{\n\t\t\n\t\t\t\t\t\n\t\n\n\t\n\n\t\n\n\t\t\n\n\t\t \n\n\n\n
"16241885":{title: "Nosefrida Fridababy Windi Gas &amp; Colic Relief", isIneligible: false, isDiscontinued: false, isLowInventory: false, isAllowed: true}
\n\n\t\n\n\t\t\n\t\t\t, \n\t\t\n\t\n\n\t\t\n\n\t\t \n\n\n\n
"8650356":{title: "Babyganics Face- Hand &amp; Baby Wipes- Fragrance Free- 100 Count", isIneligible: false, isDiscontinued: false, isLowInventory: false, isAllowed: true}
\n\n\t\n\n\t\t\n\t\t\t, \n\t\t\n\t\n\n\t\t\n\n\t\t \n\n\n\n
"16249889":{title: "Nosefrida Nasal Aspirator Replacement Filters", isIneligible: false, isDiscontinued: false, isLowInventory: false, isAllowed: true}
\n\n\t\n\n\t\t\n\t\t\t, \n\t\t\n\t\n\n\t\t\n\n\t\t \n\n\n\n
"8650355":{title: "Babyganics Face- Hand &amp; Baby Wipes- Fragrance Free- 40 Count", isIneligible: false, isDiscontinued: false, isLowInventory: false, isAllowed: true}
\n\n\t\n\n\t\t\n\t\t\t, \n\t\t\n\t\n\n\t\t\n\n\t\t \n\n\n\n
"15490928":{title: "BabyGanics Newborn Ultra Absorbent Jumbo Size Diapers - 36 Count", isIneligible: false, isDiscontinued: false, isLowInventory: false, isAllowed: true}
\n\n\t\n\n\t\t\n\t\t\t, \n\t\t\n\t\n\n\t\t\n\n\t\t \n\n\n\n
"14712536":{title: "Marvel Superhero Bandages", isIneligible: false, isDiscontinued: false, isLowInventory: false, isAllowed: true}
\n\n\t\n\n\t\t\n\t\t\t, \n\t\t\n\t\n\n\t\t\n\n\t\t \n\n\n\n
"16263505":{title: "Nosefrida "The Snotsucker" Nasal Aspirator", isIneligible: false, isDiscontinued: false, isLowInventory: false, isAllowed: true}
\n\n\t\n\n\t\t\n\t\t\t, \n\t\t\n\t\n\n\t\t\n\n\t\t \n\n\n\n
"14848093":{title: "Zarbee\'s Children\'s Cough Syrup - Grape", isIneligible: false, isDiscontinued: false, isLowInventory: false, isAllowed: true}
\n\n\t\n\n\t\t\n\t \n\n\t\t\n\t}'
</code></pre>
<p>I have tried, <code>json.dumps</code> on the string first but that just double escapes and needs a double <code>json.loads</code> which brings me back to square one. I have tried regex like this:</p>
<pre><code>double_quotes_in_json = re.compile(r'(?<=:)(\s*"[^"]*)(")([^"]*)(")?(?=[^"]*",|"\s*\})')
def escape_double_quotes(jsn_string, pattern=double_quotes_in_json):
for match in pattern.finditer(jsn_string):
# current pattern only matches 1 instance of either one double quote in JSON value string
# (presumably signifying inches) or 1 instance of phrase wrapped in double quotes
# for something like nicknames
# matches will have either 3 or 4 groups, representing one of the 2 match types described above
groups_matched = len(match.groups())
entire_match = match.group()
if groups_matched == 3:
# we only matched one double quote
subbed_match = pattern.sub('$1\\$2$3', entire_match)
jsn_string = re.sub(entire_match, subbed_match, jsn_string)
elif groups_matched == 4:
# we matched a phrase wrapped in double quotes
subbed_match = pattern.sub('$1\\$2$3\\$4', entire_match)
jsn_string = re.sub(entire_match, subbed_match, jsn_string)
return jsn_string
</code></pre>
<p>And while this seems the most promising, it seems to re-insert the double quotes without the escape chars I have in the sub, while also not subbing back in the first group.(I have tried with and without a raw string in the sub function <code>r</code>) So for the above problem section (below is a substring):</p>
<pre><code> "16263505":{title: "Nosefrida "The Snotsucker" Nasal Aspirator"
</code></pre>
<p>The pattern doesn't sub group 1 back in and for some reason subs in a single quote (below is a substring of the failed regex processing):</p>
<pre><code>"16263505":{title: "The Snotsucker"' Nasal Aspirator"
</code></pre>
<p>Either way <code>json.loads</code> complains about the unescaped <code>"</code>.</p>
<p>Edit 1:
My regex can pull out the unescaped quotes but subbing it back in isn't behaving as expected, I am probably doing something stupid here and could use a fresh set of eyes.</p>
<p>example output of my function with print statements:</p>
<pre><code>low_inventory = response.xpath(
'//script[contains(., "islistEligibility") or contains(., "ishlistEligibility")]/text()'
).re_first(r'(?s)(?<=registryWislistEligibilityMap)(?:\s*=\s*)(\{.+\})')
In [453]: for m in double_quotes_in_json.finditer(low_inventory):
...: groups_matched = len(m.groups())
...: print('groups: ', m.groups())
...: entire_match = m.group()
...: print('entire match: ', m.group())
...: if groups_matched == 3:
...: # we only matched a single double quote
...: subbed_match = double_quotes_in_json.sub(r'$1\\$2$3', entire_match)
...: print('subbed3: ', subbed_match)
...: jsn_string = re.sub(entire_match, subbed_match, jsn_string)
...: elif groups_matched == 4:
...: subbed_match = double_quotes_in_json.sub(r'$1\\$2$3\\\$4', entire_match)
...: print('subbed4: ', subbed_match)
...: jsn_string = re.sub(entire_match, subbed_match, jsn_string)
...: print(jsn_string)
...:
groups: (' "Nosefrida ', '"', 'The Snotsucker', '"')
entire match: "Nosefrida "The Snotsucker"
subbed4: "Nosefrida "The Snotsucker"
{ "16241885":{"title": "Nosefrida Fridababy Windi Gas &amp; Colic Relief", "isIneligible": false, "isDiscontinued": false, "isLowInventory": false, "isAllowed": true}, "8650356":{"title": "Babyganics Face- Hand &amp; Baby Wipes- Fragrance Free- 100 Count", "isIneligible": false, "isDiscontinued": false, "isLowInventory": false, "isAllowed": true}, "16249889":{"title": "Nosefrida Nasal Aspirator Replacement Filters", "isIneligible": false, "isDiscontinued": false, "isLowInventory": false, "isAllowed": true}, "8650355":{"title": "Babyganics Face- Hand &amp; Baby Wipes- Fragrance Free- 40 Count", "isIneligible": false, "isDiscontinued": false, "isLowInventory": false, "isAllowed": true}, "15490928":{"title": "BabyGanics Newborn Ultra Absorbent Jumbo Size Diapers - 36 Count", "isIneligible": false, "isDiscontinued": false, "isLowInventory": false, "isAllowed": true}, "14712536":{"title": "Marvel Superhero Bandages", "isIneligible": false, "isDiscontinued": false, "isLowInventory": false, "isAllowed": true}, "16263505":{"title": "The Snotsucker"' Nasal Aspirator", "isIneligible": false, "isDiscontinued": false, "isLowInventory": false, "isAllowed": true}, "14848093":{"title": "Zarbee's Children's Cough Syrup - Grape", "isIneligible": false, "isDiscontinued": false, "isLowInventory": false, "isAllowed": true} }
</code></pre>
| -2
|
2016-09-07T09:34:42Z
| 39,374,851
|
<p>for some reason, using pythons builtin replace function achieved the desired result whereas re.sub did not properly escape the double quotes. (this was with using groups references in a raw string with a single escape or a regular string with double escapes). Either way, here is the working function. If someone has some insight as to why using replace works over re.sub I would be very interested into why this is.</p>
<p>(old code commented out)</p>
<pre><code>double_quotes_in_json = re.compile(r'(?<=:)(\s*")([^"]*)(")([^"]*)(")?(?=[^"]*",|"\s*\})')
def escape_double_quotes(jsn_string, pattern=double_quotes_in_json):
for match in pattern.finditer(jsn_string):
# current pattern only matches 1 instance of either one double quote in JSON value string
# (presumably signifying inches) or 1 instance of phrase wrapped in double quotes
# for something like nicknames
# matches will have either 3 or 4 groups, representing one of the 2 match types described above
num_groups_matched = len(match.groups())
groups = match.groups()
entire_match = match.group()
print('groups: ', match.groups())
print('entire: ', entire_match)
if num_groups_matched == 4:
# we only matched one double quote
# subbed_match = pattern.sub('$1$2\\$3$4', entire_match)
# jsn_string = re.sub(entire_match, subbed_match, jsn_string)
target = ''.join(groups[1:4])
replaced = target.replace('"', '\\"')
print(replaced)
jsn_string = jsn_string.replace(target, replaced)
elif num_groups_matched == 5:
# we matched a phrase wrapped in double quotes
# subbed_match = pattern.sub('$1$2\\$3$4\\$5', entire_match)
# jsn_string = re.sub(entire_match, subbed_match, jsn_string)
target = ''.join(groups[1:])
replaced = target.replace('"', '\\"')
print(replaced)
jsn_string = jsn_string.replace(target, replaced)
return jsn_string
</code></pre>
<p>Edit #1 (AKA: after some sleep approach):</p>
<pre><code>double_quotes_in_title_attr = re.compile(
r'(?<="title":)(?:\s*")(?P<value>.+?)(?=",\s*"\w+":|"\s*\})'
)
def escape_double_quotes_in_title(jsn_string, pattern=double_quotes_in_title_attr):
for match in pattern.finditer(jsn_string):
target = match.group('value')
replaced = target.replace('"', '\\"')
jsn_string = jsn_string.replace(target, replaced)
return jsn_string
# use this first to properly quote keys so the above pattern will match
unquoted_key_pattern = re.compile(r'(?!")(\'?(?P<key>\w+)\'?)(?=:\s*(?:"|false|true|\d|\[|\{))')
def fix_json_keys(jsn, pattern=unquoted_key_pattern):
return pattern.sub(r'"\g<key>"', jsn)
</code></pre>
<p>Thanks for the help @deceze.</p>
| 0
|
2016-09-07T16:13:19Z
|
[
"python",
"json",
"regex",
"escaping"
] |
Appending or Adding Rows in Pandas Dataframe
| 39,366,558
|
<p>In the following DataFrame I would like to add rows if the count of values in the column A is less than 10. </p>
<p>For eg., in the following Table column A group 60 appears 12 times, however gorup 61 appears 9 times. I would like to add a row after last record of group 61 and copy the value in column B,C,D from the corresponding values group 60. Similar operation for group 62 and so on. </p>
<pre><code> A B C D
0 60 0.235 4 7.86
1 60 1.235 5 8.86
2 60 2.235 6 9.86
3 60 3.235 7 10.86
4 60 4.235 8 11.86
5 60 5.235 9 12.86
6 60 6.235 10 13.86
7 60 7.235 11 14.86
8 60 8.235 12 15.86
9 60 9.235 13 16.86
10 60 10.235 14 17.86
11 60 11.235 15 18.86
12 61 12.235 16 19.86
13 61 13.235 17 20.86
14 61 14.235 18 21.86
15 61 15.235 19 22.86
16 61 16.235 20 23.86
17 61 17.235 21 24.86
18 61 18.235 22 25.86
19 61 19.235 23 26.86
20 61 20.235 24 27.86
21 62 20.235 24 28.86
22 62 20.235 24 29.86
23 62 20.235 24 30.86
24 62 20.235 24 31.86
25 62 20.235 24 32.86
</code></pre>
| 1
|
2016-09-07T09:47:38Z
| 39,367,302
|
<p>You can use:</p>
<pre><code>#cumulative count per group
df['G'] = df.groupby('A').cumcount()
df = df.groupby(['A','G'])
.first() #agregate first
.unstack() #reshape DataFrame
.ffill() #same as fillna(method='ffill')
.stack() #get original shape
.reset_index(drop=True, level=1) #remove level G in index
.reset_index()
print (df)
</code></pre>
<pre><code> A B C D
0 60 0.235 4.0 7.86
1 60 1.235 5.0 8.86
2 60 2.235 6.0 9.86
3 60 3.235 7.0 10.86
4 60 4.235 8.0 11.86
5 60 5.235 9.0 12.86
6 60 6.235 10.0 13.86
7 60 7.235 11.0 14.86
8 60 8.235 12.0 15.86
9 60 9.235 13.0 16.86
10 60 10.235 14.0 17.86
11 60 11.235 15.0 18.86
12 61 12.235 16.0 19.86
13 61 13.235 17.0 20.86
14 61 14.235 18.0 21.86
15 61 15.235 19.0 22.86
16 61 16.235 20.0 23.86
17 61 17.235 21.0 24.86
18 61 18.235 22.0 25.86
19 61 19.235 23.0 26.86
20 61 20.235 24.0 27.86
21 61 9.235 13.0 16.86
22 61 10.235 14.0 17.86
23 61 11.235 15.0 18.86
24 62 20.235 24.0 28.86
25 62 20.235 24.0 29.86
26 62 20.235 24.0 30.86
27 62 20.235 24.0 31.86
28 62 20.235 24.0 32.86
29 62 17.235 21.0 24.86
30 62 18.235 22.0 25.86
31 62 19.235 23.0 26.86
32 62 20.235 24.0 27.86
33 62 9.235 13.0 16.86
34 62 10.235 14.0 17.86
35 62 11.235 15.0 18.86
</code></pre>
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p>
<pre><code>df['G'] = df.groupby('A').cumcount()
df = df.pivot_table(index='A', columns='G')
.ffill()
.stack()
.reset_index(drop=True, level=1)
.reset_index()
print (df)
</code></pre>
<pre><code> A B C D
0 60 0.235 4.0 7.86
1 60 1.235 5.0 8.86
2 60 2.235 6.0 9.86
3 60 3.235 7.0 10.86
4 60 4.235 8.0 11.86
5 60 5.235 9.0 12.86
6 60 6.235 10.0 13.86
7 60 7.235 11.0 14.86
8 60 8.235 12.0 15.86
9 60 9.235 13.0 16.86
10 60 10.235 14.0 17.86
11 60 11.235 15.0 18.86
12 61 12.235 16.0 19.86
13 61 13.235 17.0 20.86
14 61 14.235 18.0 21.86
15 61 15.235 19.0 22.86
16 61 16.235 20.0 23.86
17 61 17.235 21.0 24.86
18 61 18.235 22.0 25.86
19 61 19.235 23.0 26.86
20 61 20.235 24.0 27.86
21 61 9.235 13.0 16.86
22 61 10.235 14.0 17.86
23 61 11.235 15.0 18.86
24 62 20.235 24.0 28.86
25 62 20.235 24.0 29.86
26 62 20.235 24.0 30.86
27 62 20.235 24.0 31.86
28 62 20.235 24.0 32.86
29 62 17.235 21.0 24.86
30 62 18.235 22.0 25.86
31 62 19.235 23.0 26.86
32 62 20.235 24.0 27.86
33 62 9.235 13.0 16.86
34 62 10.235 14.0 17.86
35 62 11.235 15.0 18.86
</code></pre>
| 2
|
2016-09-07T10:23:05Z
|
[
"python",
"csv",
"pandas",
"append",
"pivot-table"
] |
Using AutoPep8 in pydev
| 39,366,681
|
<p>I'm trying to use autopep8.py as the code formatter for pydev but I don't seem to be able to supply the parameters correctly as the output isn't as I would expect. </p>
<p>I need to be able to supply two parameters <code>-a --max-line-length 100</code> but for some reason the formatter appears to be ignoring the line length option. Am I doing something wrong?</p>
<p><a href="http://i.stack.imgur.com/WsLf7.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/WsLf7.jpg" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/st3bH.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/st3bH.jpg" alt="enter image description here"></a></p>
| 0
|
2016-09-07T09:53:22Z
| 39,416,546
|
<p>Well, I'm specifying the following settings and it works for me:</p>
<pre><code>-a -a --max-line-length=100 --ignore=E309
</code></pre>
<p>So, I guess the problem in your case is missing the equals char after the <code>--max-line-length</code>.</p>
| 1
|
2016-09-09T17:05:51Z
|
[
"python",
"pydev",
"code-formatting",
"autopep8"
] |
How can I get a similar summary of a Pandas dataframe as in R?
| 39,366,878
|
<p>Different scales allow different types of operations. I would like to specify the scale of a column in a dataframe <code>df</code>. Then, <code>df.describe()</code> should take this into account.</p>
<h2>Examples</h2>
<ul>
<li><strong>Nominal scale</strong>: A nominal scale only allows to check for equivalence. Examples for this are sex, names, city names. You can basically only count how often they appear and give the most common ones (the mode).</li>
<li><strong>Ordinal scale</strong>: You can order, but not say how far one is away from another. Cloth sizes are one example. You can calculate the median / min / max for this scale.</li>
<li><strong>Quantitative scales</strong>: You can calculate the mean, standard deviation, quantiles for those scales.</li>
</ul>
<h2>Code example</h2>
<pre><code>import pandas as pd
import pandas.rpy.common as rcom
df = rcom.load_data('mtcars')
print(df.describe())
</code></pre>
<p>gives</p>
<pre><code> mpg cyl disp hp drat wt \
count 32.000000 32.000000 32.000000 32.000000 32.000000 32.000000
mean 20.090625 6.187500 230.721875 146.687500 3.596563 3.217250
std 6.026948 1.785922 123.938694 68.562868 0.534679 0.978457
min 10.400000 4.000000 71.100000 52.000000 2.760000 1.513000
25% 15.425000 4.000000 120.825000 96.500000 3.080000 2.581250
50% 19.200000 6.000000 196.300000 123.000000 3.695000 3.325000
75% 22.800000 8.000000 326.000000 180.000000 3.920000 3.610000
max 33.900000 8.000000 472.000000 335.000000 4.930000 5.424000
qsec vs am gear carb
count 32.000000 32.000000 32.000000 32.000000 32.0000
mean 17.848750 0.437500 0.406250 3.687500 2.8125
std 1.786943 0.504016 0.498991 0.737804 1.6152
min 14.500000 0.000000 0.000000 3.000000 1.0000
25% 16.892500 0.000000 0.000000 3.000000 2.0000
50% 17.710000 0.000000 0.000000 4.000000 2.0000
75% 18.900000 1.000000 1.000000 4.000000 4.0000
max 22.900000 1.000000 1.000000 5.000000 8.0000
</code></pre>
<p>This is not good as <code>vs</code> is a binary variable which indicates if the car has a v-engine or a straight engine (<a href="http://stackoverflow.com/a/18617340/562769">source</a>). Hence the feature is of nominal scale. Hence min / max / std / mean are not applicable. It should rather be counted how often 0 and 1 appear.</p>
<p>In R, you can do the following:</p>
<pre><code>mtcars$vs = factor(mtcars$vs, levels=c(0, 1), labels=c("straight engine", "V-Engine"))
mtcars$am = factor(mtcars$am, levels=c(0, 1), labels=c("Automatic", "Manual"))
mtcars$gear = factor(mtcars$gear)
mtcars$carb = factor(mtcars$carb)
summary(mtcars)
</code></pre>
<p>and get</p>
<pre><code> mpg cyl disp hp drat
Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0 Min. :2.760
1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5 1st Qu.:3.080
Median :19.20 Median :6.000 Median :196.3 Median :123.0 Median :3.695
Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7 Mean :3.597
3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0 3rd Qu.:3.920
Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0 Max. :4.930
wt qsec vs am gear carb
Min. :1.513 Min. :14.50 straight engine:18 Automatic:19 3:15 1: 7
1st Qu.:2.581 1st Qu.:16.89 V-Engine :14 Manual :13 4:12 2:10
Median :3.325 Median :17.71 5: 5 3: 3
Mean :3.217 Mean :17.85 4:10
3rd Qu.:3.610 3rd Qu.:18.90 6: 1
Max. :5.424 Max. :22.90 8: 1
</code></pre>
<p>Is something similar also possible with Pandas?</p>
<p>I tried</p>
<pre><code>df["vs"] = df["vs"].astype('category')
</code></pre>
<p>But this makes <code>"vs"</code> disappear from the description.</p>
| 2
|
2016-09-07T10:03:26Z
| 39,370,071
|
<p>You could have something like:</p>
<pre><code>def summary_lookalike(frame):
frame.index = frame.index.map(str)
return (frame.astype(str).apply(lambda x: frame.index.values + ': ' + x))
def descriptive_stats(df1, df2):
df2 = df2.apply(lambda x: x.value_counts())
df1, df2 = summary_lookalike(df1), summary_lookalike(df2)
df2 = df2[df2.apply(lambda x: ~x.str.contains('nan'))].fillna('')
return pd.concat([df1.reset_index(drop=True), df2.reset_index(drop=True)], axis=1)
</code></pre>
<p>Choosing Ordinal and Quantitative scales of data:</p>
<pre><code>df_describe = df[df.columns.difference(['vs', 'am', 'gear', 'carb'])].describe()
</code></pre>
<p>Choosing Nominal scales of data:</p>
<pre><code>df_nominal = df.drop(df_describe.columns, axis=1)
</code></pre>
<p>Performing label replacement:</p>
<pre><code>df = pd.DataFrame(descriptive_stats(df_describe, df_nominal))
df['vs'] = df['vs'].str.replace('0.0', 'straight engine').str.replace('1.0', 'V-Engine')
df['am'] = df['am'].str.replace('0.0', 'Automatic').str.replace('1.0', 'Manual')
</code></pre>
<p>Result:</p>
<pre><code>df
cyl disp drat \
0 count: 32.0 count: 32.0 count: 32.0
1 mean: 6.1875 mean: 230.721875 mean: 3.5965625
2 std: 1.78592164695 std: 123.938693831 std: 0.534678736071
3 min: 4.0 min: 71.1 min: 2.76
4 25%: 4.0 25%: 120.825 25%: 3.08
5 50%: 6.0 50%: 196.3 50%: 3.695
6 75%: 8.0 75%: 326.0 75%: 3.92
7 max: 8.0 max: 472.0 max: 4.93
hp mpg qsec \
0 count: 32.0 count: 32.0 count: 32.0
1 mean: 146.6875 mean: 20.090625 mean: 17.84875
2 std: 68.5628684893 std: 6.02694805209 std: 1.7869432361
3 min: 52.0 min: 10.4 min: 14.5
4 25%: 96.5 25%: 15.425 25%: 16.8925
5 50%: 123.0 50%: 19.2 50%: 17.71
6 75%: 180.0 75%: 22.8 75%: 18.9
7 max: 335.0 max: 33.9 max: 22.9
wt vs am gear \
0 count: 32.0 straight engine: 18.0 Automatic: 19.0
1 mean: 3.21725 V-Engine: 14.0 Manual: 13.0
2 std: 0.97845744299
3 min: 1.513 3.0: 15.0
4 25%: 2.58125 4.0: 12.0
5 50%: 3.325 5.0: 5.0
6 75%: 3.61
7 max: 5.424
carb
0
1 1.0: 7.0
2 2.0: 10.0
3 3.0: 3.0
4 4.0: 10.0
5
6 6.0: 1.0
7 8.0: 1.0
</code></pre>
<p>Timing Constraints:</p>
<pre><code>%timeit descriptive_stats(df_describe, df_nominal)
100 loops, best of 3: 12.6 ms per loop
</code></pre>
| 0
|
2016-09-07T12:32:46Z
|
[
"python",
"pandas",
"dataframe"
] |
How to create domain ontology lexicon by getting all the classes name attribute relations and save it in the lists
| 39,366,879
|
<p>I am new to the ontology and semantic analysis. currently, I have one public ontology source which was from BBC website. the source is in " .ttl " format.
I was also to load the source in Jena by using eclipse. However, i was a little lost when i see the code. </p>
<p>Here is some example:</p>
<pre><code><http://www.bbc.co.uk/ontologies/bbc/Mobile>
a <http://www.bbc.co.uk/ontologies/bbc/Platform> ;
<http://www.w3.org/2000/01/rdf-schema#comment>
"Represents the web documents designed for a smaller, mobile screen."@en-gb ;
<http://www.w3.org/2000/01/rdf-schema#isDefinedBy>
<http://www.bbc.co.uk/ontologies/bbc> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"Mobile"@en-gb .
<http://www.bbc.co.uk/ontologies/bbc/primaryContent>
a <http://www.w3.org/2002/07/owl#ObjectProperty> ;
<http://www.w3.org/2000/01/rdf-schema#comment>
"Represents the fact that a web document has as primary content the creative work (e.g., a news story about Tom Daley is the primary content of a webpage)."@en-gb ;
<http://www.w3.org/2000/01/rdf-schema#domain>
<http://www.bbc.co.uk/ontologies/bbc/WebDocument> ;
<http://www.w3.org/2000/01/rdf-schema#isDefinedBy>
<http://www.bbc.co.uk/ontologies/bbc> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"primaryContent"@en-gb ;
<http://www.w3.org/2000/01/rdf-schema#range>
<http://www.bbc.co.uk/ontologies/creativework/CreativeWork> ;
<http://www.w3.org/2002/07/owl#inverseOf>
<http://www.bbc.co.uk/ontologies/bbc/primaryContentOf> .
</code></pre>
<p>So how can I getting all the classes name attribute relations and save it in the lists??
Is it possible to do it in Python?? As I am not sure hoe rdflib in python can be use</p>
| 2
|
2016-09-07T10:03:26Z
| 39,570,430
|
<pre><code>for subj, pred, obj in g:
subname = subj.split("/")[-1]
</code></pre>
<p>This way you can get the name of the subject.</p>
| 1
|
2016-09-19T10:04:12Z
|
[
"python",
"eclipse",
"jena",
"ontology",
"apache-jena"
] |
Why /usr/local/bin is not recognisable in my C++ program?
| 39,366,943
|
<p>My C++ code:</p>
<pre><code>int main(int argc, const char * argv[])
{
system("python test.py");
return 0;
}
</code></pre>
<p>I have a program <code>foo</code> in /usr/local/bin, and I can just type <code>foo</code> in Unix console and it starts.</p>
<p>The following Python script (test.py) works:</p>
<pre><code>from subprocess import call
call(["/usr/local/bin/foo"])
</code></pre>
<p>This one doesn't (with a "command not found" error):</p>
<pre><code>from subprocess import call
call(["foo"])
</code></pre>
<p>Why is my Python script, when executed from C++, not able to call the program directly?</p>
<p><strong>EDIT:</strong></p>
<p>I'm on Mac OSX. I suspect this has something to do with the folder <code>/usr/local/bin</code> not added by the C++ executable or something like that.</p>
<p><strong>EDIT:</strong></p>
<pre><code> which kallisto
/usr/local/bin/kallisto
cat test.py
from subprocess import call
call(["kallisto"])
python test.py
kallisto 0.43.0
In my C++ run:
Traceback (most recent call last):
File "/Users/tedwong/Sources/QA/test.py", line 2, in <module>
call(["kallisto"])
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
</code></pre>
| 3
|
2016-09-07T10:06:26Z
| 39,367,578
|
<p>Thanks to @ilent2, his answer solved my problem. I was using an IDE to run the C++ code and never realised that I had to tell the IDE my paths. When I ran the same program directly in the console, it worked.</p>
| 3
|
2016-09-07T10:36:01Z
|
[
"python",
"c++"
] |
NetworkX - path around a node
| 39,367,036
|
<p>I use <a href="http://networkx.readthedocs.io/en/latest/" rel="nofollow">NetworkX</a> to create the following graph.</p>
<p><a href="http://i.stack.imgur.com/C69Jr.png" rel="nofollow"><img src="http://i.stack.imgur.com/C69Jr.png" alt="Networkx graph"></a></p>
<p>The graph is created using:</p>
<pre><code>G = nx.grid_2d_graph(4,3)
</code></pre>
<p>After that two nodes are modified with respect to their positions (just to explain the figure, not necessary for the answer).</p>
<p>Using the following code:</p>
<pre><code>G.neighbors((1, 1))
</code></pre>
<p>outputs:</p>
<pre><code>[(0, 1), (1, 2), (1, 0), (2, 1)]
</code></pre>
<p>What I need in addition are the points:</p>
<pre><code>[(0, 2), (2, 2), (2, 0), (0, 0)]
</code></pre>
<p>This would make up a "loop" around (1, 1) containing all nodes in that "loop". Since I dont't know the correct naming in terms of graphs I have a hard time searching after what I'm looking for.</p>
<p><strong>EDIT:</strong></p>
<p>After being inspired by @orestiss and fiddling around I came up with this.</p>
<pre><code>l = list()
center = (1, 1)
for neighb in G.neighbors(center):
others = [n for n in G.neighbors(center) if n != neighb]
for other in others:
l.append([n for n in nx.common_neighbors(G, neighb, other) if n != center])
l.append([neighb])
lf = list(set([item for sublist in l for item in sublist]))
</code></pre>
<p>With that I get all nodes which are in the cycle around <em>center</em>, except <em>center</em> itself.
This works also for boundary nodes.</p>
| 4
|
2016-09-07T10:11:17Z
| 39,367,790
|
<p>I believe that in this specific case would suffice to find which neighbours your neighbours have in common. </p>
<p>the code would be : </p>
<pre><code>in_loop = set()
root = (1,1)
for neighb in G.neighbors(root):
others = [n for n in G.neighbors((1,1)) if n != neighb]
for other in others:
if neighb in [x for x in G.neighbors(other) if x != root]:
in_loop.add(neighb)
break
print in_loop
</code></pre>
| 1
|
2016-09-07T10:46:23Z
|
[
"python",
"networkx"
] |
select certain monitor for going fullscreen with gtk
| 39,367,246
|
<p>I intend to change the monitor where I show a fullscreen window.
This is especially interesting when having a projector hooked up.</p>
<p>I've tried to use <a href="https://developer.gnome.org/gtk3/stable/GtkWindow.html#gtk-window-fullscreen-on-monitor" rel="nofollow"><code>fullscreen_on_monitor</code></a> but that doesn't produce any visible changes.</p>
<p>Here is a non-working example:</p>
<pre><code>#!/usr/bin/env python
import sys
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gdk
w = Gtk.Window()
screen = Gdk.Screen.get_default()
print ("Montors: %d" % screen.get_n_monitors())
if len(sys.argv) > 1:
n = int(sys.argv[1])
else:
n = 0
l = Gtk.Button(label="Hello, %d monitors!" % screen.get_n_monitors())
w.add(l)
w.show_all()
w.fullscreen_on_monitor(screen, n)
l.connect("clicked", Gtk.main_quit)
w.connect("destroy", Gtk.main_quit)
Gtk.main()
</code></pre>
<p>I get to see the window on the very same monitor (out of 3), regardless of the value I provide.</p>
<p>My question is: how do I make the fullscreen window appear on a different monitor?</p>
| 4
|
2016-09-07T10:20:38Z
| 39,386,341
|
<p>The problem seems to be that Gtk just ignores the monitor number, it will always fullscreen the window on the monitor on which the window currently is positioned. This sucks, but we can use that to make it work the way we want to.</p>
<p>But first some theory about multiple monitors, they aren't actually separate monitors for your pc. It considers them to collectively form one screen which share the same global origin. On that global screen each monitor has a origin relative to the global origin, just like windows. </p>
<p>Because we know that Gtk will always fullscreen on the monitor on which the window is we can simply move the window to the origin of the monitor using <code>window.move(x,y)</code> and then call <code>window.fullscreen()</code>. </p>
<p>(The <code>move</code> function will move the window to a position <code>(x,y)</code> relative to it's parent, which in the case of the main window is the global screen.)</p>
<p>Combining all this we get this, which works perfectly on Windows 10:</p>
<pre><code>def fullscreen_at_monitor(window, n):
screen = Gdk.Screen.get_default()
monitor_n_geo = screen.get_monitor_geometry(n)
x = monitor_n_geo.x
y = monitor_n_geo.y
window.move(x,y)
window.fullscreen()
</code></pre>
| 3
|
2016-09-08T08:41:31Z
|
[
"python",
"gtk",
"fullscreen",
"gtk3"
] |
Using named arguments as variables
| 39,367,278
|
<p>I am using django but I think this question primarily belongs to Python itself.</p>
<p>I have something like:</p>
<pre><code>def get(self, request, arg, *args, **kwargs):
if kwargs['m0'] == 'death':
if kwargs['m1'] == 'year':
result = Artists.objects.filter(death_year=arg)
elif kwargs['m1'] == 'month':
result = Artists.objects.filter(death_month=arg)
elif kwargs['m1'] == 'day':
result = Artists.objects.filter(death_day=arg)
elif kwargs['m0'] == 'birth':
if kwargs['m1'] == 'year':
result = Artists.objects.filter(birth_year=arg)
elif kwargs['m1'] == 'month':
result = Artists.objects.filter(birth_month=arg)
elif kwargs['m1'] == 'day':
result = Artists.objects.filter(birthh_day=arg)
</code></pre>
<p>Where <code>death_year</code> is a named argument that is a field in my model <code>Artists</code> representing a column in my database. The variables 'm0' and <code>m1</code> are passed from the <code>urlconf</code> to my get function (it is actually a <code>get</code> method in my view class).
Can I control the name value of the variable <code>death_year</code> without using an if else if chain (i.e. make it <code>death_month</code> or <code>birth_year</code>)? Since I have many choices, I will have to use a ridiculously very long conditional chain that leads to this same line but with just a different named argument.</p>
<p>I strongly doubt that you should understand this whole problem to answer the question. The original question is simple: Can I use a named argument and its corresponding value as variables in Python?</p>
| 1
|
2016-09-07T10:21:51Z
| 39,367,848
|
<p>From what I can make out you can construct the key and then pass in an arg to construct the dict, then include that in the filter</p>
<pre><code>key = '%s_%s' % (kwargs['m0'], kwargs['m1'])
result = Artists.objects.filter(**{key: arg})
</code></pre>
| 5
|
2016-09-07T10:48:29Z
|
[
"python",
"django"
] |
Using named arguments as variables
| 39,367,278
|
<p>I am using django but I think this question primarily belongs to Python itself.</p>
<p>I have something like:</p>
<pre><code>def get(self, request, arg, *args, **kwargs):
if kwargs['m0'] == 'death':
if kwargs['m1'] == 'year':
result = Artists.objects.filter(death_year=arg)
elif kwargs['m1'] == 'month':
result = Artists.objects.filter(death_month=arg)
elif kwargs['m1'] == 'day':
result = Artists.objects.filter(death_day=arg)
elif kwargs['m0'] == 'birth':
if kwargs['m1'] == 'year':
result = Artists.objects.filter(birth_year=arg)
elif kwargs['m1'] == 'month':
result = Artists.objects.filter(birth_month=arg)
elif kwargs['m1'] == 'day':
result = Artists.objects.filter(birthh_day=arg)
</code></pre>
<p>Where <code>death_year</code> is a named argument that is a field in my model <code>Artists</code> representing a column in my database. The variables 'm0' and <code>m1</code> are passed from the <code>urlconf</code> to my get function (it is actually a <code>get</code> method in my view class).
Can I control the name value of the variable <code>death_year</code> without using an if else if chain (i.e. make it <code>death_month</code> or <code>birth_year</code>)? Since I have many choices, I will have to use a ridiculously very long conditional chain that leads to this same line but with just a different named argument.</p>
<p>I strongly doubt that you should understand this whole problem to answer the question. The original question is simple: Can I use a named argument and its corresponding value as variables in Python?</p>
| 1
|
2016-09-07T10:21:51Z
| 39,371,856
|
<p>The basic and incredibly powerful idea in Python is that you can pass a list of positional arguments without writing <code>args[0], args[1],...</code> and/or a dict of keyword arguments without writing <code>foo=kwargs["foo"], bar=kwargs["bar"],...</code> by using <code>*</code> and <code>**</code> as in <code>func( *args, **kwargs)</code></p>
<p>A function can likewise be written to accept a list of positional args of arbitrary length, and any set of unmatched keyword arguments: <code>def func( a, b, c=0, *args, **kwargs)</code>. (<code>args</code> and <code>kwargs</code> are not reserved words, just conventional variable names)</p>
<p>This example probably shows most of it in operation:</p>
<pre><code>>>> def foo( a, b=0, c=0, *args, **kwargs):
... print( "a,b,c: ", a, b, c)
... print( args)
... print( kwargs)
...
>>> foo( *[1,2,3,4], **{"baz":42} )
a,b,c: 1 2 3
(4,)
{'baz': 42}
>>> foo( 1, b=2, **{"baz":42, "c":3} )
a,b,c: 1 2 3
()
{'baz': 42}
>>> foo( **{"baz":42, "c":3, "a":1, "zork":"?" } )
a,b,c: 1 0 3
()
{'zork': '?', 'baz': 42}
</code></pre>
<p>kwargs is a dict so if you want, you can use <code>kwargs.keys()</code> and all the other <code>dict</code> methods to introspect what the user actually passed and validate, parse, process etc. Django frequently uses <code>kwargs.pop()</code> to allow the fetching of arguments for the current function, while leaving other named arguments to propagate down a possibly deep set of nested function invocations until a routine near the bottom finds an optional keyword argument of its own. </p>
| 1
|
2016-09-07T13:54:36Z
|
[
"python",
"django"
] |
Python SQLAlchemy attribute-events - How to check oldvalue equals NO_VALUE?
| 39,367,329
|
<p>The <a href="http://docs.sqlalchemy.org/en/latest/orm/events.html#attribute-events" rel="nofollow">official documentation</a> of SQLAlchemy states:</p>
<blockquote>
<p>oldvalue â the previous value being replaced. This may also be the
symbol <code>NEVER_SET</code> or <code>NO_VALUE</code>. If the listener is registered with
<code>active_history=True</code>, the previous value of the attribute will be
loaded from the database if the existing value is currently unloaded
or expired.</p>
</blockquote>
<pre><code>from sqlalchemy import event
# standard decorator style
@event.listens_for(SomeClass.some_attribute, 'set')
def receive_set(target, value, oldvalue, initiator):
"listen for the 'set' event"
# ... (event handling logic) .
</code></pre>
<p>My problem is how can I check the old value equals the symbol <code>NO_VALUE</code>?</p>
<p>M use <code>if oldvalue == symbol(NO_VALUE)</code> but it gives me error.</p>
<blockquote>
<p>TypeError: 'module' object is not callable</p>
</blockquote>
| 0
|
2016-09-07T10:24:30Z
| 39,405,614
|
<p>use </p>
<pre><code>from sqlalchemy.orm.base import NO_VALUE
if oldvalue is NO_VALUE:
//login here
</code></pre>
<p>works for me </p>
| 0
|
2016-09-09T07:00:55Z
|
[
"python",
"sqlalchemy",
"flask-sqlalchemy"
] |
Get "TypeError: cannot create mph' When Using sympy.nsolve()
| 39,367,450
|
<p>I am attempting to determine the time, angle and speed that something would have to travel to intersect with a moving ellipse. (I actually want these conditions for the minimum time). Right now I was trying to use Sympy to help with this adventure. The following is the code which I am executing:</p>
<pre><code>import sympy as sp
sp.init_printing()
delta_x, delta_y, t = sp.symbols('delta_x delta_y t', real=True, positive=True)
V, V_s, x_0, y_0, theta_s, theta_t = sp.symbols('V V_s x_0 y_0 theta_s theta_t', real=True)
x, y = sp.symbols('x y', real=True)
EQ1 = sp.Eq(((x-(x_0+V*sp.cos(theta_t)*t))/(delta_x+V*sp.cos(theta_t)*t))**2+((y-(y_0+V*sp.sin(theta_t)*t))/(delta_y+V*sp.sin(theta_t)*t))**2-1, 0)
sx = sp.Eq(x, V_s*sp.cos(theta_s)*t)
sy = sp.Eq(y, V_s*sp.sin(theta_s)*t)
mysubs = [(V,5), (x_0, 10), (y_0, 10), (theta_t, 7*(sp.pi/4)), (delta_x, 0), (delta_y, 0)]
sp.nsolve((EQ1.subs(mysubs), sx.subs(mysubs), sy.subs(mysubs)), (V_s, theta_s, t), (5, 0.0, 1))
</code></pre>
<p>The result of this operation yields:</p>
<pre><code>---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sympy/mpmath/calculus/optimization.py in findroot(ctx, f, x0, solver, tol, verbose, verify, **kwargs)
927 try:
--> 928 fx = f(*x0)
929 multidimensional = isinstance(fx, (list, tuple, ctx.matrix))
<string> in <lambda>(_Dummy_75, _Dummy_76, _Dummy_77)
/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sympy/mpmath/matrices/matrices.py in __init__(self, *args, **kwargs)
300 for j, a in enumerate(row):
--> 301 self[i, j] = convert(a)
302 else:
/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sympy/mpmath/ctx_mp_python.py in convert(ctx, x, strings)
661 return ctx.convert(x._mpmath_(prec, rounding))
--> 662 return ctx._convert_fallback(x, strings)
663
/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sympy/mpmath/ctx_mp.py in _convert_fallback(ctx, x, strings)
613 raise ValueError("can only create mpf from zero-width interval")
--> 614 raise TypeError("cannot create mpf from " + repr(x))
615
TypeError: cannot create mpf from 0.08*(x - 13.535533905932737622)**2 + 0.08*(y - 6.464466094067262378)**2 - 1
</code></pre>
<p>Is this because the system is not constrained enough? There is a family of angles and velocities which could be used to intercept the moving ellipse. This error does not seem to imply this. (Yes, even when I attempt to constrain V_s in this problem the same error appears).</p>
<p>I am using the following versions of things:</p>
<pre><code>| Software | Version |
|----------|-----------|
| python | 3.5.2 |
| sympy | 1.0 |
| mpmath | 0.19 |
</code></pre>
| 1
|
2016-09-07T10:30:22Z
| 39,419,144
|
<p>The variables <code>x</code> and <code>y</code> are still symbolic in the equations. <code>nsolve</code> requires all variables to be specified, and at least as many equations as variables. So you either need to include values for them in <code>mysubs</code>, or else solve for them (but to do that with <code>nsolve</code>, you will need two more equations). </p>
| 0
|
2016-09-09T20:19:23Z
|
[
"python",
"sympy"
] |
Python - How to hide labels and keep legends matplotlib?
| 39,367,481
|
<p>I would like to remove the labels of a pie chart and keep the legends only. Currently, my code has both. Any idea how to remove the labels?</p>
<p>I've tried the code below: </p>
<pre><code>plt.legend(labels, loc="best")
and
labels=None
</code></pre>
<p>Bu didn't work.</p>
<p>My full code is:</p>
<pre><code>plt.pie(percent, # data
explode=explode, # offset parameters
labels=country, # slice labels
colors=colors, # array of colours
autopct='%1.0f%%', # print the values inside the wedges - add % to the values
shadow=True, # enable shadow
startangle=70 # starting angle
)
plt.axis('equal')
plt.title('Top 5 Countries', y=1.05, fontsize=15) #distance from plot and size
plt.legend( loc="best")
plt.tight_layout()
countrypie = "%s_country_pie.png" % pname
plt.savefig(countrypie)
</code></pre>
<p>Thanks for your input</p>
| 0
|
2016-09-07T10:31:39Z
| 39,367,824
|
<p>If I understand your question correctly this should solve it.
Removing the labels from the pie chart creation and adding the labels to the legend - </p>
<pre class="lang-py prettyprint-override"><code>plt.pie(percent, # data
explode=explode, # offset parameters
colors=colors, # array of colours
autopct='%1.0f%%', # print the values inside the wedges - add % to the values
shadow=True, # enable shadow
startangle=70 # starting angle
)
plt.axis('equal')
plt.title('Top 5 Countries', y=1.05, fontsize=15) #distance from plot and size
plt.legend(loc="best", labels=country)
plt.tight_layout()
countrypie = "%s_country_pie.png" % pname
plt.savefig(countrypie)
</code></pre>
| 0
|
2016-09-07T10:47:17Z
|
[
"python",
"matplotlib",
"legend",
"pie-chart"
] |
Python - How to hide labels and keep legends matplotlib?
| 39,367,481
|
<p>I would like to remove the labels of a pie chart and keep the legends only. Currently, my code has both. Any idea how to remove the labels?</p>
<p>I've tried the code below: </p>
<pre><code>plt.legend(labels, loc="best")
and
labels=None
</code></pre>
<p>Bu didn't work.</p>
<p>My full code is:</p>
<pre><code>plt.pie(percent, # data
explode=explode, # offset parameters
labels=country, # slice labels
colors=colors, # array of colours
autopct='%1.0f%%', # print the values inside the wedges - add % to the values
shadow=True, # enable shadow
startangle=70 # starting angle
)
plt.axis('equal')
plt.title('Top 5 Countries', y=1.05, fontsize=15) #distance from plot and size
plt.legend( loc="best")
plt.tight_layout()
countrypie = "%s_country_pie.png" % pname
plt.savefig(countrypie)
</code></pre>
<p>Thanks for your input</p>
| 0
|
2016-09-07T10:31:39Z
| 39,369,353
|
<p>If you alter your code to the following, it should remove the labels and keep the legend:</p>
<pre><code>plt.pie(percent, # data
explode=explode, # offset parameters
labels=None, # OR omit this argument altogether
colors=colors, # array of colours
autopct='%1.0f%%', # print the values inside the wedges - add % to the values
shadow=True, # enable shadow
startangle=70 # starting angle
)
plt.axis('equal')
plt.title('Top 5 Countries', y=1.05, fontsize=15) #distance from plot and size
plt.legend( loc="best", labels=country)
plt.tight_layout()
countrypie = "%s_country_pie.png" % pname
plt.savefig(countrypie)
</code></pre>
| 1
|
2016-09-07T11:58:51Z
|
[
"python",
"matplotlib",
"legend",
"pie-chart"
] |
Django 1.95 template i18n not working
| 39,367,492
|
<p>I am trying to translate the string from English to zh-hans</p>
<p>In the <code>settings.py</code></p>
<pre><code>LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
</code></pre>
<p>I have run the <code>python manage.py makemessages -l zh-hans</code> and <code>python manage.py makemessages -a</code> for many times.</p>
<p>The .po file is simple as following:</p>
<pre><code>msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2016-09-07 09:53+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: blog/views.py:18
msgid "author"
msgstr "ä½è
"
</code></pre>
<p>In the html file:</p>
<pre><code> <div id = "info">
<p>
{% trans "author" %} : {{ blog.author }}
</p>
</div>
</code></pre>
<p>The tag returns "author" instead of Chinese characters.
Also I have tried ugettext in <code>view.py</code></p>
<pre><code>def detail(request, slug):
blog = get_object_or_404(Post, slug=slug)
msg = _("author")
print(msg)
context = {
'blog': blog,
'author': msg,
}
return render(request, 'blog/detail.html', context)
</code></pre>
<p>The msg is still "author".</p>
<p>Using </p>
<pre><code> {% get_current_language as LANGUAGE_CODE %}
{{ LANGUAGE_CODE }}
</code></pre>
<p>The language code is zh-hans.</p>
<p>So what's going wrong here? How to show the translated string in the template? Thank you </p>
| 0
|
2016-09-07T10:31:58Z
| 39,381,282
|
<p>It's a very silly mistake.</p>
<p>Although in the <code>setting.py</code> the Chinese language code can be set as 'zh-hans', to implement the i18n, it should be makemessages -l zh_hans instead of zh-hans.</p>
| 0
|
2016-09-08T01:30:32Z
|
[
"python",
"django",
"internationalization"
] |
Importing modules used in a package in __init__.py
| 39,367,497
|
<p>I have the following directory structure:</p>
<pre><code>funniest/
setup.py
funniest/
__init__.py
ModuleA.py
ModuleB.py
</code></pre>
<pre><code># __init__.py
from numba import jit
from .ModuleA import ClassA
</code></pre>
<pre><code># ModuleA.py
import funniest.ModuleB
class ClassA():
pass
</code></pre>
<pre><code># ModuleB.py
@jit
def f():
pass
</code></pre>
<p>However, when importing the module, I get the error message:</p>
<pre><code>>>> import funniest
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/domi89/Dropbox/Python_Projects/funniest/funniest /__init__.py", line 2, in <module>
from .ModuleA import ClassA
File "/home/domi89/Dropbox/Python_Projects/funniest/funniest /ModuleA.py", line 1, in <module>
import funniest.ModuleB
File "/home/domi89/Dropbox/Python_Projects/funniest/funniest/ModuleB.py", line 1, in <module>
@jit
NameError: name 'jit' is not defined
</code></pre>
<p>I cannot understand why this happends, because when <code>__init__.py</code> get executed first, the first thing it does is importing <code>from numba import jit</code>. So why is <code>jit</code> not defined when it comes to function <code>f</code> in <code>ModuleB</code>? </p>
| 3
|
2016-09-07T10:32:06Z
| 39,367,643
|
<p>The imports you put in <code>funniest/__init__.py</code> are only imported when you do <code>import funniest</code>, not automatically inside submodules. So <code>ModuleB</code> doesn't know about <code>jit</code>.</p>
<p>What you need to do here is to move <code>from numba import jit</code> from <code>__init__.py</code> to <code>ModuleB.py</code>.</p>
| 4
|
2016-09-07T10:39:45Z
|
[
"python"
] |
Importing modules used in a package in __init__.py
| 39,367,497
|
<p>I have the following directory structure:</p>
<pre><code>funniest/
setup.py
funniest/
__init__.py
ModuleA.py
ModuleB.py
</code></pre>
<pre><code># __init__.py
from numba import jit
from .ModuleA import ClassA
</code></pre>
<pre><code># ModuleA.py
import funniest.ModuleB
class ClassA():
pass
</code></pre>
<pre><code># ModuleB.py
@jit
def f():
pass
</code></pre>
<p>However, when importing the module, I get the error message:</p>
<pre><code>>>> import funniest
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/domi89/Dropbox/Python_Projects/funniest/funniest /__init__.py", line 2, in <module>
from .ModuleA import ClassA
File "/home/domi89/Dropbox/Python_Projects/funniest/funniest /ModuleA.py", line 1, in <module>
import funniest.ModuleB
File "/home/domi89/Dropbox/Python_Projects/funniest/funniest/ModuleB.py", line 1, in <module>
@jit
NameError: name 'jit' is not defined
</code></pre>
<p>I cannot understand why this happends, because when <code>__init__.py</code> get executed first, the first thing it does is importing <code>from numba import jit</code>. So why is <code>jit</code> not defined when it comes to function <code>f</code> in <code>ModuleB</code>? </p>
| 3
|
2016-09-07T10:32:06Z
| 39,367,755
|
<p>The name <code>jit</code> is not known inside <code>ModuleB</code>. Python imports doesn't work like C/C++ includes that roll-out the code in place of the <code>import</code>. A new module creates a new namespace with a map inside - a map with functions, classes, etc.</p>
<p>So when you did <code>import funniest</code>, you created new map entry in the current namespace, like: <code>{..., funniest: {}, ...}</code>. By importing <code>funniest</code>, you imported <code>jit</code> and <code>ClassA</code>, so from the place when you imported the <code>funniest</code> module, you have access to such map: <code>funniest: {jit: {..}, ClassA: {...}}</code>.</p>
<p>In <code>ModuleA</code> you imported <code>ModuleB</code>, so in <code>ModuleA</code> you have new variable <code>ModuleB:{...}</code> with content of <code>ModuleB</code>. But here you don't see the <code>funniest</code> map - it is in other level in hierarchy.</p>
<p>And in <code>ModuleB</code>, you don't see <code>funniest</code> and <code>ClassA</code> maps (namespaces - and whatever you like to call it;)).</p>
| 3
|
2016-09-07T10:44:28Z
|
[
"python"
] |
Repeating a for in line loop python
| 39,367,593
|
<p>How would I repeat this (excluding the opening of the file and the setting of the variables)?
this is my code in python3 </p>
<pre><code>file = ('file.csv','r')
count = 0 #counts number of times i was equal to 1
i = 0 #column number
for line in file:
line = line.split(",")
if line[i] == 1:
count = count + 1
i = i+1
</code></pre>
| -4
|
2016-09-07T10:37:00Z
| 39,367,685
|
<p>If I understand the question, try this and adjust for however you want to format. Replace <code>NUM_COLUMNS</code> with the number of times you want it repeating</p>
<pre><code>file = open('file.csv','r')
data = file.readlines()
for i in range(NUM_COLUMNS):
count = 0
for line in data:
line = line.split(",")
if line[i] == ("1"):
count = count + 1
print count
</code></pre>
| 0
|
2016-09-07T10:41:38Z
|
[
"python",
"list",
"python-3.x",
"csv",
"repeat"
] |
Repeating a for in line loop python
| 39,367,593
|
<p>How would I repeat this (excluding the opening of the file and the setting of the variables)?
this is my code in python3 </p>
<pre><code>file = ('file.csv','r')
count = 0 #counts number of times i was equal to 1
i = 0 #column number
for line in file:
line = line.split(",")
if line[i] == 1:
count = count + 1
i = i+1
</code></pre>
| -4
|
2016-09-07T10:37:00Z
| 39,367,779
|
<p>The following function will return the number of fields in the csv file <code>file_name</code> whose value is <code>field_value</code>, which is what I think you are trying to do:</p>
<pre><code>import csv
def get_count(file_name, field_value):
count = 0
with open(file_name) as f:
reader = csv.reader(f)
for row in reader:
count += row.count(field_value)
return count
print(get_count('file.csv', '1'))
</code></pre>
| 0
|
2016-09-07T10:45:49Z
|
[
"python",
"list",
"python-3.x",
"csv",
"repeat"
] |
Save binary image after watershed
| 39,367,655
|
<p>I have problems storing my image after watershed segmentation as a binary image. When I plot the segmentation with cmap=plt.cm.gray it shows a binary image but I don't know how to store the image (without to display it).</p>
<pre><code>import cv2
import numpy as np
from matplotlib import pyplot as plt
from skimage.morphology import watershed
from scipy import ndimage as ndi
from skimage import morphology
from skimage.filters import sobel
from skimage.io import imread, imsave, imshow
import scipy.misc
img = cv2.imread('07.png')
img = cv2.medianBlur(img,5)
b,g,r = cv2.split(img)
elevation_map = sobel(r)
markers = np.zeros_like(r)
markers[s < 140] = 1
markers[s > 200] = 2
segmentation = morphology.watershed(elevation_map, markers)
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(segmentation, cmap=plt.cm.gray, interpolation='nearest')
ax.axis('off')
plt.show()
</code></pre>
| 0
|
2016-09-07T10:40:16Z
| 39,371,049
|
<p>In short, you can save it similarly to how you are displaying it using (see <a href="http://stackoverflow.com/questions/30941350/how-are-images-actually-saved-with-skimage-python">here</a> for reference):</p>
<pre><code>plt.imsave('test.png', segmentation, cmap = plt.cm.gray)
</code></pre>
<p>Note however, that <code>segmentation</code> will consist of two labels, label <code>1</code> and label <code>2</code>. This is because you are setting up</p>
<pre><code>markers[s < 140] = 1
markers[s > 200] = 2
</code></pre>
<p>which leaves a region where <code>markers</code> is zero; those pixels are not treated as markes. The result of running <code>watershed</code> is a label matrix consisting of the marker labels, in your case <code>1</code> and <code>2</code>. When displaying it using your code, you will see a binary image because <code>cmap = plt.cm.gray</code> will scale the image. As the label <code>0</code> does not exist, it will scale label <code>1</code> to value <code>0</code> (i.e. black) and label <code>2</code> to value <code>255</code> (i.e. white) (see <a href="http://stackoverflow.com/questions/12760797/imshowimg-cmap-cm-gray-shows-a-white-for-128-value">here</a> for explanation and example). The same is done when using <code>plt.imsave</code> with <code>cmap = plt.cm.gray</code>. Long story short, if you want to save the image using any other method/library (for example OpenCV), you might need to do something like this:</p>
<pre><code>segmentation[segmentation == 1] == 0
segmentation[segmentation == 2] == 255
segmentation = segmentation.astype(np.uint8)
# e.g. when writing using OpenCV
cv2.imwrite('test.png', segmentation)
</code></pre>
| 1
|
2016-09-07T13:20:07Z
|
[
"python",
"image-segmentation",
"watershed",
"skimage"
] |
How to use Python Matplotlib with OSx and virtualenv?
| 39,367,776
|
<p>I just started learning Python's libraries for data analysis (Numpy, Pandas and Matplotlib) but have already stumbled across my first problem - getting the Matplotlib to work with <code>virtualenv</code>. </p>
<p>When working with Python I always create a new virtual environment, get my desired Python version and libraries/dependancies into this environment. This time, the course required that I use <strong>Python3</strong>, so I installed it via <strong>HomeBrew</strong>.</p>
<p><strong>The challenge:</strong></p>
<ul>
<li>Matplotlib needs to interact with OS</li>
<li>to make this happen it needs the framework build of Python (the system one)</li>
<li>...which is not possible if it's inside of a virtualenv, which makes it use the virtualenv build of Python</li>
</ul>
<p>The workaround that Is supposed to be common is described at <a href="http://matplotlib.org/faq/virtualenv_faq.html" rel="nofollow">this link</a> but I am unsure how to use this (the OSX section). </p>
<p><strong>My understanding of the solution:</strong></p>
<ol>
<li>get Python version that I wish to use, install it system wide, NOT in a virtualenv</li>
<li>create a virtualenv, get dependencies that I need, this creates the virtualenv Python build</li>
<li>somehow <strong>trick the system</strong> into using virtualenv dependancies with system build of Python</li>
<li>this is done with the shell script(?) which seems to modify certain variables in shell/terminal config file(s)</li>
</ol>
<p><strong>Questions:</strong></p>
<ol>
<li>am I correct with the above "explanation to myself"?</li>
<li>what is the correct way to do this? from within the virtualenv, from outside of it...?</li>
<li>after this is done, how do I execute my Python scripts? with my virtualenv activated or not?</li>
</ol>
<p>Many thanks!</p>
| 2
|
2016-09-07T10:45:26Z
| 39,369,009
|
<p>You are almost correct. From personal experience, Matplotlib doesn't require the system Python to run on macOS. </p>
<p>As such, to install and use Matplotlib you can:</p>
<ol>
<li>Create a new virtual env and activate it with <code>source virtualenv/bin/activate</code>.</li>
<li>Install Matplotlib with <code>pip install matplotlib</code>.</li>
<li>Run your script (which imports Matplotlib) with <code>python script.py</code>.</li>
</ol>
<p>If you need more information take a look at the <a href="http://matplotlib.org/users/installing.html" rel="nofollow">Matplotlib documentation for installation</a>. </p>
<p>I also believe that if you download the source files and install it with <code>python setup.py install</code> while inside the virtual env then you can use the modules just the same as if you were to do <code>pip install matplotlib</code>. </p>
| 1
|
2016-09-07T11:44:04Z
|
[
"python",
"osx",
"shell",
"matplotlib",
"virtualenv"
] |
How to save webpages text content as a text file using python
| 39,367,963
|
<p>I did python script:</p>
<pre><code> from string import punctuation
from collections import Counter
import urllib
from stripogram import html2text
myurl = urllib.urlopen("https://www.google.co.in/?gfe_rd=cr&ei=v-PPV5aYHs6L8Qfwwrlg#q=samsung%20j7")
html_string = myurl.read()
text = html2text( html_string )
file = open("/home/nextremer/Final_CF/contentBased/contentCount/hi.txt", "w")
file.write(text)
file.close()
</code></pre>
<p>Using this script I didn't get perfect output only some HTML code.<br>
<li> I want save all webpage text content in a text file.<br>
<li> I used urllib2 or bs4 but I didn't get results.<br>
<li> I don't want output as a html structure.
<li>I want all text data from webpage</p>
| 1
|
2016-09-07T10:54:05Z
| 39,368,155
|
<pre><code> import urllib
urllib.urlretrieve("http://www.example.com/test.html", "test.txt")
</code></pre>
| 0
|
2016-09-07T11:02:49Z
|
[
"python"
] |
How to save webpages text content as a text file using python
| 39,367,963
|
<p>I did python script:</p>
<pre><code> from string import punctuation
from collections import Counter
import urllib
from stripogram import html2text
myurl = urllib.urlopen("https://www.google.co.in/?gfe_rd=cr&ei=v-PPV5aYHs6L8Qfwwrlg#q=samsung%20j7")
html_string = myurl.read()
text = html2text( html_string )
file = open("/home/nextremer/Final_CF/contentBased/contentCount/hi.txt", "w")
file.write(text)
file.close()
</code></pre>
<p>Using this script I didn't get perfect output only some HTML code.<br>
<li> I want save all webpage text content in a text file.<br>
<li> I used urllib2 or bs4 but I didn't get results.<br>
<li> I don't want output as a html structure.
<li>I want all text data from webpage</p>
| 1
|
2016-09-07T10:54:05Z
| 39,368,166
|
<p>What do you mean with "webpage text"?
It seems you don't want the full HTML-File. If you just want the text you see in your browser, that is not so easily solvable, as the parsing of a HTML-document can be very complex, especially with JavaScript-rich pages.
That starts with assessing if a String between "<" and ">" is a regular tag and includes analyzing the CSS-Properties changed by JavaScript-behavior.</p>
<p>That is why people write very big and complex rendering-Engines for Webpage-Browsers.</p>
| 1
|
2016-09-07T11:03:16Z
|
[
"python"
] |
How to save webpages text content as a text file using python
| 39,367,963
|
<p>I did python script:</p>
<pre><code> from string import punctuation
from collections import Counter
import urllib
from stripogram import html2text
myurl = urllib.urlopen("https://www.google.co.in/?gfe_rd=cr&ei=v-PPV5aYHs6L8Qfwwrlg#q=samsung%20j7")
html_string = myurl.read()
text = html2text( html_string )
file = open("/home/nextremer/Final_CF/contentBased/contentCount/hi.txt", "w")
file.write(text)
file.close()
</code></pre>
<p>Using this script I didn't get perfect output only some HTML code.<br>
<li> I want save all webpage text content in a text file.<br>
<li> I used urllib2 or bs4 but I didn't get results.<br>
<li> I don't want output as a html structure.
<li>I want all text data from webpage</p>
| 1
|
2016-09-07T10:54:05Z
| 39,369,122
|
<p>You dont need to write any hard algorithms to extract data from search result. Google has a API to do this.<br>
Here is an example:<br><a href="https://github.com/google/google-api-python-client/blob/master/samples/customsearch/main.py" rel="nofollow">https://github.com/google/google-api-python-client/blob/master/samples/customsearch/main.py</a><br>
But to use it, first you must to register in google for API Key.<br>
All information you can find here:<br> <a href="https://developers.google.com/api-client-library/python/start/get_started" rel="nofollow">https://developers.google.com/api-client-library/python/start/get_started</a></p>
| 0
|
2016-09-07T11:49:01Z
|
[
"python"
] |
SQLAlchemy: undefer column via joinedload technique
| 39,368,018
|
<p>Here is my query.</p>
<pre><code>query = dbsession.query(Parent)\
.options(joinedload(Parent.child))\
.first()
</code></pre>
<p>Model <code>Child</code> is available through <code>Parent.child</code> relationship and has deffered column named 'column'. How to undefer and load that column using query listed above?</p>
| 0
|
2016-09-07T10:56:33Z
| 39,368,314
|
<p>Chain the undefer option through the joined load with</p>
<pre><code>joinedload(Parent.child).undefer('column')
</code></pre>
<p>See <a href="http://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html#loading-along-paths" rel="nofollow">"Loading Along Paths"</a> and the documentation on <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.strategy_options.Load" rel="nofollow">loaders</a>.</p>
<p>Given the following models:</p>
<pre><code>In [3]: class A(Base):
...: __tablename__ = 'a'
...: id = Column(Integer, primary_key=True)
...:
In [4]: class B(Base):
...: __tablename__ = 'b'
...: id = Column(Integer, ForeignKey('a.id'), primary_key=True)
...: value = deferred(Column(Integer))
...: a = relationship('A', backref='bs')
...:
</code></pre>
<p>undeferring <code>value</code></p>
<pre><code>In [21]: print(session.query(A).options(joinedload(A.bs).undefer('value')))
SELECT a.id AS a_id, b_1.value AS b_1_value, b_1.id AS b_1_id
FROM a LEFT OUTER JOIN b AS b_1 ON a.id = b_1.id
</code></pre>
<p>without</p>
<pre><code>In [17]: print(session.query(A).options(joinedload(A.bs)))
SELECT a.id AS a_id, b_1.id AS b_1_id
FROM a LEFT OUTER JOIN b AS b_1 ON a.id = b_1.id
</code></pre>
| 1
|
2016-09-07T11:10:52Z
|
[
"python",
"sqlalchemy"
] |
what went wrong with my get and set properties?
| 39,368,268
|
<p>Please I need help. I code with PyCharm and it keeps showing me unresolved reference 'model'. Parameter 'model' value is not used and getter signature should be (self). Please how do I get around this.</p>
<pre><code>class ProductObject:
def __init__(self, product, brand, car, model, year):
self.product = product
self.brand = brand
self.car = car
self.model = model
self.year = year
def set_product(self, product):
self.product = product.capitalize()
def get_product(self):
return self.product
product = property(get_product, set_product)
def set_brand(self, brand):
self.brand = brand.title()
def get_brand(self):
return self.brand
brand = property(get_brand, set_brand)
def set_car(self, car):
self.car = car.title()
def get_car(self):
return self.car
car = property(get_car, set_car)
def set_model(self):
self.model = model.title()
def get_model(self, model):
return self.model
model = property(get_model, set_model)
def set_year(self):
self.year = year.int()
def get_year(self, year):
return self.year
year = property(get_year, set_year)
</code></pre>
| 0
|
2016-09-07T11:08:23Z
| 39,368,478
|
<p>You need change parameters of methods. Get method needs only <strong>self</strong> and set method need <strong>self</strong> and <strong>model</strong> as parameter.</p>
<pre><code>def set_model(self, model):
self.model = model.title()
def get_model(self):
return self.model
</code></pre>
<p><strong>EDIT</strong>
Inheriting from your class:</p>
<pre><code>class YourSubclass(ProductObject):
#code of your subclass which inherit from ProductObject class
</code></pre>
<p>Module:
if you want create module you should check this <a href="http://stackoverflow.com/questions/3842616/organizing-python-classes-in-modules-and-or-packages">Module structure</a>
Is it nothing more than classes with init.py file. You can then import classes with normal import statements. Here is another link with info about init.py file: <a href="http://stackoverflow.com/questions/1944569/how-do-i-write-good-correct-package-init-py-files">Init.py structure</a></p>
| 0
|
2016-09-07T11:18:48Z
|
[
"python"
] |
Unable to detect face and eye with OpenCV in Python
| 39,368,307
|
<p>This code is to detect face and eyes using webcam but getting this error</p>
<pre><code>Traceback (most recent call last):
File "D:/Acads/7.1 Sem/BTP/FaceDetect-master/6.py", line 28, in <module>
eyes = eyeCascade.detectMultiScale(roi)
NameError: name 'roi' is not defined
</code></pre>
<p>but when i use this code do detect faces and eyes in a image its working properly without any error </p>
<pre><code>import matplotlib
import matplotlib.pyplot as plt
import cv2
import sys
import numpy as np
import os
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyeCascade= cv2.CascadeClassifier('haarcascade_eye.xml')
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
faces = faceCascade.detectMultiScale(frame)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
roi = frame[y:y+h, x:x+w]
eyes = eyeCascade.detectMultiScale(roi)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi,(ex,ey),(ex+ew,ey+eh), 255, 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
</code></pre>
| 0
|
2016-09-07T11:10:26Z
| 39,368,777
|
<p>I think it is just a problem of indentation.</p>
<p><code>roi</code> is out of scope when you go out of the <code>faces</code> loop.</p>
<pre><code>for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
roi = frame[y:y+h, x:x+w]
# eyes detection runs for each face
eyes = eyeCascade.detectMultiScale(roi)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi,(ex,ey),(ex+ew,ey+eh), 255, 2)
</code></pre>
| 2
|
2016-09-07T11:32:14Z
|
[
"python",
"opencv",
"face-detection",
"nameerror",
"eye-detection"
] |
How can I set the value for request.authenticated_userid in pyramid framework of python
| 39,368,342
|
<p>I am getting an error when I try to set the attribute for authenticated_userid as a request parameter. Its actually a nosetest I am using to mock up the request and see the response.</p>
<pre><code>Traceback (most recent call last):
File "/web/core/pulse/wapi/tests/testWapiUtilities_integration.py", line 652, in setUp
setattr(self.request, 'authenticated_userid', self.data['user'].id)
AttributeError: can't set attribute
</code></pre>
<p>Code is as below</p>
<pre><code>@attr(can_split=False)
class logSuspiciousRequestAndRaiseHTTPError(IntegrationTestCase):
def setUp(self):
super(logSuspiciousRequestAndRaiseHTTPError, self).setUp()
from pyramid.request import Request
from pyramid.threadlocal import get_current_registry
request = Request({
'SERVER_PROTOCOL': 'testprotocol',
'SERVER_NAME': 'test server name',
'SERVER_PORT': '80',
})
request.context = TestContext()
request.root = request.context
request.subpath = ['path']
request.traversed = ['traversed']
request.view_name = 'test view name'
request.path_info = 'test info'
request.scheme = 'https'
request.host = 'test.com'
request.registry = get_current_registry()
self.request = request
self.data = {}
self.createDefaultData()
self.request.userAccount = self.data['user'].userAccount
# @unittest.skip('Pre-Demo skip. Need to mock userAccountModel')
@mock.patch('pulse.wapi.wapiUtilities.pyramid.threadlocal.get_current_request')
@mock.patch('pulse.wapi.wapiUtilities.securityLog')
def testHasRequest_raises400AndLogsError(
self, securityLog, get_current_request):
# Arrange
get_current_request.return_value = self.request
with self.assertRaises(exception.HTTPBadRequest):
from pulse.wapi.wapiUtilities import logSuspiciousRequestAndRaiseHTTPError
logSuspiciousRequestAndRaiseHTTPError()
self.assertTrue(securityLog.called)
self.assertTrue(securityLog.return_value.info.called)
</code></pre>
<p>I am creating a dummy request and I am adding attributes to request.</p>
<p>When this method <code>logSuspiciousRequestAndRaiseHTTPError()</code> is called the request is parsed by the method to get user account.</p>
<pre><code>userAccountID=authenticated_userid(self.request)
</code></pre>
<p>This returns <code>None</code> since the request doesn't have an attribute <code>self.request.authenticated_userid</code></p>
<p>Please let me know if you need any additional information.</p>
| 2
|
2016-09-07T11:12:14Z
| 39,420,596
|
<p><code>authenticated_userid</code> is reified attribute set by authentication framework.</p>
<p>See <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/quick_tutorial/authentication.html" rel="nofollow">Logins with authentication for basic information</a>.</p>
<p>Please include more code how you set up your request, as in its current form the question does not have details to give accurate answer.</p>
| 0
|
2016-09-09T22:36:52Z
|
[
"python",
"pyramid"
] |
How can I set the value for request.authenticated_userid in pyramid framework of python
| 39,368,342
|
<p>I am getting an error when I try to set the attribute for authenticated_userid as a request parameter. Its actually a nosetest I am using to mock up the request and see the response.</p>
<pre><code>Traceback (most recent call last):
File "/web/core/pulse/wapi/tests/testWapiUtilities_integration.py", line 652, in setUp
setattr(self.request, 'authenticated_userid', self.data['user'].id)
AttributeError: can't set attribute
</code></pre>
<p>Code is as below</p>
<pre><code>@attr(can_split=False)
class logSuspiciousRequestAndRaiseHTTPError(IntegrationTestCase):
def setUp(self):
super(logSuspiciousRequestAndRaiseHTTPError, self).setUp()
from pyramid.request import Request
from pyramid.threadlocal import get_current_registry
request = Request({
'SERVER_PROTOCOL': 'testprotocol',
'SERVER_NAME': 'test server name',
'SERVER_PORT': '80',
})
request.context = TestContext()
request.root = request.context
request.subpath = ['path']
request.traversed = ['traversed']
request.view_name = 'test view name'
request.path_info = 'test info'
request.scheme = 'https'
request.host = 'test.com'
request.registry = get_current_registry()
self.request = request
self.data = {}
self.createDefaultData()
self.request.userAccount = self.data['user'].userAccount
# @unittest.skip('Pre-Demo skip. Need to mock userAccountModel')
@mock.patch('pulse.wapi.wapiUtilities.pyramid.threadlocal.get_current_request')
@mock.patch('pulse.wapi.wapiUtilities.securityLog')
def testHasRequest_raises400AndLogsError(
self, securityLog, get_current_request):
# Arrange
get_current_request.return_value = self.request
with self.assertRaises(exception.HTTPBadRequest):
from pulse.wapi.wapiUtilities import logSuspiciousRequestAndRaiseHTTPError
logSuspiciousRequestAndRaiseHTTPError()
self.assertTrue(securityLog.called)
self.assertTrue(securityLog.return_value.info.called)
</code></pre>
<p>I am creating a dummy request and I am adding attributes to request.</p>
<p>When this method <code>logSuspiciousRequestAndRaiseHTTPError()</code> is called the request is parsed by the method to get user account.</p>
<pre><code>userAccountID=authenticated_userid(self.request)
</code></pre>
<p>This returns <code>None</code> since the request doesn't have an attribute <code>self.request.authenticated_userid</code></p>
<p>Please let me know if you need any additional information.</p>
| 2
|
2016-09-07T11:12:14Z
| 39,424,366
|
<p>Finally I got the solution.</p>
<p>I added <code>self.config = testing.setUp()</code></p>
<pre><code>self.config.testing_securitypolicy(
userid=self.data['user'].userAccount.id, permissive=True
)
</code></pre>
<p>Added the userAccountId as mock up value for testing security policy.</p>
<pre><code>@attr(can_split=False)
class logSuspiciousRequestAndRaiseHTTPError(IntegrationTestCase):
def setUp(self):
super(logSuspiciousRequestAndRaiseHTTPError, self).setUp()
from pyramid.request import Request
from pyramid.threadlocal import get_current_registry
self.config = testing.setUp()
request = Request({
'SERVER_PROTOCOL': 'testprotocol',
'SERVER_NAME': 'test server name',
'SERVER_PORT': '80',
})
request.context = TestContext()
request.root = request.context
request.subpath = ['path']
request.traversed = ['traversed']
request.view_name = 'test view name'
request.path_info = 'test info'
request.scheme = 'https'
request.host = 'test.com'
request.registry = get_current_registry()
self.request = request
self.data = {}
self.createDefaultData()
self.request.userAccount = self.data['user'].userAccount
@mock.patch('pulse.wapi.wapiUtilities.pyramid.threadlocal.get_current_request')
@mock.patch('pulse.wapi.wapiUtilities.securityLog')
def testHasRequest_raises400AndLogsError(
self, securityLog, get_current_request):
# Arrange
get_current_request.return_value = self.request
self.loggedInUser = self.data['user']
self.config.testing_securitypolicy(
userid=self.data['user'].userAccount.id, permissive=True
)
with self.assertRaises(exception.HTTPBadRequest):
from pulse.wapi.wapiUtilities import logSuspiciousRequestAndRaiseHTTPError
logSuspiciousRequestAndRaiseHTTPError()
self.assertTrue(securityLog.called)
self.assertTrue(securityLog.return_value.info.called)
</code></pre>
| 1
|
2016-09-10T08:54:52Z
|
[
"python",
"pyramid"
] |
pypi pakcage automatically uninstalling and upgrading other things?
| 39,368,443
|
<p>I have a pypi package that I distribute that requires django, in my setup.py I have this...</p>
<pre><code>install_requires = ["Django"]
</code></pre>
<p>then in the egg I have a requires.txt file that is like this...</p>
<pre><code>Django
</code></pre>
<p>Now I just made a new version and uploaded it to <code>pypi</code> and did <code>pip install -U mypackage</code> and it uninstalled my current django 1.10 and reinstalled django 1.10.1.</p>
<p>How can I make it leave the users Django version alone? </p>
| 0
|
2016-09-07T11:17:25Z
| 39,368,980
|
<p>Specify your version dependencies like</p>
<pre><code>install_requires = ["Django>=1.8"]
</code></pre>
<p>So that if the user has <code>Django</code> less than <code>1.8</code> then only it will upgrade.</p>
| 2
|
2016-09-07T11:42:50Z
|
[
"python",
"django"
] |
Python - TypeError: float() argument must be a string or a number, not 'list
| 39,368,446
|
<p>Python newbie here. I am trying to operate on lists which contain floating point numbers. <code>avg</code> is a list parameter that is returned from a different method. However, when I tried doing the following, it throws me an error that float() should have a string or a number and not a list. <code>avg1</code> should contain a copy of the lists with float-type numbers instead of lists right? I tried a few edits I read on other posts with similar titles, but couldn't solve this.
Just starting out so kindly tell me where I am going wrong. </p>
<pre><code>def movingavg(EMA,avg):
EMA=[]
avg1 = [float(i) for i in avg]
EMA[:3] = avg1[:3]
for i,j in zip(EMA[2:],avg1[3:]):
a =float(i)*0.67 + float(j)*0.33
EMA.append(a)
return EMA
</code></pre>
<p>The error that I get is as follows :</p>
<pre><code>avg1 = [float(i) for i in avg]
TypeError: float() argument must be a string or a number, not 'list'
</code></pre>
<p>Using Python 3.4</p>
| 0
|
2016-09-07T11:17:35Z
| 39,368,801
|
<p>Please check return type of avg I think it's return type is list's of list.</p>
| 0
|
2016-09-07T11:34:01Z
|
[
"python",
"python-3.x"
] |
Python - TypeError: float() argument must be a string or a number, not 'list
| 39,368,446
|
<p>Python newbie here. I am trying to operate on lists which contain floating point numbers. <code>avg</code> is a list parameter that is returned from a different method. However, when I tried doing the following, it throws me an error that float() should have a string or a number and not a list. <code>avg1</code> should contain a copy of the lists with float-type numbers instead of lists right? I tried a few edits I read on other posts with similar titles, but couldn't solve this.
Just starting out so kindly tell me where I am going wrong. </p>
<pre><code>def movingavg(EMA,avg):
EMA=[]
avg1 = [float(i) for i in avg]
EMA[:3] = avg1[:3]
for i,j in zip(EMA[2:],avg1[3:]):
a =float(i)*0.67 + float(j)*0.33
EMA.append(a)
return EMA
</code></pre>
<p>The error that I get is as follows :</p>
<pre><code>avg1 = [float(i) for i in avg]
TypeError: float() argument must be a string or a number, not 'list'
</code></pre>
<p>Using Python 3.4</p>
| 0
|
2016-09-07T11:17:35Z
| 39,368,948
|
<p>Instead of <code>avg1 = [float(i) for i in avg]</code> use below code.</p>
<pre><code>avg1 = []
for i in avg:
for j in i:
avg1.append(float(j))
</code></pre>
<p>or can use below list comprehension.</p>
<pre><code>avg1 = [float(i) for val in avg for i in val]
</code></pre>
| 0
|
2016-09-07T11:41:05Z
|
[
"python",
"python-3.x"
] |
Python - TypeError: float() argument must be a string or a number, not 'list
| 39,368,446
|
<p>Python newbie here. I am trying to operate on lists which contain floating point numbers. <code>avg</code> is a list parameter that is returned from a different method. However, when I tried doing the following, it throws me an error that float() should have a string or a number and not a list. <code>avg1</code> should contain a copy of the lists with float-type numbers instead of lists right? I tried a few edits I read on other posts with similar titles, but couldn't solve this.
Just starting out so kindly tell me where I am going wrong. </p>
<pre><code>def movingavg(EMA,avg):
EMA=[]
avg1 = [float(i) for i in avg]
EMA[:3] = avg1[:3]
for i,j in zip(EMA[2:],avg1[3:]):
a =float(i)*0.67 + float(j)*0.33
EMA.append(a)
return EMA
</code></pre>
<p>The error that I get is as follows :</p>
<pre><code>avg1 = [float(i) for i in avg]
TypeError: float() argument must be a string or a number, not 'list'
</code></pre>
<p>Using Python 3.4</p>
| 0
|
2016-09-07T11:17:35Z
| 39,368,957
|
<p>To convert a list of lists to float, you need to use two list comprehensions, like this:</p>
<pre><code>avg1 = [[float(i) for i in val] for val in avg]
</code></pre>
| 0
|
2016-09-07T11:41:39Z
|
[
"python",
"python-3.x"
] |
Python - TypeError: float() argument must be a string or a number, not 'list
| 39,368,446
|
<p>Python newbie here. I am trying to operate on lists which contain floating point numbers. <code>avg</code> is a list parameter that is returned from a different method. However, when I tried doing the following, it throws me an error that float() should have a string or a number and not a list. <code>avg1</code> should contain a copy of the lists with float-type numbers instead of lists right? I tried a few edits I read on other posts with similar titles, but couldn't solve this.
Just starting out so kindly tell me where I am going wrong. </p>
<pre><code>def movingavg(EMA,avg):
EMA=[]
avg1 = [float(i) for i in avg]
EMA[:3] = avg1[:3]
for i,j in zip(EMA[2:],avg1[3:]):
a =float(i)*0.67 + float(j)*0.33
EMA.append(a)
return EMA
</code></pre>
<p>The error that I get is as follows :</p>
<pre><code>avg1 = [float(i) for i in avg]
TypeError: float() argument must be a string or a number, not 'list'
</code></pre>
<p>Using Python 3.4</p>
| 0
|
2016-09-07T11:17:35Z
| 39,369,119
|
<p>For example if you have list = [ [1,2],[4,5] ]
then you can use
[[float(s) for s in xs] for xs in list]
and it's output is:
[[1.0, 2.0], [4.0, 5.0]] </p>
| -1
|
2016-09-07T11:48:46Z
|
[
"python",
"python-3.x"
] |
Python parse_known_args with named arguments
| 39,368,641
|
<p>I would like to pass an arbitrary set of arguments in the format <code>--arg1 value1</code> to my python script and retrieve them in a dictionary of the kind <code>{'arg1': 'value1}</code>. I want to use <code>argparse</code> to achieve that. The function <code>parse_known_args</code> allows for extra args, but they can be retrieved as a simple list and are not named.</p>
| -1
|
2016-09-07T11:26:04Z
| 39,369,112
|
<p>A better idea is to define <em>one</em> option that takes two arguments, a name and a value, and use a custom action to update a dictionary using those two arguments.</p>
<pre><code>class OptionAppend(Action):
def __call__(self, parser, namespace, values, option_string):
d = getattr(namespace, self.dest)
name, value = values
d[name] = value
p.add_argument("-o", "--option", nargs=2, action=OptionAppend, default={})
</code></pre>
<p>Then instead of <code>myscript --arg1 value1 --arg2 value2</code>, you would write <code>myscript -o arg1 value1 -o arg2value1</code>, and after <code>args = parser.parse_args()</code>, you would have <code>args.o == {'arg1': 'value1, 'arg2': 'value2'}</code>.</p>
<hr>
<p>This is somewhat analogous to the use of a list or dictionary to hold a set of related variables, instead of a set of individually named variables.</p>
<pre><code> # Good
v = [x, y, z]
v = { 'key1': x, 'key2': y, 'key3': z}
# Bad
v1 = x
v2 = y
v3 = z
</code></pre>
| 2
|
2016-09-07T11:48:28Z
|
[
"python",
"argparse"
] |
Python parse_known_args with named arguments
| 39,368,641
|
<p>I would like to pass an arbitrary set of arguments in the format <code>--arg1 value1</code> to my python script and retrieve them in a dictionary of the kind <code>{'arg1': 'value1}</code>. I want to use <code>argparse</code> to achieve that. The function <code>parse_known_args</code> allows for extra args, but they can be retrieved as a simple list and are not named.</p>
| -1
|
2016-09-07T11:26:04Z
| 39,375,736
|
<p>The question of handling arbitrary key/value pairs has come up a number of times. <code>argparse</code> does not have a builtin mechanism for that.</p>
<p><a href="http://stackoverflow.com/questions/37367331/argparse-arbitrary-optional-arguments">argparse - Arbitrary optional arguments</a> (almost a duplicate from last May)</p>
<p>Your idea of using <code>parse_know_args</code> and then doing your own dictionary build from the <code>extras</code> is good - and perhaps the simplest. How you handle the extras list will depend on how well behaved your users are (predicable <code>'--key', 'value'</code> pairs). This basically the same as if you parsed <code>sys.arv[1:]</code> directly.</p>
<p>If the user gives input like <code>--options key1:value1 key2=value2 "key3 value3"</code> you can parse those pairs in a custom Action class (e.g. split the string on the delimiter etc).</p>
<p>Input like <code>--options "{key1: value1, key2: value2}"</code> can be handled as a <code>JSON</code> string, with a type function like: <code>type=json.load</code> (I'd have to look that up).</p>
| 0
|
2016-09-07T17:10:16Z
|
[
"python",
"argparse"
] |
how to properly run Python script with crontab on every system startup
| 39,368,748
|
<p>I have a Python script that should open my Linux terminal, browser, file manager and text editor on system startup. I decided <code>crontab</code> is a suitable way to automatically run the script. Unfortunately, it doesn't went well, nothing happened when I reboot my laptop. So, I captured the output of the script to a file in order to get some clues. It seems my script is only partially executed. I use Debian 8 (Jessie), and here's my Python script:</p>
<pre><code>#!/usr/bin/env python3
import subprocess
import webbrowser
def action():
subprocess.call('gnome-terminal')
subprocess.call('subl')
subprocess.call(('xdg-open', '/home/fin/Documents/Learning'))
webbrowser.open('https://reddit.com/r/python')
if __name__ == '__main__':
action()
</code></pre>
<p>here's the entry in my <code>crontab</code> file:</p>
<pre><code>@reboot python3 /home/fin/Labs/my-cheatcodes/src/dsktp_startup_script/dsktp_startup_script.py > capture_report.txt
</code></pre>
<p>Here's the content of capture_report.txt file (I trim several lines, since its too long, it only prints my folder structures. seems like it came from '<code>xdg-open</code>' line on Python script):</p>
<pre><code>Directory list of /home/fin/Documents/Learning/
Type Format Sort
[Tree ] [Standard] [By Name] [Update]
âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
/
... the rest of my dir stuctures goes here
</code></pre>
<p>I have no other clue what's possible going wrong here. I really appreciate your advice guys. thanks.</p>
| 1
|
2016-09-07T11:30:47Z
| 39,369,451
|
<p>No, <code>cron</code> is not suitable for this. The <code>cron</code> daemon has no connection to your user's desktop session, which will not be running at system startup, anyway.</p>
<p>My recommendation would be to hook into your desktop environment's login scripts, which are responsible for starting various desktop services for you when you log in, anyway, and easily extended with your own scripts.</p>
| 1
|
2016-09-07T12:03:02Z
|
[
"python",
"cron"
] |
Python Paramiko Child Process
| 39,368,763
|
<p>I've written a script that uses PARAMIKO library to log on to a server and executes a command. This command actually invokes the server to execute another python script (resulting in a child process I believe). I believe the server returns back signal indicating that the command was executed successfully, however it doesn't seem to wait for the new child process to complete - only that the original parent process has been completed. Is there anyway of waiting to reference any/all child processes that were generated as a result of this command and waiting that they are all completed before returning control to the initiating client?</p>
<p>Many thanks.</p>
| 0
|
2016-09-07T11:31:18Z
| 39,369,100
|
<p>Without the code this will be difficult. I think you should create a rest service . So you would POST to <a href="http://0.0.0.0/runCode" rel="nofollow">http://0.0.0.0/runCode</a> and this would kick off a process in a different thread. That would end that call. The thread is still running ...when done do a post to http:// 0.0.0.0/afterProcessIsDone this will be the response from the thread that was kicked off. Then in that route you can do whatever you want with thay response there. If you need help with REST check out Flask. It's pretty easy and straight to the point for small projects.</p>
| 1
|
2016-09-07T11:47:45Z
|
[
"python",
"shell",
"process",
"subprocess",
"paramiko"
] |
How to install package via pip requirements.txt from VCS into current directory?
| 39,368,789
|
<p>For example, we have project <code>Foo</code> with dependency <code>Bar</code> (that in private Git repo) and we want install <code>Bar</code> into <code>Foo</code> directory via <code>pip</code> from <code>requirements.txt</code>. </p>
<p>We can manually install <code>Bar</code> with console command:</p>
<p><code>pip install --target=. git+ssh://git.repo/some_pkg.git#egg=SomePackage</code></p>
<p>But how to install <code>Bar</code> into current directory from <code>requirements.txt</code>? </p>
| 0
|
2016-09-07T11:33:03Z
| 39,369,148
|
<p>The best way to do this would be to clone the repository, or just donwload the <code>requirements.txt</code> file, and then run <code>pip install -r requirements.txt</code> to install all the modules dependencies. </p>
| 0
|
2016-09-07T11:50:15Z
|
[
"python",
"git",
"pip"
] |
Tkinter/matplotlib multiple active windows on osx
| 39,368,979
|
<p>I have a script as follows that executes on my windows machine</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import tkinter
class main(tkinter.Frame): #main window
def __init__(self, root): # initialise
tkinter.Frame.__init__(self)
self.root = root
tkinter.Button(self, text='New spots', command=self.newSpots).grid()
def newSpots(self):
x = np.random.rand(10)
y = np.random.rand(10)
plt.scatter(x,y)
plt.show()
if __name__=='__main__':
root = tkinter.Tk()
app = main(root).grid()
root.mainloop()
</code></pre>
<p>When running on windows, it opens a window with a simple button, and clicking this button opens a matplotlib viewer with 10 dots plotted in random positions. Each subsequent press of the button adds a further ten dots.</p>
<p>Executing this code on a mac produces the same initial window, and the first press of the button generates the plot and opens the viewer as expected. However, it then becomes impossible to interact with the original window (only the controls on the viewer work) until the viewer window is closed. How do I make the behaviour on the mac mirror that on the windows machine?</p>
| 2
|
2016-09-07T11:42:45Z
| 39,375,001
|
<p>I found a solution to this issue -- it seems matplotlib defaults to the TkAgg backend on Windows (I'm unsure whether this is a general Windows thing, or specific to whatever particular install is on the machine).</p>
<p>Adding the following lines to the top of the script forces the TkAgg backend and leads to the same behaviour on both machines.</p>
<pre><code>import matplotlib
matplotlib.use("TkAgg")
</code></pre>
| 1
|
2016-09-07T16:21:06Z
|
[
"python",
"windows",
"osx",
"matplotlib",
"tkinter"
] |
Python GUI class structure calls
| 39,369,039
|
<p>Let's say for example I have two classes, <code>A</code> and <code>B</code>.</p>
<p>Class <code>A</code> is the one I called <code>class main</code> and <code>B</code> is a <code>GUI</code> class(lets say its called <code>class main_gui</code>).</p>
<p>GUI class contains method that initiates and sets all views, buttons and stuff called <code>setupUi</code>. Class is generated by <code>QtCreator</code>.</p>
<p>What else must my class have to make it sufficient to run <code>B</code> by itself or be called from other classes? I know that calling <code>__init__</code> is not mandatory but its a good idea. What must this function contain? Is <code>__main__</code> mandatory to make it runnable? </p>
<p>What must <code>__main__</code> contain? What must the constructor contain? I am stuck on calling classes and I can't find simple enough explanation or a simple enough sample code that i can implement in my case. Please explain for braindead human. </p>
<p>I am a Java developer but i am new in Python and its specifics. If it is possible to provide with some code samples (even pseudocode will do) you will be very helpful. Thanks in advance! </p>
| 0
|
2016-09-07T11:45:14Z
| 39,369,391
|
<p>not sure if this is what your are looking for but :</p>
<p>A simple view :</p>
<pre><code>class Home(QtWidgets.QFrame, Ui_home):
"""Home view."""
def __init__(self, parent=None):
"""Initializer."""
super(Home, self).__init__()
self._parent = parent
self.setupUi(self)
</code></pre>
<p>Ui_home is the QtDesigner generated class </p>
<p>in my main i just create a QApplication and exec it :</p>
<pre><code>app = QtWidgets.QApplication(sys.argv)
</code></pre>
<p>Then i can call my home_controller or just create a home display my view:</p>
<pre><code>home = Home()
sys.exit(app.exec_())
</code></pre>
<p>Obviously this is a very simple exemple in a real app, you would have a class to handle the controller/ view creation but, this is as simple as that</p>
| 0
|
2016-09-07T12:00:30Z
|
[
"python",
"qt",
"python-3.x",
"pyqt",
"qt-creator"
] |
softlayer api: How to get the status(finish or processing) when copy os image cross IDC?
| 39,369,135
|
<p>When I call <code>SoftLayer_Virtual_Guest_Block_Device_Template_Group:addLocations</code> to copy private image_A cross <code>IDC</code>, this function returns <code>True</code> immediately. So it is known that the operation is asynchronous.</p>
<p>The question is how can I know that this async operation is finished, namely <code>image_A</code> is already finished copy to the target <code>IDC</code>?</p>
<p>I have found the api: </p>
<p><code>SoftLayer_Virtual_Guest_Block_Device_Template_Group:getTransaction()</code>, but this one always returns an empty str??What the hell ~ ~ ~</p>
| 0
|
2016-09-07T11:49:48Z
| 39,371,791
|
<p>You need to make the following call</p>
<pre><code>https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest_Block_Device_Template_Group/$templateGroupId/getChildren?objectMask=mask[transaction]
Method: Get
</code></pre>
<p>Replace: <strong>$user</strong>, <strong>$apiKey</strong> and <strong>$templateGroupId</strong></p>
<p>You need to verify that the children (image template groups that are clones of an image template group) have no any pending or current transaction. In case that there is one or more transactions, you will not able to add/remove locations until this finishes.</p>
| 0
|
2016-09-07T13:51:32Z
|
[
"python",
"api",
"softlayer"
] |
Is there a mode of python that traces each line executed, similar to 'bash -x'?
| 39,369,346
|
<p>I am running a python script in crontab that works fine from the command line but appears to not be running at all when it runs in cron. If this was a bash script, I would add 'bash -x' to the crontab and pipe STOUT and STDERR to a log file. Is there a similar mode of python that will capture the execution of each individual line of code within a script?</p>
| 1
|
2016-09-07T11:58:31Z
| 39,369,368
|
<p><a href="https://docs.python.org/2/library/trace.html" rel="nofollow">The trace module</a> does this.</p>
<pre><code>python -m trace --trace yourscript.py
</code></pre>
| 3
|
2016-09-07T11:59:37Z
|
[
"python",
"debugging"
] |
Beginner in Python, can't get this for loop to stop
| 39,369,347
|
<pre><code>Bit_128 = 0
Bit_64 = 0
Bit_32 = 0
Bit_64 = 0
Bit_32 = 0
Bit_16 = 0
Bit_8 = 0
Bit_4 = 0
Bit_2 = 0
Bit_1 = 0
Number = int(input("Enter number to be converted: "))
for power in range(7,0,-1):
if (2**power) <= Number:
place_value = 2**power
if place_value == 128:
Bit_128 = 1
elif place_value == 64:
Bit_64 = 1
elif place_value == 32:
Bit_32 = 1
elif place_value == 16:
Bit_16 = 1
elif place_value == 8:
Bit_8 = 1
elif place_value == 4:
Bit_4 = 1
elif place_value == 2:
Bit_2 = 1
elif place_value ==1:
Bit_1 = 1
Number = Number - (place_value)
if Number == 0:
print ("Binary form of"),Number,("is"),Bit_128,Bit_64,Bit_32,Bit_16,Bit_8,Bit_4,Bit_2,Bit_1
</code></pre>
<p>I want this loop to move to the next 'power' value when it fails the first if condition, but when I run it in an interpreter, the program keeps on running despite the first condition not being true. I only want it to move on the next conditions if the first condition turns out to be true.
How can I do this? This is my first "big" program in python, and I'm having a hard time figuring this out. Any tips would be appreciated. Btw, the program is meant to convert any number from 1-255 to binary form. </p>
| 0
|
2016-09-07T11:58:39Z
| 39,369,511
|
<p>If you want a loop to go to the next value, all you need to do is use the continue keyword:</p>
<pre><code>...
for power in range(7,0,-1):
if (2**power) <= Number:
place_value = 2**power
continue
...
</code></pre>
| 0
|
2016-09-07T12:05:51Z
|
[
"python",
"for-loop"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.