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
listlengths
1
5
How do I write the index for a list of lists
38,730,635
<p>I have a list of 3 lists each containing a random integer between 1 and 9:</p> <pre><code>lists= [[1,3,5],[2,4,6],[7,8,9]] </code></pre> <p>I ask the user to select any single digit number. I am making a program that finds the number one less than the user inputs and then decides if the next number in the list (assuming it is not the end of the list) is bigger or smaller.</p> <pre><code>for x in lists: for i in x: if i= user_choice-1: </code></pre> <p>Here I am stuck.</p> <p>Lets say the user_choice is 3. I want the program to find the number 3-1=2 in the nested lists and then compare the number following 2 (in this case 4) to the user_choice. </p>
0
2016-08-02T21:19:04Z
38,730,744
<p>I am a little confused by what you are trying to achieve but you can get the index along with the element in a for loop by using:</p> <pre><code>for index, value in enumerate(my_list): # Do stuff here </code></pre> <p>Or you can find the index of any element in a list with:</p> <pre><code>index = my_list.index(value) </code></pre> <p>Don't forget to change you <code>=</code> to a <code>==</code> in your if statement, by the way.</p>
1
2016-08-02T21:26:51Z
[ "python", "list", "syntax" ]
How do I write the index for a list of lists
38,730,635
<p>I have a list of 3 lists each containing a random integer between 1 and 9:</p> <pre><code>lists= [[1,3,5],[2,4,6],[7,8,9]] </code></pre> <p>I ask the user to select any single digit number. I am making a program that finds the number one less than the user inputs and then decides if the next number in the list (assuming it is not the end of the list) is bigger or smaller.</p> <pre><code>for x in lists: for i in x: if i= user_choice-1: </code></pre> <p>Here I am stuck.</p> <p>Lets say the user_choice is 3. I want the program to find the number 3-1=2 in the nested lists and then compare the number following 2 (in this case 4) to the user_choice. </p>
0
2016-08-02T21:19:04Z
38,730,788
<p>If I understand correctly, you want:</p> <pre><code>for x in lists: for i in range(len(x)): if x[i] == user_choice-1 and i &lt; len(x)-1: if x[i+1] &gt; x[i]: #Next value is bigger... else: #Next value is smaller... </code></pre>
1
2016-08-02T21:30:03Z
[ "python", "list", "syntax" ]
~/.bash_profile in OSX version 10.11.6 for virtualenv and Python
38,730,743
<p>So when I just write these commands in the terminal I get these errors:</p> <pre><code> /  L/F/P  Versions  export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3  ➶ 127  04:21:45 PM /  L/F/P  Versions  source /usr/local/bin/virtualenvwrapper.sh  04:21:52 PM Expected end of the statement, but instead found a '&amp;' /usr/local/bin/virtualenvwrapper.sh (line 67): if [ "$OS" = "Windows_NT" ] &amp;&amp; ([ "$MSYSTEM" = "MINGW32" ] || [ "$MSYSTEM" = "MINGW64" ]) ^ from sourcing file /usr/local/bin/virtualenvwrapper.sh called on standard input source: Error while reading file '/usr/local/bin/virtualenvwrapper.sh' </code></pre> <p>Also when I write them in <code>~/.bash_profile</code> I get these errors:</p> <pre><code> /  L/F/P  Versions  vi ~/.bash_profile  04:18:50 PM /  L/F/P  Versions  source ~/.bash_profile  04:21:11 PM Unsupported use of '&amp;&amp;'. In fish, please use 'COMMAND; and COMMAND'. ~/.bash_profile (line 3): [[ -s "$HOME/.profile" ]] &amp;&amp; source "$HOME/.profile" # Load the default .profile ^ from sourcing file ~/.bash_profile called on standard input source: Error while reading file '/Users/mona/.bash_profile' </code></pre> <p>I have these in my <code>~/.bash_profile</code>:</p> <pre><code> ~/.bash_profile 1 export PATH=$PATH:/usr/local/go/bin 2 3 [[ -s "$HOME/.profile" ]] &amp;&amp; source "$HOME/.profile" # Load the default .profile 4 5 [[ -s "$HOME/.rvm/scripts/rvm" ]] &amp;&amp; source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function* 6 7 # Setting PATH for Python 3.4 8 # The orginal version is saved in .bash_profile.pysave 9 PATH="/Library/Frameworks/Python.framework/Versions/3.4/bin:${PATH}" 10 export PATH 11 12 # added by Anaconda2 2.4.1 installer 13 export PATH="/Users/mona/anaconda/bin:$PATH" 14 15 compresspdf() { 16 gs -sDEVICE=pdfwrite -dNOPAUSE -dQUIET -dBATCH -dPDFSETTINGS=/${3:-"screen"} -dCompatibilityLevel=1.4 -sOutputFile=$2 $1 17 } 18 19 20 export PATH="/usr/local/sbin:$PATH" 21 export PATH=/usr/local/bin:$PATH 22 export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3 23 source /usr/local/bin/virtualenvwrapper.sh ~ </code></pre> <p>I am trying to follow this tutorial:</p> <pre><code>http://www.pyimagesearch.com/2015/06/29/install-opencv-3-0-and-python-3-4-on-osx/ </code></pre> <p>Thanks for any help or comment.</p> <pre><code> /  L/F/P  Versions  python  04:28:32 PM Python 3.5.2 (default, Jul 28 2016, 21:28:07) [GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin Type "help", "copyright", "credits" or "license" for more information. </code></pre>
0
2016-08-02T21:26:47Z
38,730,875
<p>It looks like you're using <code>fish</code> shell. Your bash profile is written using items that are apparently unsupported by fish, see specifically</p> <pre><code>Unsupported use of '&amp;&amp;'. In fish, please use 'COMMAND; and COMMAND'. </code></pre> <p>From when you tried to source your bash profile. You may need to find a different tutorial to follow, create the virtualenvs yourself, or try to translate the bash pieces of the tutorial to fish.</p>
1
2016-08-02T21:36:03Z
[ "python", "opencv", ".bash-profile" ]
Django: changing image size and upload to S3
38,730,753
<p>I have inherited a Django Project and we have moved images to S3</p> <p>One of the models is a typical user profile</p> <pre><code>class Profile(UUIDBase): first_name = models.CharField(_("First Name"), max_length=20) last_name = models.CharField(_("Last Name"), max_length=20, null=True) profile_image = models.ImageField( _("Profile Image"), upload_to=profile_image_name, max_length=254, blank=True, null=True ) profile_image_thumb = models.ImageField( _("Profile Image Thumbnail"), upload_to=profile_image_name, max_length=254, blank=True, null=True ) ... other fields </code></pre> <p>Where <code>profile_image_name</code> is a function:</p> <pre><code>def profile_image_name(instance, filename): if filename: target_dir = 'uploads/profile_img/' _, ext = filename.rsplit('.', 1) filename = str(instance.uid) + '.' + ext return '/'.join([target_dir, filename]) </code></pre> <p>I have a bit of code that worked:</p> <pre><code>@shared_task def resize_image(image_path, dim_x, append_str='_resized', **kwargs): ''' resize any image_obj while maintaining aspect ratio ''' orig = storage.open(image_path, 'r') im = Image.open(orig, mode='r') new_y = (float(dim_x) * float(im.height)) / float(im.width) new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS) img_path, img_name = path.split(image_path) file_name, img_ext = img_name.rsplit('.', 1) new_img_path = path.join(img_path, file_name + append_str + '.' + img_ext) try: new_f = storage.open(new_img_path, 'w') except IOError as e: logger.critical("Caught IOError in {}, {}".format(__file__, e)) ravenclient.captureException() return None try: new_im.save(new_f) except IOError as e: logger.critical("Caught IOError in {}, {}".format(__file__, e)) ravenclient.captureException() return None except Exception as e: logger.critical("Caught unhandled exception in {}. {}".format( __file__, e) ) ravenclient.captureException() return None im.close() new_im.close() new_f.close() return new_img_path </code></pre> <p>Which is called from a post_save signal handler :</p> <pre><code>@receiver(post_save, sender=Profile, dispatch_uid='resize_profile_image') def resize_profile_image(sender, instance=None, created=False, **kwargs): if created: if instance.profile_image: width, height = image_dimensions(instance.profile_image.name) print(width, height) if width &gt; MAX_WIDTH: result = resize_image.delay(instance.profile_image.name, MAX_WIDTH) instance.profile_image.name = result.get() if width &gt; THUMB_WIDTH: result = resize_image.delay( instance.profile_image.name, THUMB_WIDTH, append_str='_thumb' ) instance.profile_image_thumb.name = result.get() try: instance.save() except Exception as e: log.critical("Unhandled exception in {}, {}".format(__name__, e)) ravenclient.captureException() </code></pre> <p>The intent is to take uploaded images and resize them 1) to the max width that a mobile device can display and 2) to a 50 pixel thumbnail for use in the mobile app.</p> <p>When I look on S3, I do not see my resized images or thumbnails. Yet the unit tests (which are thorough) don't give any errors.</p> <p>When I get the image dimensions:</p> <pre><code>def image_dimensions(image_path): f = storage.open(image_path, 'r') im = Image.open(f, 'r') height = im.height width = im.width im.close() f.close() return (width, height) </code></pre> <p>There is no problem accessing the object's ImageField. I get no error when I use default_storage to open the instance's profile_image. The PIL method </p> <p><code>new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS)</code> does return a new instance of class 'PIL.Image.Image'.</p> <p>In fact (pardon my verbosity)</p> <p>This does not raise an error:</p> <pre><code>&gt;&gt;&gt; u = User(email="root@groupon.com", password="sdfbskjfskjfskjdf") &gt;&gt;&gt; u.save() &gt;&gt;&gt; p = Profile(user=u, profile_image=create_image_file()) &gt;&gt;&gt; p.save() &gt;&gt;&gt; from django.core.files.storage import default_storage as storage &gt;&gt;&gt; orig = storage.open(p.profile_image.name, 'r') &gt;&gt;&gt; orig &lt;S3BotoStorageFile: uploads/profile_img/b0fd4f00-cce6-4dd3-b514-4c46a801ab19.jpg&gt; &gt;&gt;&gt; im = Image.open(orig, mode='r') &gt;&gt;&gt; im &lt;PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=5000x5000 at 0x10B8F1FD0&gt; &gt;&gt;&gt; im.__class__ &lt;class 'PIL.JpegImagePlugin.JpegImageFile'&gt; &gt;&gt;&gt; dim_x = 500 &gt;&gt;&gt; new_y = (float(dim_x) * float(im.height)) / float(im.width) &gt;&gt;&gt; new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS) &gt;&gt;&gt; new_im.__class__ &lt;class 'PIL.Image.Image'&gt; &gt;&gt;&gt; img_path, img_name = path.split(p.profile_image.name) &gt;&gt;&gt; file_name, img_ext = img_name.rsplit('.', 1) &gt;&gt;&gt; append_str='_resized' &gt;&gt;&gt; new_img_path = path.join(img_path, file_name + append_str + '.' + img_ext) &gt;&gt;&gt; new_f = storage.open(new_img_path, 'w') &gt;&gt;&gt; new_f &lt;S3BotoStorageFile: uploads/profile_img/b0fd4f00-cce6-4dd3-b514-4c46a801ab19_resized.jpg&gt; &gt;&gt;&gt; new_im.save(new_f) #### This does NOT create an S3 file!!!! &gt;&gt;&gt; im.close() &gt;&gt;&gt; new_im.close() &gt;&gt;&gt; new_f.close() </code></pre> <p><code>&gt;&gt;&gt; p.save()</code> uploads the new profile image to S3. I was expecting <code>&gt;&gt;&gt; new_im.save(new_f)</code> to write the Image file to S3. But it does not.</p> <p>Any insight or help is greatly appreciated and thank you for taking the time to look at this problem.</p> <p>Edit ...</p> <p>My settings:</p> <pre><code>AWS_STORAGE_BUCKET_NAME = 'testthis' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' </code></pre> <p>Where custom_storage.py is</p> <pre><code>from django.conf import settings from storages.backends.s3boto import S3BotoStorage class MediaStorage(S3BotoStorage): location = settings.MEDIAFILES_LOCATION bucket_name = settings.AWS_STORAGE_BUCKET_NAME </code></pre>
6
2016-08-02T21:27:26Z
38,779,207
<p>The issue seems to be related to PIL's JPEG library:</p> <pre><code>&gt;&gt;&gt; u = User(email="root@groupon.com", password="sdfbskjfskjfskjdf") &gt;&gt;&gt; u.save() &gt;&gt;&gt; p = Profile(user=u, profile_image=create_image_file()) &gt;&gt;&gt; p.save() &gt;&gt;&gt; from django.core.files.storage import default_storage as storage &gt;&gt;&gt; orig = storage.open(p.profile_image.name, 'r') &gt;&gt;&gt; orig &lt;S3BotoStorageFile: uploads/profile_img/b0fd4f00-cce6-4dd3-b514-4c46a801ab19.png&gt; &gt;&gt;&gt; im = Image.open(orig, mode='r') &gt;&gt;&gt; im.__class__ &lt;class 'PIL.PngImagePlugin.PngImageFile'&gt; &gt;&gt;&gt; dim_x = 500 &gt;&gt;&gt; new_y = (float(dim_x) * float(im.height)) / float(im.width) &gt;&gt;&gt; new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS) &gt;&gt;&gt; new_im.__class__ &lt;class 'PIL.Image.Image'&gt; &gt;&gt;&gt; img_path, img_name = path.split(p.profile_image.name) &gt;&gt;&gt; file_name, img_ext = img_name.rsplit('.', 1) &gt;&gt;&gt; append_str='_resized' &gt;&gt;&gt; new_img_path = path.join(img_path, file_name + append_str + '.' + img_ext) &gt;&gt;&gt; new_f = storage.open(new_img_path, 'w') &gt;&gt;&gt; new_f &lt;S3BotoStorageFile: uploads/profile_img/b0fd4f00-cce6-4dd3-b514-4c46a801ab19_resized.png&gt; &gt;&gt;&gt; new_im.save(new_f) #### This does create a file on S3! &gt;&gt;&gt; im.close() &gt;&gt;&gt; new_im.close() &gt;&gt;&gt; new_f.close() </code></pre>
0
2016-08-05T00:04:21Z
[ "python", "django", "amazon-s3", "python-imaging-library", "image-resizing" ]
Django: changing image size and upload to S3
38,730,753
<p>I have inherited a Django Project and we have moved images to S3</p> <p>One of the models is a typical user profile</p> <pre><code>class Profile(UUIDBase): first_name = models.CharField(_("First Name"), max_length=20) last_name = models.CharField(_("Last Name"), max_length=20, null=True) profile_image = models.ImageField( _("Profile Image"), upload_to=profile_image_name, max_length=254, blank=True, null=True ) profile_image_thumb = models.ImageField( _("Profile Image Thumbnail"), upload_to=profile_image_name, max_length=254, blank=True, null=True ) ... other fields </code></pre> <p>Where <code>profile_image_name</code> is a function:</p> <pre><code>def profile_image_name(instance, filename): if filename: target_dir = 'uploads/profile_img/' _, ext = filename.rsplit('.', 1) filename = str(instance.uid) + '.' + ext return '/'.join([target_dir, filename]) </code></pre> <p>I have a bit of code that worked:</p> <pre><code>@shared_task def resize_image(image_path, dim_x, append_str='_resized', **kwargs): ''' resize any image_obj while maintaining aspect ratio ''' orig = storage.open(image_path, 'r') im = Image.open(orig, mode='r') new_y = (float(dim_x) * float(im.height)) / float(im.width) new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS) img_path, img_name = path.split(image_path) file_name, img_ext = img_name.rsplit('.', 1) new_img_path = path.join(img_path, file_name + append_str + '.' + img_ext) try: new_f = storage.open(new_img_path, 'w') except IOError as e: logger.critical("Caught IOError in {}, {}".format(__file__, e)) ravenclient.captureException() return None try: new_im.save(new_f) except IOError as e: logger.critical("Caught IOError in {}, {}".format(__file__, e)) ravenclient.captureException() return None except Exception as e: logger.critical("Caught unhandled exception in {}. {}".format( __file__, e) ) ravenclient.captureException() return None im.close() new_im.close() new_f.close() return new_img_path </code></pre> <p>Which is called from a post_save signal handler :</p> <pre><code>@receiver(post_save, sender=Profile, dispatch_uid='resize_profile_image') def resize_profile_image(sender, instance=None, created=False, **kwargs): if created: if instance.profile_image: width, height = image_dimensions(instance.profile_image.name) print(width, height) if width &gt; MAX_WIDTH: result = resize_image.delay(instance.profile_image.name, MAX_WIDTH) instance.profile_image.name = result.get() if width &gt; THUMB_WIDTH: result = resize_image.delay( instance.profile_image.name, THUMB_WIDTH, append_str='_thumb' ) instance.profile_image_thumb.name = result.get() try: instance.save() except Exception as e: log.critical("Unhandled exception in {}, {}".format(__name__, e)) ravenclient.captureException() </code></pre> <p>The intent is to take uploaded images and resize them 1) to the max width that a mobile device can display and 2) to a 50 pixel thumbnail for use in the mobile app.</p> <p>When I look on S3, I do not see my resized images or thumbnails. Yet the unit tests (which are thorough) don't give any errors.</p> <p>When I get the image dimensions:</p> <pre><code>def image_dimensions(image_path): f = storage.open(image_path, 'r') im = Image.open(f, 'r') height = im.height width = im.width im.close() f.close() return (width, height) </code></pre> <p>There is no problem accessing the object's ImageField. I get no error when I use default_storage to open the instance's profile_image. The PIL method </p> <p><code>new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS)</code> does return a new instance of class 'PIL.Image.Image'.</p> <p>In fact (pardon my verbosity)</p> <p>This does not raise an error:</p> <pre><code>&gt;&gt;&gt; u = User(email="root@groupon.com", password="sdfbskjfskjfskjdf") &gt;&gt;&gt; u.save() &gt;&gt;&gt; p = Profile(user=u, profile_image=create_image_file()) &gt;&gt;&gt; p.save() &gt;&gt;&gt; from django.core.files.storage import default_storage as storage &gt;&gt;&gt; orig = storage.open(p.profile_image.name, 'r') &gt;&gt;&gt; orig &lt;S3BotoStorageFile: uploads/profile_img/b0fd4f00-cce6-4dd3-b514-4c46a801ab19.jpg&gt; &gt;&gt;&gt; im = Image.open(orig, mode='r') &gt;&gt;&gt; im &lt;PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=5000x5000 at 0x10B8F1FD0&gt; &gt;&gt;&gt; im.__class__ &lt;class 'PIL.JpegImagePlugin.JpegImageFile'&gt; &gt;&gt;&gt; dim_x = 500 &gt;&gt;&gt; new_y = (float(dim_x) * float(im.height)) / float(im.width) &gt;&gt;&gt; new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS) &gt;&gt;&gt; new_im.__class__ &lt;class 'PIL.Image.Image'&gt; &gt;&gt;&gt; img_path, img_name = path.split(p.profile_image.name) &gt;&gt;&gt; file_name, img_ext = img_name.rsplit('.', 1) &gt;&gt;&gt; append_str='_resized' &gt;&gt;&gt; new_img_path = path.join(img_path, file_name + append_str + '.' + img_ext) &gt;&gt;&gt; new_f = storage.open(new_img_path, 'w') &gt;&gt;&gt; new_f &lt;S3BotoStorageFile: uploads/profile_img/b0fd4f00-cce6-4dd3-b514-4c46a801ab19_resized.jpg&gt; &gt;&gt;&gt; new_im.save(new_f) #### This does NOT create an S3 file!!!! &gt;&gt;&gt; im.close() &gt;&gt;&gt; new_im.close() &gt;&gt;&gt; new_f.close() </code></pre> <p><code>&gt;&gt;&gt; p.save()</code> uploads the new profile image to S3. I was expecting <code>&gt;&gt;&gt; new_im.save(new_f)</code> to write the Image file to S3. But it does not.</p> <p>Any insight or help is greatly appreciated and thank you for taking the time to look at this problem.</p> <p>Edit ...</p> <p>My settings:</p> <pre><code>AWS_STORAGE_BUCKET_NAME = 'testthis' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' </code></pre> <p>Where custom_storage.py is</p> <pre><code>from django.conf import settings from storages.backends.s3boto import S3BotoStorage class MediaStorage(S3BotoStorage): location = settings.MEDIAFILES_LOCATION bucket_name = settings.AWS_STORAGE_BUCKET_NAME </code></pre>
6
2016-08-02T21:27:26Z
38,811,226
<p>The problem is in django-storages. S3BotoStorageFile's _file attribute is a SpooledTemporaryFile which works for png files, but not jpg files. </p> <p>See: <a href="https://github.com/jschneier/django-storages/issues/155" rel="nofollow">https://github.com/jschneier/django-storages/issues/155</a></p>
0
2016-08-07T05:35:49Z
[ "python", "django", "amazon-s3", "python-imaging-library", "image-resizing" ]
Regex to extract all urls from string
38,730,782
<p>I have a string like this </p> <blockquote> <p><code>http://example.com/path/topage.htmlhttp://twitter.com/p/xyanhshttp://httpget.org/get.zipwww.google.com/privacy.htmlhttps://goodurl.net/</code></p> </blockquote> <p>I would like to extract all url / webaddress into a Array. for example </p> <p><code>urls = ['http://example.com/path/topage.html','http://twitter.com/p/xyan',.....]</code></p> <p>Here is my approach which didn't work. </p> <pre><code>import re strings = "http://example.com/path/topage.htmlhttp://twitter.com/p/xyanhshttp://httpget.org/get.zipwww.google.com/privacy.htmlhttps://goodurl.net/" links = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', strings) print links // result always same as strings </code></pre>
-1
2016-08-02T21:29:31Z
38,730,916
<p>The problem is that your regex pattern is too inclusive. It includes all urls. You can use lookahead by using (?=)</p> <p>Try this:</p> <pre><code>re.findall("((www\.|http://|https://)(www\.)*.*?(?=(www\.|http://|https://|$)))", strings) </code></pre>
2
2016-08-02T21:39:14Z
[ "python", "regex" ]
Regex to extract all urls from string
38,730,782
<p>I have a string like this </p> <blockquote> <p><code>http://example.com/path/topage.htmlhttp://twitter.com/p/xyanhshttp://httpget.org/get.zipwww.google.com/privacy.htmlhttps://goodurl.net/</code></p> </blockquote> <p>I would like to extract all url / webaddress into a Array. for example </p> <p><code>urls = ['http://example.com/path/topage.html','http://twitter.com/p/xyan',.....]</code></p> <p>Here is my approach which didn't work. </p> <pre><code>import re strings = "http://example.com/path/topage.htmlhttp://twitter.com/p/xyanhshttp://httpget.org/get.zipwww.google.com/privacy.htmlhttps://goodurl.net/" links = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', strings) print links // result always same as strings </code></pre>
-1
2016-08-02T21:29:31Z
38,731,035
<p>Your problem is that <code>http://</code> is being accepted as a valid part of a url. This is because of this token right here:</p> <pre><code>[$-_@.&amp;+] </code></pre> <p>or more specifically:</p> <pre><code>$-_ </code></pre> <p>This matches all characters with the range from <code>$</code> to <code>_</code>, which includes a lot more characters than you probably intended to do.</p> <p>You can change this to <code>[$\-_@.&amp;+]</code> but this causes problems since now, <code>/</code> characters will not match. So add it by using <code>[$\-_@.&amp;+/]</code>. However, this will again cause problems since <code>http://example.com/path/topage.htmlhttp</code> would be considered a valid match.</p> <p>The final addition is to add a lookahead to ensure that you are not matching <code>http://</code> or <code>https://</code>, which just so happens to be the first part of your regex!</p> <pre><code>http[s]?://(?:(?!http[s]?://)[a-zA-Z]|[0-9]|[$\-_@.&amp;+/]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+ </code></pre> <p>tested <a href="https://regex101.com/r/sF0oM0/1" rel="nofollow">here</a></p>
0
2016-08-02T21:46:35Z
[ "python", "regex" ]
Regex to extract all urls from string
38,730,782
<p>I have a string like this </p> <blockquote> <p><code>http://example.com/path/topage.htmlhttp://twitter.com/p/xyanhshttp://httpget.org/get.zipwww.google.com/privacy.htmlhttps://goodurl.net/</code></p> </blockquote> <p>I would like to extract all url / webaddress into a Array. for example </p> <p><code>urls = ['http://example.com/path/topage.html','http://twitter.com/p/xyan',.....]</code></p> <p>Here is my approach which didn't work. </p> <pre><code>import re strings = "http://example.com/path/topage.htmlhttp://twitter.com/p/xyanhshttp://httpget.org/get.zipwww.google.com/privacy.htmlhttps://goodurl.net/" links = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', strings) print links // result always same as strings </code></pre>
-1
2016-08-02T21:29:31Z
38,731,212
<p>A simple answer without getting into much complication:</p> <pre><code>import re url_list = [] for x in re.split("http://", l): url_list.append(re.split("https://",x)) url_list = [item for sublist in url_list for item in sublist] </code></pre> <p>In case you want to append the string <code>http://</code> and <code>https://</code> back to the urls, do appropriate changes to the code. Hope i convey the idea.</p>
0
2016-08-02T22:02:54Z
[ "python", "regex" ]
Python 3.4 windows, pip install fails
38,730,867
<p>I am struggling with adding to my Python 34 installation:</p> <p>C:> pip install --upgrade pip<BR> Could not find any downloads that satisfy the requirement pip in c:\python34\lib \site-packages<BR> Collecting pip<BR> No distributions at all found for pip in c:\python34\lib\site-packages<BR></p> <p>What am I doing wrong? Please help.</p>
0
2016-08-02T21:35:25Z
38,730,957
<p>You need to run pip as a script and python will be the main executable.</p> <pre><code>python -m pip install -U pip </code></pre> <p>The recommended procedure will be to update from get-pip.py</p> <pre><code>curl https://bootstrap.pypa.io/get-pip.py | python </code></pre>
2
2016-08-02T21:41:50Z
[ "python", "windows", "pip" ]
Python 3.4 windows, pip install fails
38,730,867
<p>I am struggling with adding to my Python 34 installation:</p> <p>C:> pip install --upgrade pip<BR> Could not find any downloads that satisfy the requirement pip in c:\python34\lib \site-packages<BR> Collecting pip<BR> No distributions at all found for pip in c:\python34\lib\site-packages<BR></p> <p>What am I doing wrong? Please help.</p>
0
2016-08-02T21:35:25Z
38,767,497
<p>Seems I found the reason: the Windows computer is within a state agency behind a hefty firewall. I tried the same install with Python 3.4.3 from my laptop connected through my phone and had no problem at all. So, I think the firewall was in the way. Thanks for looking into this, @froost1999 and @Rockse .</p>
0
2016-08-04T12:35:17Z
[ "python", "windows", "pip" ]
Many-to-many relationship with different other objects, self and attributes in SQLAlchemy
38,731,062
<p>I am declaring a somewhat complicated model with SQLAlchemy. I have basic objects like (fields are not important in that case):</p> <pre><code>class A(Base): __tablename__ = 'as' class B(Base): __tablename__ = 'bs' </code></pre> <p>Now I want to declare a collection of such objects, which would be easy with a simple <code>relationship</code>, but unfortunately, I need the followinf <code>class C</code>:</p> <ul> <li>A single field called <code>members</code> that can point to an arbitrary number of <code>A</code> and <code>B</code> objects</li> <li>It also needs to be able to contain references to other <code>C</code> objects as well.</li> <li>The mappings need to have an attribute attached to them.</li> </ul> <p>I think the third bullet point is simple, as described at <a href="http://pythoncentral.io/sqlalchemy-association-tables/" rel="nofollow">http://pythoncentral.io/sqlalchemy-association-tables/</a> . I do not know if the first one is possible, and I do not get my head wrapped around the second. I tried a simple <code>relationship('C')</code>, but that lead to SQLAlchemy complaining a lot about duplicate foreign key fields.</p>
-1
2016-08-02T21:49:04Z
38,745,928
<p>The answer is to use <strong>joined table inheritance</strong> as described <a href="http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#joined-table-inheritance" rel="nofollow">here</a>.</p> <p>First, add a common parent class for the similar classes, with a field named type (or anything else) as a discriminator…</p> <pre><code>class E(Base): __tablename__ = 'es' id = COlumn(Integer, primary_key=True) type = Column(String) </code></pre> <p>…then add mapper arguments:</p> <pre><code> __mapper_args__ = { 'polymorphic_identity': 'es', 'polymorphic_on': type, 'with_polymorphic': '*' } </code></pre> <p>Let the similar classes inherit from it…</p> <pre><code>class A(E): __tablename__ = 'as' </code></pre> <p>…and have them use a shared primary/foreign key and the correct mapper args:</p> <pre><code> id = Column(Integer, ForeignKey('es.id'), primary_key=True) __mapper_args__ = { 'polymorphic_identity': 'as' } </code></pre> <p>(Same goes for <code>B</code>)</p> <p>A relationship can then be defined towards class <code>E</code>.</p> <p>The relationship to the class containing the relationship itself just works if you leave out the backref.</p>
0
2016-08-03T14:06:09Z
[ "python", "orm", "sqlalchemy" ]
How to "merge" multiple pandas dataframes with the index as dataframe column?
38,731,071
<p>I have two pandas dataframes: one:</p> <pre><code>import pandas as pd df1 = pd.read_csv('filename1.csv') df1 A B 0 1 22 1 2 15 2 5 99 3 6 1 .... </code></pre> <p>and two</p> <pre><code>df2 = pd.read_csv('filename1.csv') df2 A B 0 1 6 1 3 52 2 4 15 3 5 62 ... </code></pre> <p>I would like to merge these dataframes into a single dataframe, with column <code>A</code> as the index for this new dataframe. </p> <p>The columns are filenames, the rows are the values for 'A'. </p> <p>If values do not exist for these index, <code>NaN</code> then exists. The column names should be the filenames from the *csv above.</p> <pre><code> filename1 filename2 1 22 6 2 15 NaN 3 NaN 52 4 NaN 15 5 99 62 6 1 NaN </code></pre> <p>How does one do this? For two files, one could use <code>pandas.merge()</code>, but what is dozens of the orginal dataframes exists? </p>
2
2016-08-02T21:49:45Z
38,731,184
<pre><code>files = ['file1', 'file2'] def read(f): f = f + '.csv' df = pd.read_csv(f, usecols=['A', 'B']) return df.drop_duplicates(subset=['A']).set_index('A').B pd.concat([read(f) for f in files], axis=1, keys=files) </code></pre> <p><a href="http://i.stack.imgur.com/vG4XW.png" rel="nofollow"><img src="http://i.stack.imgur.com/vG4XW.png" alt="enter image description here"></a></p>
3
2016-08-02T22:00:30Z
[ "python", "python-3.x", "pandas", "indexing", "dataframe" ]
Django(1.9.6) list_display works on dev not prod
38,731,104
<p>I am running a local version of django on my computer as well as a django droplet at DigitalOcean, both Django 1.9.6. However, everything I have done this far has been the same across these two environment, but when I tried to customize the admin screen, it only worked on my local env. </p> <p>The change I did was to add the following code to the app/admin.py.</p> <pre><code>class PostAdmin(admin.ModelAdmin): list_display = ('post_title', 'pub_date', 'is_premium', 'source_title') list_filter = ['pub_date', 'source_title', 'is_premium'] admin.site.register(Post, PostAdmin) </code></pre> <p>But this customization is only shown on my local env... I have of course pulled and updated my code on DigitalOcean using Git. Just to make that clear. </p> <p><a href="http://i.stack.imgur.com/bLMV4.png" rel="nofollow">Screenshot of local environment</a></p> <p><a href="http://i.stack.imgur.com/NEufV.png" rel="nofollow">Screenshot of DigitalOcean environment</a></p>
0
2016-08-02T21:53:02Z
38,788,188
<p>I needed to restart gunicorn. Thanks to valentjedi for providing the answer in the comments. </p>
0
2016-08-05T11:29:52Z
[ "python", "django" ]
Mysterious "embedded null byte" error
38,731,132
<p>Working on a fairly large/complex Django project with a team, we occasionally see runserver crash with <code>ValueError: embedded null byte</code>. We restart runserver and it's fine - either for a few minutes or a few days. We can detect no pattern to what causes the crashes (seems totally random). Fortunately it's only happening in local development, not on our servers, but I'm worried that it will bite us down the road.</p> <p>The stack trace below does not point to any location in our code -- seems to come either from Django or the virtualenv itself.</p> <p>Using Django 1.9.8, Python 3.5.0, on El Capitan. </p> <p>I can't see any way to debug this. Theories? </p> <pre><code>Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 54, in execute super(Command, self).execute(*args, **options) File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 93, in handle self.run(**options) File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.main(self.inner_run, None, options) File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/utils/autoreload.py", line 333, in main reloader(wrapped_main_func, args, kwargs) File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/utils/autoreload.py", line 299, in python_reloader reloader_thread() File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/utils/autoreload.py", line 275, in reloader_thread change = fn() File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/utils/autoreload.py", line 204, in code_changed for filename in gen_filenames(): File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/utils/autoreload.py", line 114, in gen_filenames basedirs = [os.path.abspath(basedir) for basedir in basedirs File "/path/to/virtualenvs/ourproj/lib/python3.5/site-packages/django/utils/autoreload.py", line 115, in &lt;listcomp&gt; if os.path.isdir(basedir)] File "/path/to/virtualenvs/ourproj/bin/../lib/python3.5/genericpath.py", line 42, in isdir st = os.stat(s) ValueError: embedded null byte </code></pre>
0
2016-08-02T21:55:17Z
38,731,324
<ul> <li>One of the <code>AppConfig</code> objects has null byte in its <code>path</code> attribute.</li> <li>One of the <code>LOCALE_PATHS</code> has null byte.</li> <li>One of the files is in the "wrong" encoding, so Django treats something has null byte (e. g. <code>AppConfig.path</code>).</li> <li>One of the files or directories in project directory has null byte (<code>\x00</code>) in its name.</li> <li>Other reason.</li> </ul> <p><a href="https://github.com/django/django/blob/master/django/utils/autoreload.py#L108-L115" rel="nofollow"><code>autoreload.py</code> lines</a> related to this issue. <code>os.path.isdir()</code> raises <code>ValueError: embedded null byte</code> if its argument has null byte, e. g. <code>os.path.isdir('foo\x00bar')</code>.</p> <p>You can try to edit <code>autoreload.py</code>, comment out these lines temporarily:</p> <pre><code>basedirs = [os.path.abspath(basedir) for basedir in basedirs if os.path.isdir(basedir)] </code></pre> <p>and add this:</p> <pre><code>temp_basedirs = [] for basedir in basedirs: try: if os.path.isdir(basedir): temp_basedirs.append(os.path.abspath(basedir)) except ValueError: print(basedir) raise basedirs = temp_basedirs </code></pre>
0
2016-08-02T22:14:13Z
[ "python", "django" ]
Access Second Instance Of Key In Nested Dictionary In Python
38,731,133
<p>So I'm utilizing the <a href="https://github.com/simon-weber/gmusicapi" rel="nofollow">GMusicAPI</a> to try to interact with Google Play Music (I'm utilizing the MobileClient view) a bit. Unfortunately it's only in Python, a language I've never used before. I'm running a search, that will search for a given artist. The problem I run into is that, some artists, the artist I want isn't the first result.</p> <p>My solution around that was to just search (this search returns a dictionary) for the Top 5-10 artists and then loop through them until the name in the dictionary key matches the search query.</p> <p>Here's the portion of the dictionary I'm getting back from the search. This specifically is the <code>"artist_hits"</code> section.</p> <pre><code>[{'artist': {'name': 'Tiësto', 'artistArtRef': 'http://lh3.googleusercontent.com/wfrs3FuLMoZ7MMfESLOE7kXw9pR9usqZsR-OCo7GW544aqHfj_WMo_YYeETdAmUGQU9fJW7D', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': False, 'url': 'http://lh3.googleusercontent.com/wfrs3FuLMoZ7MMfESLOE7kXw9pR9usqZsR-OCo7GW544aqHfj_WMo_YYeETdAmUGQU9fJW7D', 'aspectRatio': '2'}], 'kind': 'sj#artist', 'artistId': 'Agzf4r7d54azste62qh6z2q7bcy', 'artist_bio_attribution': {'license_url': 'http://creativecommons.org/licenses/by-sa/4.0/legalcode', 'kind': 'sj#attribution', 'source_title': 'Wikipedia', 'license_title': 'Creative Commons Attribution CC-BY-SA 4.0', 'source_url': 'http://en.wikipedia.org/wiki/Ti%C3%ABsto'}}, 'type': '2'}, {'artist': {'name': 'Skrillex', 'artistArtRef': 'http://lh3.googleusercontent.com/wUw1KU9e6VOO7tSNFjKvCljL05Fud1w5mvt8UTbs5G7fBS4sFGphEOIs0EUXBwF9CHuGFEufgQ', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': False, 'url': 'http://lh3.googleusercontent.com/wUw1KU9e6VOO7tSNFjKvCljL05Fud1w5mvt8UTbs5G7fBS4sFGphEOIs0EUXBwF9CHuGFEufgQ', 'aspectRatio': '2'}], 'kind': 'sj#artist', 'artistId': 'Aqy2vtuiohb4rdrakrtbphxbdme', 'artist_bio_attribution': {'kind': 'sj#attribution', 'source_title': 'artist representative'}}, 'type': '2'}, {'artist': {'kind': 'sj#artist', 'artistId': 'Achiqpfv5ncaoobeiu6vfmf2jf4', 'name': 'Marshmello', 'artistArtRef': 'http://lh3.googleusercontent.com/KAqga3a8rX1Tam5FSyWGUcT56Zm9uDoyei2vty1Xra8CApKn1vi5Nb9-nNt70U4Q6rtuOA9KXQ', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/KAqga3a8rX1Tam5FSyWGUcT56Zm9uDoyei2vty1Xra8CApKn1vi5Nb9-nNt70U4Q6rtuOA9KXQ', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/Zp3xcR0sc0LDnFuYy7sY-l8ggvEmPjFK_UruOSaZk25jKIYZKDsZA382WIyXqptClH91oI7QzQ', 'aspectRatio': '1'}]}, 'type': '2'}, {'artist': {'name': 'deadmau5', 'artistArtRef': 'http://lh3.googleusercontent.com/rNh6zCCuiJCgEWldulkYIbpfP33W9K0ULAPsWrDThPdz_naqHR_bznxRFgoOwMRr5V0ur-O-', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': False, 'url': 'http://lh3.googleusercontent.com/rNh6zCCuiJCgEWldulkYIbpfP33W9K0ULAPsWrDThPdz_naqHR_bznxRFgoOwMRr5V0ur-O-', 'aspectRatio': '2'}], 'kind': 'sj#artist', 'artistId': 'Atngmlxlixottlthpcypidmxlu4', 'artist_bio_attribution': {'license_url': 'http://creativecommons.org/licenses/by-sa/4.0/legalcode', 'kind': 'sj#attribution', 'source_title': 'Wikipedia', 'license_title': 'Creative Commons Attribution CC-BY-SA 4.0', 'source_url': 'http://en.wikipedia.org/wiki/Deadmau5'}}, 'type': '2'}, {'artist': {'kind': 'sj#artist', 'artistId': 'A3akm3hkaas6r4mp3nmhn2d7vom', 'name': 'Marshmello', 'artistArtRef': 'http://lh3.googleusercontent.com/sU63V5nC1xAYuYLfd-WCzmfP5Z1iYslm8xntUe6HPVRmvIEs9QCwaxRgcaQy1Eh8HbSEwEMunQ', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/sU63V5nC1xAYuYLfd-WCzmfP5Z1iYslm8xntUe6HPVRmvIEs9QCwaxRgcaQy1Eh8HbSEwEMunQ', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh4.ggpht.com/6cv48SUFmOIXMjXmgs6KCw6NViHEQ2w2YRN2hhQ6HBAcVggh9-L882bYwH5VKZ2YqloodT3rNg', 'aspectRatio': '1'}]}, 'type': '2'}, {'artist': {'kind': 'sj#artist', 'artistId': 'Aatki3zj7b6fnemq2qldpjmfg74', 'name': 'Marshmellow Overcoat', 'artistArtRef': 'http://lh3.googleusercontent.com/-0spMaLVdzkwkoLgfNPAAL-KMUX1ulOYEMN7sAs_i2kZtFhq-CmPCKHECF_wRtKeTUnFWKViPg', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/-0spMaLVdzkwkoLgfNPAAL-KMUX1ulOYEMN7sAs_i2kZtFhq-CmPCKHECF_wRtKeTUnFWKViPg', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.ggpht.com/BfiwEzdKnrAonw4myuyPu6p7GlsAhpd3ZA4E4wQQ-rkygRikCYKRwOWTTM1y3C2oYhPkqXsq0Q', 'aspectRatio': '1'}]}, 'type': '2'}, {'artist': {'kind': 'sj#artist', 'artistId': 'Aik7qbnj6ml3i7fpya4rwxjswqq', 'name': 'Marshmellow', 'artistArtRef': 'http://lh3.googleusercontent.com/9UXduVP_4LP702bqvQKU8NKBh9sH_1P9LLYXYQ_IcRcVQUNXqMiSY1dykYdWlGR21NsakeOK', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/9UXduVP_4LP702bqvQKU8NKBh9sH_1P9LLYXYQ_IcRcVQUNXqMiSY1dykYdWlGR21NsakeOK', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/xmuuJ_XtgD1CBq7ZBKYZdo0gp7s9oiXZeNQ1lEhDfsXIWhAv2JD3w7IyM54y5OFpw8cAOEaV2Q', 'aspectRatio': '1'}]}, 'type': '2'}] </code></pre> <p>My question is how do I access anything past the first <code>"artist"</code> key? I need to get the <code>"name"</code> and <code>"artistId"</code> values from it. I'm calling the first one like this.</p> <p><code>ArtistSearch['artist_hits'][0]['artist']['name']</code></p> <p>And that works fine. However I try to access the second instance of that key like this</p> <p><code>ArtistSearch['artist_hits'][0]['artist'][1]['name']</code></p> <p>And it doesn't work. Any help would be greatly appreciated.</p>
0
2016-08-02T21:55:24Z
38,731,167
<p>I think what you wish is:</p> <pre><code>ArtistSearch['artist_hits'][1]['artist']['name'] # ---^--- </code></pre> <p>because <code>ArtistSearch['artist_hits']</code> is the list, you want the second dictionary <code>[1]</code> and inside it the <code>['artist']['name']</code> field</p>
1
2016-08-02T21:59:09Z
[ "python", "dictionary", "nested", "key", "value" ]
Access Second Instance Of Key In Nested Dictionary In Python
38,731,133
<p>So I'm utilizing the <a href="https://github.com/simon-weber/gmusicapi" rel="nofollow">GMusicAPI</a> to try to interact with Google Play Music (I'm utilizing the MobileClient view) a bit. Unfortunately it's only in Python, a language I've never used before. I'm running a search, that will search for a given artist. The problem I run into is that, some artists, the artist I want isn't the first result.</p> <p>My solution around that was to just search (this search returns a dictionary) for the Top 5-10 artists and then loop through them until the name in the dictionary key matches the search query.</p> <p>Here's the portion of the dictionary I'm getting back from the search. This specifically is the <code>"artist_hits"</code> section.</p> <pre><code>[{'artist': {'name': 'Tiësto', 'artistArtRef': 'http://lh3.googleusercontent.com/wfrs3FuLMoZ7MMfESLOE7kXw9pR9usqZsR-OCo7GW544aqHfj_WMo_YYeETdAmUGQU9fJW7D', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': False, 'url': 'http://lh3.googleusercontent.com/wfrs3FuLMoZ7MMfESLOE7kXw9pR9usqZsR-OCo7GW544aqHfj_WMo_YYeETdAmUGQU9fJW7D', 'aspectRatio': '2'}], 'kind': 'sj#artist', 'artistId': 'Agzf4r7d54azste62qh6z2q7bcy', 'artist_bio_attribution': {'license_url': 'http://creativecommons.org/licenses/by-sa/4.0/legalcode', 'kind': 'sj#attribution', 'source_title': 'Wikipedia', 'license_title': 'Creative Commons Attribution CC-BY-SA 4.0', 'source_url': 'http://en.wikipedia.org/wiki/Ti%C3%ABsto'}}, 'type': '2'}, {'artist': {'name': 'Skrillex', 'artistArtRef': 'http://lh3.googleusercontent.com/wUw1KU9e6VOO7tSNFjKvCljL05Fud1w5mvt8UTbs5G7fBS4sFGphEOIs0EUXBwF9CHuGFEufgQ', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': False, 'url': 'http://lh3.googleusercontent.com/wUw1KU9e6VOO7tSNFjKvCljL05Fud1w5mvt8UTbs5G7fBS4sFGphEOIs0EUXBwF9CHuGFEufgQ', 'aspectRatio': '2'}], 'kind': 'sj#artist', 'artistId': 'Aqy2vtuiohb4rdrakrtbphxbdme', 'artist_bio_attribution': {'kind': 'sj#attribution', 'source_title': 'artist representative'}}, 'type': '2'}, {'artist': {'kind': 'sj#artist', 'artistId': 'Achiqpfv5ncaoobeiu6vfmf2jf4', 'name': 'Marshmello', 'artistArtRef': 'http://lh3.googleusercontent.com/KAqga3a8rX1Tam5FSyWGUcT56Zm9uDoyei2vty1Xra8CApKn1vi5Nb9-nNt70U4Q6rtuOA9KXQ', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/KAqga3a8rX1Tam5FSyWGUcT56Zm9uDoyei2vty1Xra8CApKn1vi5Nb9-nNt70U4Q6rtuOA9KXQ', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/Zp3xcR0sc0LDnFuYy7sY-l8ggvEmPjFK_UruOSaZk25jKIYZKDsZA382WIyXqptClH91oI7QzQ', 'aspectRatio': '1'}]}, 'type': '2'}, {'artist': {'name': 'deadmau5', 'artistArtRef': 'http://lh3.googleusercontent.com/rNh6zCCuiJCgEWldulkYIbpfP33W9K0ULAPsWrDThPdz_naqHR_bznxRFgoOwMRr5V0ur-O-', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': False, 'url': 'http://lh3.googleusercontent.com/rNh6zCCuiJCgEWldulkYIbpfP33W9K0ULAPsWrDThPdz_naqHR_bznxRFgoOwMRr5V0ur-O-', 'aspectRatio': '2'}], 'kind': 'sj#artist', 'artistId': 'Atngmlxlixottlthpcypidmxlu4', 'artist_bio_attribution': {'license_url': 'http://creativecommons.org/licenses/by-sa/4.0/legalcode', 'kind': 'sj#attribution', 'source_title': 'Wikipedia', 'license_title': 'Creative Commons Attribution CC-BY-SA 4.0', 'source_url': 'http://en.wikipedia.org/wiki/Deadmau5'}}, 'type': '2'}, {'artist': {'kind': 'sj#artist', 'artistId': 'A3akm3hkaas6r4mp3nmhn2d7vom', 'name': 'Marshmello', 'artistArtRef': 'http://lh3.googleusercontent.com/sU63V5nC1xAYuYLfd-WCzmfP5Z1iYslm8xntUe6HPVRmvIEs9QCwaxRgcaQy1Eh8HbSEwEMunQ', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/sU63V5nC1xAYuYLfd-WCzmfP5Z1iYslm8xntUe6HPVRmvIEs9QCwaxRgcaQy1Eh8HbSEwEMunQ', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh4.ggpht.com/6cv48SUFmOIXMjXmgs6KCw6NViHEQ2w2YRN2hhQ6HBAcVggh9-L882bYwH5VKZ2YqloodT3rNg', 'aspectRatio': '1'}]}, 'type': '2'}, {'artist': {'kind': 'sj#artist', 'artistId': 'Aatki3zj7b6fnemq2qldpjmfg74', 'name': 'Marshmellow Overcoat', 'artistArtRef': 'http://lh3.googleusercontent.com/-0spMaLVdzkwkoLgfNPAAL-KMUX1ulOYEMN7sAs_i2kZtFhq-CmPCKHECF_wRtKeTUnFWKViPg', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/-0spMaLVdzkwkoLgfNPAAL-KMUX1ulOYEMN7sAs_i2kZtFhq-CmPCKHECF_wRtKeTUnFWKViPg', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.ggpht.com/BfiwEzdKnrAonw4myuyPu6p7GlsAhpd3ZA4E4wQQ-rkygRikCYKRwOWTTM1y3C2oYhPkqXsq0Q', 'aspectRatio': '1'}]}, 'type': '2'}, {'artist': {'kind': 'sj#artist', 'artistId': 'Aik7qbnj6ml3i7fpya4rwxjswqq', 'name': 'Marshmellow', 'artistArtRef': 'http://lh3.googleusercontent.com/9UXduVP_4LP702bqvQKU8NKBh9sH_1P9LLYXYQ_IcRcVQUNXqMiSY1dykYdWlGR21NsakeOK', 'artistArtRefs': [{'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/9UXduVP_4LP702bqvQKU8NKBh9sH_1P9LLYXYQ_IcRcVQUNXqMiSY1dykYdWlGR21NsakeOK', 'aspectRatio': '2'}, {'kind': 'sj#imageRef', 'autogen': True, 'url': 'http://lh3.googleusercontent.com/xmuuJ_XtgD1CBq7ZBKYZdo0gp7s9oiXZeNQ1lEhDfsXIWhAv2JD3w7IyM54y5OFpw8cAOEaV2Q', 'aspectRatio': '1'}]}, 'type': '2'}] </code></pre> <p>My question is how do I access anything past the first <code>"artist"</code> key? I need to get the <code>"name"</code> and <code>"artistId"</code> values from it. I'm calling the first one like this.</p> <p><code>ArtistSearch['artist_hits'][0]['artist']['name']</code></p> <p>And that works fine. However I try to access the second instance of that key like this</p> <p><code>ArtistSearch['artist_hits'][0]['artist'][1]['name']</code></p> <p>And it doesn't work. Any help would be greatly appreciated.</p>
0
2016-08-02T21:55:24Z
38,731,260
<p>I think that the dictionary itself is not well formed, maybe you don't need the "artist" keyword. However could be useful access data in dictionary with something like:</p> <pre><code>for key,value in dictionary.iteritems(): print key,value </code></pre> <p>Rather than statically with numeric indices.</p>
0
2016-08-02T22:08:14Z
[ "python", "dictionary", "nested", "key", "value" ]
NameError: global name 'category' is not defined
38,731,247
<p>I am making a Hangman Game and having trouble. Ok every time I go to edit this and save my edits I get a red mark saying I need more details not just code so this is my more details. Please do not delete it or I cannot edit my post. :)</p> <p>My error is, </p> <blockquote> <p>"NameError: global name 'category' is not defined" </p> </blockquote> <pre><code>#Hangman Game V1 by (My name) import random import time play_again = 'Yes' #Categorys animals = ['alligator', 'barracuda', 'cougar', 'cheetah', 'dolphin', 'falcon', 'gorilla', 'penguin', 'salmon', 'wombat'] olympics = ['archery', 'badminton', 'cycling', 'rowing', 'fencing', 'gymnastics', 'sailing', 'tennis', 'swimming', 'volleyball'] countries = ['china', 'america', 'mexico', 'russia', 'sweden', 'canada', 'spain', 'korea', 'japan', 'france'] def intro(): print '' print 'Welcome to Hangman by (My name)!' print '' print '' def pick_category(): category = raw_input('First, choose a category by typing in it\'s name. Your options are: Animals, Olympics, &amp; '\ 'Countries!') print '' print 'You chose the category ' + category + '.' return category def choose_word(): print '' print 'Now I will pick the secret word from your category.' print '' print '...' time.sleep(1) if category == 'Animals': secret_word = random.choice(animals) if category == 'Olympics': secret_word = random.choice(olympics) if category == 'Countries': secret_word = random.choice(countries) print '' print 'Alright, I have chosen the word!' #for testing purposes print secret_word </code></pre> <p>while play_again: intro() pick_category() choose_word()</p>
0
2016-08-02T22:06:52Z
38,731,468
<p>You probably meant for <em>category</em> to be an argument of <code>choose_word()</code>. At the moment <code>pick_category()</code> returns the value of the local variable <em>category</em>, which is then ignored. Instead define <code>choose_word()</code> as:</p> <pre><code>def choose_word(category): ... </code></pre> <p>and pass the returned category to it, for example like this:</p> <pre><code>while play_again: intro() # Passes the returned category as the argument choose_word(pick_category()) </code></pre>
1
2016-08-02T22:27:27Z
[ "python", "nameerror" ]
How to calculate sum of prime numbers from list of integers in Python?
38,731,252
<p>I am struck and need help with this.. I want to find the sum of prime numbers from a given list of integers. Here are a few test cases for the same. </p> <pre><code>n([3,3,1,13]) 19 n([2,4,6,9,11]) 13 n([-3,0,1,6]) 0 </code></pre> <p>The Code that I have written is as follows but it fails with the test cases above..</p> <pre><code>def sumprimes(n): sum1 = 0 for i in range(0,len(n)): num = n[i] if num &gt; 1: for j in range(2, int(num**0.5)+1): if num%j != 0: sum1 = sum1 + num else: sum1 = 0 return(sum1) </code></pre>
1
2016-08-02T22:07:25Z
38,731,389
<p>This part is wrong:</p> <pre><code> for j in range(2, int(num**0.5)+1): if num%j != 0: sum1 = sum1 + num </code></pre> <p>you are summing <code>num</code> for each number in the range that didn't divide. you should sum just if <strong>all</strong> of them didn't divide.</p> <p>Simple way to do this is:</p> <pre><code> prime = True for j in range(2, int(num**0.5)+1): if num%j == 0: prime = False break if prime: sum1 = sum1 + num </code></pre> <p>Or in a more <em>pythonic</em> way using <a class='doc-link' href="http://stackoverflow.com/documentation/python/209/list/8125/any-and-all#t=20160802223010260792">all()</a>:</p> <pre><code> if all(num%j != 0 for j in range(2, int(num**0.5)+1)): sum1 = sum1 + num </code></pre>
5
2016-08-02T22:20:06Z
[ "python", "python-3.x" ]
How to calculate sum of prime numbers from list of integers in Python?
38,731,252
<p>I am struck and need help with this.. I want to find the sum of prime numbers from a given list of integers. Here are a few test cases for the same. </p> <pre><code>n([3,3,1,13]) 19 n([2,4,6,9,11]) 13 n([-3,0,1,6]) 0 </code></pre> <p>The Code that I have written is as follows but it fails with the test cases above..</p> <pre><code>def sumprimes(n): sum1 = 0 for i in range(0,len(n)): num = n[i] if num &gt; 1: for j in range(2, int(num**0.5)+1): if num%j != 0: sum1 = sum1 + num else: sum1 = 0 return(sum1) </code></pre>
1
2016-08-02T22:07:25Z
38,731,629
<p>Don't try to do everything in one function. I separated out the rest of the logic, but I'll leave isprime to you:</p> <pre><code>def isprime(x): # Replace this with your code # separate function so it can have its own tests return x in [3, 13, 11, 2] def sum_prime_numbers_in_list(l): return sum([x for x in l if isprime(x)]) if 19 != sum_prime_numbers_in_list([3, 3, 1, 13]): raise ValueError else: print 'pass' if 13 != sum_prime_numbers_in_list([2, 4, 6, 9, 11]): raise ValueError else: print 'pass' if 0 != sum_prime_numbers_in_list([-3, 0, 1, 6]): raise ValueError else: print 'pass' </code></pre>
1
2016-08-02T22:42:07Z
[ "python", "python-3.x" ]
How to calculate sum of prime numbers from list of integers in Python?
38,731,252
<p>I am struck and need help with this.. I want to find the sum of prime numbers from a given list of integers. Here are a few test cases for the same. </p> <pre><code>n([3,3,1,13]) 19 n([2,4,6,9,11]) 13 n([-3,0,1,6]) 0 </code></pre> <p>The Code that I have written is as follows but it fails with the test cases above..</p> <pre><code>def sumprimes(n): sum1 = 0 for i in range(0,len(n)): num = n[i] if num &gt; 1: for j in range(2, int(num**0.5)+1): if num%j != 0: sum1 = sum1 + num else: sum1 = 0 return(sum1) </code></pre>
1
2016-08-02T22:07:25Z
38,769,444
<p>The Answer should be this. [You should try this code, in this link.<a href="https://gist.github.com/Jayhalani/aa7ddf085bea9d1057644a93753f8813" rel="nofollow">Gist</a>]</p> <pre><code>def sumprimes(n): sum1 = 0 for i in range(0,len(n)): num = n[i] if num &gt; 1: prime = True for j in range(2, int(num**0.5)+1): if num%j == 0: prime = False break if prime: sum1 = sum1 + num #else: # sum1 = 0 return(sum1) </code></pre>
0
2016-08-04T13:57:43Z
[ "python", "python-3.x" ]
I can't understand how this (function?) works
38,731,273
<p>I'm pretty new to Python and I'm going through a starter book. The code isn't written in English so I tried my best to translate, hope you guys understand. It has this exercise where we calculate the taxes from the user salary:</p> <pre><code>salary = float(input("Enter your salary to taxes calculation: ")) base = salary taxes = 0 if base &gt; 3000: taxes = taxes + ((base - 3000) * 0.35) base = 3000 if base &gt; 1000: taxes = taxes + ((base - 1000) * 0.20) </code></pre> <p>My problem is when the input is bigger than 3000, for example, if I run the code with the salary of 5000, the result will be 1100. But when I do the 'same' math on the calculator the result is 700, so I'm lost in here, could someone explain it please?</p>
2
2016-08-02T22:09:50Z
38,731,333
<p>Please note that in case of salary 5000, the control will go to both the if statements. So it comes out as 700 from first, and 400 from second, therefore answer is 700+400. This also makes sense, as tax calculation is mostly partitioned in brackets, and is not a flat percentage on salary.</p>
5
2016-08-02T22:14:43Z
[ "python" ]
I can't understand how this (function?) works
38,731,273
<p>I'm pretty new to Python and I'm going through a starter book. The code isn't written in English so I tried my best to translate, hope you guys understand. It has this exercise where we calculate the taxes from the user salary:</p> <pre><code>salary = float(input("Enter your salary to taxes calculation: ")) base = salary taxes = 0 if base &gt; 3000: taxes = taxes + ((base - 3000) * 0.35) base = 3000 if base &gt; 1000: taxes = taxes + ((base - 1000) * 0.20) </code></pre> <p>My problem is when the input is bigger than 3000, for example, if I run the code with the salary of 5000, the result will be 1100. But when I do the 'same' math on the calculator the result is 700, so I'm lost in here, could someone explain it please?</p>
2
2016-08-02T22:09:50Z
38,731,354
<p>It flows on to the second function </p> <p>so if I sub in the numbers:</p> <pre><code>Salary = 5000 base = 5000 taxes = 0 if 5000 &gt; 3000: taxes = 0 + ((5000- 3000) * 0.35) # = 700 base = 3000 if 3000 &gt; 1000: taxes = 700 + ((3000 - 1000) * 0.20) # = 1100 </code></pre>
1
2016-08-02T22:16:40Z
[ "python" ]
I can't understand how this (function?) works
38,731,273
<p>I'm pretty new to Python and I'm going through a starter book. The code isn't written in English so I tried my best to translate, hope you guys understand. It has this exercise where we calculate the taxes from the user salary:</p> <pre><code>salary = float(input("Enter your salary to taxes calculation: ")) base = salary taxes = 0 if base &gt; 3000: taxes = taxes + ((base - 3000) * 0.35) base = 3000 if base &gt; 1000: taxes = taxes + ((base - 1000) * 0.20) </code></pre> <p>My problem is when the input is bigger than 3000, for example, if I run the code with the salary of 5000, the result will be 1100. But when I do the 'same' math on the calculator the result is 700, so I'm lost in here, could someone explain it please?</p>
2
2016-08-02T22:09:50Z
38,731,377
<p>Alright, let's walk through it with your example of 5000</p> <pre><code>salary = float(input("Enter your salary to taxes calculation: ")) base = salary # base = 5000 taxes = 0 if base &gt; 3000: # base is larger than 3000, so we enter the if statement taxes = taxes + ((base - 3000) * 0.35) # taxes = 0 + ((5000 - 3000) * 0.35) # taxes = 0 + 700 # taxes = 700 base = 3000 # base is set to 3000 if base &gt; 1000: # base was set to 3000 in the line above, so we enter the if statement taxes = taxes + ((base - 1000) * 0.20) # taxes = 700 + ((3000 - 1000) * 0.20), remember taxes is already 700 from above # taxes = 700 + 400 # taxes = 1100 </code></pre> <p>since it is two <code>if</code> statements and not an <code>if</code> and an <code>else</code> we evaluate both statements when <code>base</code> is set larger than 3000. I hope that helps.</p>
3
2016-08-02T22:19:18Z
[ "python" ]
I can't understand how this (function?) works
38,731,273
<p>I'm pretty new to Python and I'm going through a starter book. The code isn't written in English so I tried my best to translate, hope you guys understand. It has this exercise where we calculate the taxes from the user salary:</p> <pre><code>salary = float(input("Enter your salary to taxes calculation: ")) base = salary taxes = 0 if base &gt; 3000: taxes = taxes + ((base - 3000) * 0.35) base = 3000 if base &gt; 1000: taxes = taxes + ((base - 1000) * 0.20) </code></pre> <p>My problem is when the input is bigger than 3000, for example, if I run the code with the salary of 5000, the result will be 1100. But when I do the 'same' math on the calculator the result is 700, so I'm lost in here, could someone explain it please?</p>
2
2016-08-02T22:09:50Z
38,731,398
<p>This is an economical equation which calculate tax for every part of salary. the procedure would be this: </p> <ul> <li>For amount greater than <code>3000</code> calculate 35% tax for this portion of salary.</li> <li>For amount greater than <code>1000</code> (and less than <code>3000</code>) calculate 20% tax for this portion of salary.</li> </ul> <p>Tax over salary would be the summation of this taxes.</p>
0
2016-08-02T22:21:21Z
[ "python" ]
Looping over dictionary values, which are nested lists to convert into matrices
38,731,317
<p>I have the following problem:</p> <p>I have a dictionary where each K,V is as follows:</p> <p>k = 1 String </p> <p>v = nested lists in the following manner,</p> <p>inside V are A number of lists, inside each A list, there are B number of lists, inside each B list there are C number of entries.</p> <p>Eventually, I would like to do some calculations of averages and standard deviations so I would like to create a dictionary where the key is the same and the v is as follows:</p> <p>a matrix of A rows by B columns, where each entry in the matrix is the list B. This would allow me to arrange the data in such a way that I could remove specific values from each column of the matrix to do some calculations.</p> <p>This was my reasoning, so I have tried the following:</p> <pre><code>#Initialzing the new dictionary matrix_dictionary = {} for k,v in overall_dictionary.iteritems(): num_rows = len(v) #Number of rows in desired matrix for i in v: width = len(i) #Number of columns in desired matrix #Initializing the matrix data_matrix = [[] for i in xrange(0,width) for j in xrange(0,num_rows)] for y in xrange(0,height)#For row in row for element in v: #For each list A in v counter = 0; #one of indices to add element to specific spot in matrix for i in element:#for B list in A data_matrix[y][counter] = i #Trying to add list B inside matrix counter = counter + 1; matrix_dictionary[k] = data_matrix #Adding key value pair to dic </code></pre> <p><strong>Different attempt at explaining problem</strong></p> <p>for each k in the dictionary, i have a 3D v</p> <p>v for example is made up of 100 lists (A)</p> <p>Each list has 50 lists (B) inside of it</p> <p>Each list B has a list C, Where two indices of C are of interest</p> <p>I want to create a giant table that is A rows by B columns and all of the C lists are inside</p> <p>Example: first row, first column has C1, first row second column has C2, etc...</p> <p>I want the matrix to then be the value in the dictionary</p> <p><strong>I saw the following errors</strong></p> <p>1) Index error for the matrix</p> <p>2) The following works outside on its own</p> <pre><code>for k, v in ovarall_dictionary.iteritems(): for A in v: print(A) #Prints the list A containing a bunch of lists B for B in A: print(B) #Prints each B list </code></pre> <p>However, the following does not work, I get index out of range for list, why?</p> <pre><code>z = v[0] print(z) </code></pre> <p><strong>Eventual Goal</strong></p> <p>For each k,v in new matrix dictionary</p> <p>For each column in the matrix and within each cell for that column get two indices X and Y</p> <p>get the average of all of the X's, get the average of all the Y's</p> <p>Make a new dictionary with k as string, and list of results as value pairs</p> <p><strong>Help needed on</strong></p> <p>I've been explained that I have a 3D array inside v: A[B[C]]]</p> <p>I want to create a AxB matrix where different values of C are easily callable in the matrix</p>
-1
2016-08-02T22:13:36Z
38,732,104
<p>The good news is: You already have your dictionary in the form you want! A list of lists <strong><em>is</em></strong> a 2D matrix.</p> <p>The bad news: It's not really so clear what errors you're having and where they are coming up. More detail on that would be helpful for people to come up with solutions.</p> <p>In the meantime, a few comments on your code (though I don't think it's necessary since you already have a matrix):</p> <ul> <li>You use height in your code, but never initialize it. Is height = num_rows?</li> <li><p>Instead of iterating through all of the rows, updating width each time, just do it once, like:</p> <pre><code>width = len(v[0]) #This assumes all rows have same number of cols </code></pre></li> <li><p>No need for the semi-colons. (Not that there's anything wrong with them!)</p></li> <li><p>The indentation in your code isn't clear. Make sure everything is in the right for loop.</p></li> <li><p>You should have 'for element' not 'for element a'.</p></li> <li><p>I think the counter complicates things. Try to use 'enumerate' or something like that instead.</p></li> </ul>
0
2016-08-02T23:36:26Z
[ "python", "loops", "dictionary", "matrix", "list-comprehension" ]
Tkinter, why does my code skip the first label update?
38,731,350
<p>I have a button that I want to press to process some excel data. This often takes a moment or two especially if the user uploads a number of large files. While the files are being processed, I want to display a note to the user that the files are processing and that the program has not frozen. Once the files are complete, I want to indicate that as well. </p> <p>This is the relevant code I have so far:</p> <pre><code> self.l2 = Label(self, text = " ", width = 20) self.l2.grid(row = 3, column = 2, sticky = W) # Calculate button self.b2 = Button(self, text = "Calculate", command = self.calculate, width = 20) self.b2.grid(row = 3, column = 3, sticky = W) def calculate(self): self.l2.config(text="Processing...") get_data(filelist, self.v.get()) self.l2.config(text="Files Ready!") </code></pre> <p>The label is initially blank like I want and once the files are ready it shows "files ready" but it never seems to hit the "processing" label even if I upload enough files for the get_data command to take nearly a minute. </p> <p>Why exactly would it not be showing up? It seems like the commands should execute sequentially, the label should update, get_data should be called, then once get _data has returned, the next label update should happen. Is this logic incorrect?</p>
0
2016-08-02T22:15:58Z
38,731,393
<p>In order for the screen to refresh, the event loop must be able to process a refresh event. Since your code is running, the event loop is frozen.</p> <p>A quick and dirty solution is to call <code>self.update_idletasks()</code>, which tells tkinter to handle all of the "idle" events, which includes events related to updating the screen.</p> <pre><code>self.l2.config(text="Processing...") self.update_idletasks() get_data(filelist, self.v.get()) self.l2.config(text="Files Ready!") </code></pre>
1
2016-08-02T22:20:35Z
[ "python", "python-3.x", "tkinter" ]
Requested modules not available: vtkRenderingOpenGL-cmake/OpenCVDetectVTK.cmake:6 (find_package)
38,731,358
<p>I am basically trying to install OpenCV3 with Python3.5. I have successfully gone through all the steps in <a href="http://www.pyimagesearch.com/2015/06/29/install-opencv-3-0-and-python-3-4-on-osx/" rel="nofollow">this tutorial</a> for <code>git checkout 3.1.0</code> of opencv. However when I enter this command:</p> <pre><code>cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D PYTHON3_PACKAGES_PATH=~/.virtualenvs/cv3/lib/python3.5/site-packages \ -D PYTHON3_LIBRARY=/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/libpython3.5.dylib \ -D PYTHON3_INCLUDE_DIR=/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/include/python3.5m/ \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D BUILD_EXAMPLES=ON \ -D BUILD_opencv_python3=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules .. </code></pre> <p>I get this error:</p> <pre><code>...etc... -- Checking for module 'gstreamer-base-1.0' -- No package 'gstreamer-base-1.0' found -- Checking for module 'gstreamer-video-1.0' -- No package 'gstreamer-video-1.0' found -- Checking for module 'gstreamer-app-1.0' -- No package 'gstreamer-app-1.0' found -- Checking for module 'gstreamer-riff-1.0' -- No package 'gstreamer-riff-1.0' found -- Checking for module 'gstreamer-pbutils-1.0' -- No package 'gstreamer-pbutils-1.0' found -- Checking for module 'gstreamer-base-0.10' -- No package 'gstreamer-base-0.10' found -- Checking for module 'gstreamer-video-0.10' -- No package 'gstreamer-video-0.10' found -- Checking for module 'gstreamer-app-0.10' -- No package 'gstreamer-app-0.10' found -- Checking for module 'gstreamer-riff-0.10' -- No package 'gstreamer-riff-0.10' found -- Checking for module 'gstreamer-pbutils-0.10' -- No package 'gstreamer-pbutils-0.10' found -- Checking for module 'libdc1394-2' -- No package 'libdc1394-2' found -- Checking for module 'libdc1394' -- No package 'libdc1394' found -- Checking for module 'libv4l1' -- No package 'libv4l1' found -- Checking for module 'libv4l2' -- No package 'libv4l2' found -- Looking for linux/videodev.h -- Looking for linux/videodev.h - not found -- Looking for linux/videodev2.h -- Looking for linux/videodev2.h - not found -- Looking for sys/videoio.h -- Looking for sys/videoio.h - not found -- Checking for module 'libavcodec' -- Found libavcodec, version 57.48.101 -- Checking for module 'libavformat' -- Found libavformat, version 57.41.100 -- Checking for module 'libavutil' -- Found libavutil, version 55.28.100 -- Checking for module 'libswscale' -- Found libswscale, version 4.1.100 -- Checking for module 'libavresample' -- Found libavresample, version 3.0.0 -- Looking for libavformat/avformat.h -- Looking for libavformat/avformat.h - found -- Looking for ffmpeg/avformat.h -- Looking for ffmpeg/avformat.h - not found -- Checking for module 'libgphoto2' -- No package 'libgphoto2' found -- ICV: Removing previous unpacked package: /Users/mona/computer_vision/Face_Recognition/opencv/3rdparty/ippicv/unpack -- ICV: Unpacking ippicv_macosx_20151201.tgz to /Users/mona/computer_vision/Face_Recognition/opencv/3rdparty/ippicv/unpack... -- ICV: Package successfully downloaded -- found IPP (ICV version): 9.0.1 [9.0.1] -- at: /Users/mona/computer_vision/Face_Recognition/opencv/3rdparty/ippicv/unpack/ippicv_osx -- Found Doxygen: /usr/local/bin/doxygen (found version "1.8.11") -- To enable PlantUML support, set PLANTUML_JAR environment variable or pass -DPLANTUML_JAR=&lt;filepath&gt; option to cmake -- Found PythonInterp: /usr/local/bin/python2.7 (found suitable version "2.7.12", minimum required is "2.7") -- Could NOT find PythonLibs: Found unsuitable version "2.7.10", but required is exact version "2.7.12" (found /usr/lib/libpython2.7.dylib) -- Found PythonInterp: /usr/local/bin/python3.4 (found suitable version "3.4.1", minimum required is "3.4") -- Could NOT find PythonLibs: Found unsuitable version "3.5.2", but required is exact version "3.4.1" (found /usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/libpython3.5.dylib) -- Found apache ant 1.9.7: /usr/local/bin/ant -- Found JNI: /System/Library/Frameworks/JavaVM.framework -- Could NOT find Matlab (missing: MATLAB_MEX_SCRIPT MATLAB_INCLUDE_DIRS MATLAB_ROOT_DIR MATLAB_LIBRARIES MATLAB_LIBRARY_DIRS MATLAB_MEXEXT MATLAB_ARCH MATLAB_BIN) CMake Error at /usr/local/Cellar/vtk/7.0.0_1/lib/cmake/vtk-7.0/vtkModuleAPI.cmake:120 (message): Requested modules not available: vtkRenderingOpenGL Call Stack (most recent call first): /usr/local/lib/cmake/vtk-7.0/VTKConfig.cmake:88 (vtk_module_config) cmake/OpenCVDetectVTK.cmake:6 (find_package) CMakeLists.txt:597 (include) </code></pre> <p>I have tried it with both <code>ON</code> and <code>OFF</code> for <code>-D INSTALL_C_EXAMPLES=ON \</code> line still no success. Any feedback is really appreciated!</p> <p>This is the log for flag set to OFF: <a href="http://pastebin.com/NF1bbpBC" rel="nofollow">http://pastebin.com/NF1bbpBC</a></p>
0
2016-08-02T22:16:54Z
38,732,770
<p>It took me a good few hours to get this fixed. Here's what I did:</p> <pre><code>wget https://github.com/Itseez/opencv/archive/3.1.0.zip wget https://github.com/Itseez/opencv_contrib/archive/3.1.0.zip unzip 3.1.0.zip unzip 3.1.0.zip.1 cd opencv-3.1.0 mkdir build cd build cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D BUILD_opencv_java=OFF \ -D WITH_IPP=OFF -D WITH_1394=OFF \ -D WITH_FFMPEG=OFF \ -D BUILD_EXAMPLES=OFF \ -D BUILD_TESTS=OFF \ -D BUILD_PERF_TESTS=OFF \ -D BUILD_DOCS=OFF \ -D BUILD_opencv_python2=ON \ -D BUILD_opencv_python3=ON \ -D BUILD_opencv_video=OFF \ -D BUILD_opencv_videoio=OFF \ -D BUILD_opencv_videostab=OFF \ -D PYTHON_EXECUTABLE=$(which python) \ -D OPENCV_EXTRA_MODULES_PATH=/Users/mona/computer_vision/Face_Recognition/opencv_contrib-3.1.0/modules .. </code></pre> <p>In the last one make sure to have the absolute path not something like <code>-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/opencv_contrib-3.1.0/modules ..</code></p> <p>Also you would need <code>vi cmake/OpenCVDetectVTK.cmake</code> and change line 6 so it has <code>vtkRenderingOpenGL2</code> instead of <code>vtkRenderingOpenGL</code>:</p> <pre><code>6 find_package(VTK QUIET COMPONENTS vtkRenderingOpenGL2 vtkInteractionStyle vtkRenderingLOD vtkIOPLY vtkFiltersTexture vtkRenderingFreeType vtkIOExport NO_MODULE) </code></pre>
1
2016-08-03T01:05:33Z
[ "python", "osx", "opencv", "cmake", "opencv3.0" ]
Unstacking DataFrame with Multiple 'Value' Columns in Python Pandas
38,731,411
<p>Say I have a DataFrame that looks like this:</p> <pre><code> keys sample verify 0 foo a 1 1 bar b 2 2 monty c 3 3 foo d 4 4 bar e 5 5 monty f 6 </code></pre> <p>That I want in this form:</p> <pre><code> foo_1 bar_1 monty_1 foo_2 bar_2 monty_2 0 a b c 1 2 3 1 d e f 4 5 6 </code></pre> <p>What is the best way of unstacking? I have tried both pandas.pivot_table() and the pandas.unstack() function but the pivot table wont work with alphabetic values and the unstack function doesn't work the way I think it should (i.e. inverse of stack). I assume you could unstack column by column and join the dataframes at the end, the problem I am mostly having is with the unstack function and what it is doing. Any thoughts on the best way to do this?</p>
2
2016-08-02T22:22:38Z
38,731,568
<pre><code>df2 = df.set_index('keys').T.reset_index(drop=True) \ .T.groupby(level=0).apply(lambda df: df.reset_index(drop=True)) \ .stack().unstack(1).T df2.columns = df2.columns.set_levels((df2.columns.levels[1] + 1).astype(str), level=1) df2.columns = df2.columns.to_series().str.join('_') df2 </code></pre> <p><a href="http://i.stack.imgur.com/wI6cU.png" rel="nofollow"><img src="http://i.stack.imgur.com/wI6cU.png" alt="enter image description here"></a></p>
2
2016-08-02T22:35:36Z
[ "python", "pandas", "stack", "pivot-table" ]
How do I get this loop to work correctly when writing pandas df to xlsx?
38,731,480
<p>I have used <a href="http://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data">this code</a>, which is kind of working. Right now in the smaller 'rep_list' as it executes the first rep in the list which is CP is adds it, but then when it goes to AM it overwrites the CP. SO right now when I run this code it only actually saves the last person in the loop. If I run the code with just "CP" and then just "AM" it appends it as it should. Is it something wrong with the for loop? or is it an issue with the workbook itself?</p> <pre><code>import pandas as pd import datetime from openpyxl import load_workbook now = datetime.datetime.now() currentDate = now.strftime("%Y-%m-%d") call_report = pd.read_excel("Ending 2016-07-30.xlsx", "raw_data") #rep_list = ["CP", "AM", "JB", "TT", "KE"] rep_list = ["CP", "AM"] def call_log_reader(rep_name): rep_log = currentDate + "-" + rep_name + ".csv" df = pd.read_csv(rep_log) df = df.drop(['From Name', 'From Number', 'To Name / Reference', 'To Number', 'Billing Code', 'Original Dialed Number', 'First Hunt Group', 'Last Hunt Group'], axis=1) df['rep'] = rep_name book = load_workbook('Ending 2016-07-30.xlsx') writer = pd.ExcelWriter('Ending 2016-07-30.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) df.to_excel(writer, "raw_data", index=False) writer.save() ## I tried adding this : writer.close() hoping it would close the book and then force it to reopen for the next rep in the loop but it doesn't seem to work. for rep in rep_list: call_log_reader(rep) </code></pre> <p>Thank you so much!</p> <p>EDIT:</p> <p>Gaurav Dhama gave a great answer that worked excellent. He pointed out that there is a bit of a limitation with the Pandas excelwriter <a href="https://github.com/pydata/pandas/issues/3441" rel="nofollow">(refer to this link)</a> and proposed a solution in which each rep gets their own sheet in the end. This worked, however after I thought on it I opted against the additional sheets and came up with this solution knowing the limitation existed. Basically, I appended a CSV instead of the actual XLSX file, and then at the end opened that CSV and appended the one big list into the XLSX file. Either one works, just depends on what you're final product looks like. </p> <pre><code>import pandas as pd import datetime from openpyxl import load_workbook now = datetime.datetime.now() currentDate = now.strftime("%Y-%m-%d") call_report = "Ending 2016-07-30.xlsx" #rep_list = ["CP", "AM", "JB", "TT", "KE"] rep_list = ["CP", "AM"] csv_to_xl_files = [] merged_csv = currentDate + "-master.csv" def call_log_reader(rep_name): rep_log = currentDate + "-" + rep_name + ".csv" df = pd.read_csv(rep_log) df = df.drop(['TimestampDetail', 'Billing Code', 'From Name', 'From Number', 'To Name / Reference', 'To Number', 'Original Dialed Number', 'First Hunt Group', 'Last Hunt Group'], axis=1) df['rep'] = rep_name #print (df.head(3)) df.to_csv(merged_csv, mode='a', index=False, header=False) csv_to_xl_files.append(rep_log) book = load_workbook(call_report) writer = pd.ExcelWriter(call_report, engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) for rep in rep_list: call_log_reader(rep) master_df = pd.read_csv(merged_csv) master_df.to_excel(writer, "raw_data", index=False) writer.save() #this csv_to_xl_files list isn't finished yet, basically I'm going to use it to delete the files from the directory as I don't need them once the script is run. print (csv_to_xl_files) </code></pre>
0
2016-08-02T22:28:12Z
38,731,785
<p>Try using the following:</p> <pre><code>import pandas as pd import datetime from openpyxl import load_workbook now = datetime.datetime.now() currentDate = now.strftime("%Y-%m-%d") call_report = pd.read_excel("Ending 2016-07-30.xlsx", "raw_data") #rep_list = ["CP", "AM", "JB", "TT", "KE"] rep_list = ["CP", "AM"] def call_log_reader(rep_name): rep_log = currentDate + "-" + rep_name + ".csv" df = pd.read_csv(rep_log) df = df.drop(['From Name', 'From Number', 'To Name / Reference', 'To Number', 'Billing Code', 'Original Dialed Number', 'First Hunt Group', 'Last Hunt Group'], axis=1) df['rep'] = rep_name df.to_excel(writer, "raw_data"+rep, index=False) return df book = load_workbook('Ending 2016-07-30.xlsx') writer = pd.ExcelWriter('Ending 2016-07-30.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) for rep in rep_list: call_log_reader(rep) writer.save() </code></pre>
1
2016-08-02T23:00:24Z
[ "python", "pandas", "openpyxl" ]
How do I get this loop to work correctly when writing pandas df to xlsx?
38,731,480
<p>I have used <a href="http://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data">this code</a>, which is kind of working. Right now in the smaller 'rep_list' as it executes the first rep in the list which is CP is adds it, but then when it goes to AM it overwrites the CP. SO right now when I run this code it only actually saves the last person in the loop. If I run the code with just "CP" and then just "AM" it appends it as it should. Is it something wrong with the for loop? or is it an issue with the workbook itself?</p> <pre><code>import pandas as pd import datetime from openpyxl import load_workbook now = datetime.datetime.now() currentDate = now.strftime("%Y-%m-%d") call_report = pd.read_excel("Ending 2016-07-30.xlsx", "raw_data") #rep_list = ["CP", "AM", "JB", "TT", "KE"] rep_list = ["CP", "AM"] def call_log_reader(rep_name): rep_log = currentDate + "-" + rep_name + ".csv" df = pd.read_csv(rep_log) df = df.drop(['From Name', 'From Number', 'To Name / Reference', 'To Number', 'Billing Code', 'Original Dialed Number', 'First Hunt Group', 'Last Hunt Group'], axis=1) df['rep'] = rep_name book = load_workbook('Ending 2016-07-30.xlsx') writer = pd.ExcelWriter('Ending 2016-07-30.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) df.to_excel(writer, "raw_data", index=False) writer.save() ## I tried adding this : writer.close() hoping it would close the book and then force it to reopen for the next rep in the loop but it doesn't seem to work. for rep in rep_list: call_log_reader(rep) </code></pre> <p>Thank you so much!</p> <p>EDIT:</p> <p>Gaurav Dhama gave a great answer that worked excellent. He pointed out that there is a bit of a limitation with the Pandas excelwriter <a href="https://github.com/pydata/pandas/issues/3441" rel="nofollow">(refer to this link)</a> and proposed a solution in which each rep gets their own sheet in the end. This worked, however after I thought on it I opted against the additional sheets and came up with this solution knowing the limitation existed. Basically, I appended a CSV instead of the actual XLSX file, and then at the end opened that CSV and appended the one big list into the XLSX file. Either one works, just depends on what you're final product looks like. </p> <pre><code>import pandas as pd import datetime from openpyxl import load_workbook now = datetime.datetime.now() currentDate = now.strftime("%Y-%m-%d") call_report = "Ending 2016-07-30.xlsx" #rep_list = ["CP", "AM", "JB", "TT", "KE"] rep_list = ["CP", "AM"] csv_to_xl_files = [] merged_csv = currentDate + "-master.csv" def call_log_reader(rep_name): rep_log = currentDate + "-" + rep_name + ".csv" df = pd.read_csv(rep_log) df = df.drop(['TimestampDetail', 'Billing Code', 'From Name', 'From Number', 'To Name / Reference', 'To Number', 'Original Dialed Number', 'First Hunt Group', 'Last Hunt Group'], axis=1) df['rep'] = rep_name #print (df.head(3)) df.to_csv(merged_csv, mode='a', index=False, header=False) csv_to_xl_files.append(rep_log) book = load_workbook(call_report) writer = pd.ExcelWriter(call_report, engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) for rep in rep_list: call_log_reader(rep) master_df = pd.read_csv(merged_csv) master_df.to_excel(writer, "raw_data", index=False) writer.save() #this csv_to_xl_files list isn't finished yet, basically I'm going to use it to delete the files from the directory as I don't need them once the script is run. print (csv_to_xl_files) </code></pre>
0
2016-08-02T22:28:12Z
38,736,670
<p>If you use openpyxl 2.4 then you can <a href="http://openpyxl.readthedocs.io/en/latest/pandas.html" rel="nofollow">work with Pandas dataframes in directly in openpyxl</a>.</p>
0
2016-08-03T07:07:43Z
[ "python", "pandas", "openpyxl" ]
Add custom legend to bokeh Bar
38,731,491
<p>I have pandas series as:</p> <pre><code>&gt;&gt;&gt; etypes 0 6271 1 6379 2 399 3 110 4 4184 5 1987 </code></pre> <p>And I want to draw Bar chart in Bokeh: <code>p = Bar(etypes)</code>. However for legend I get just <code>etypes</code> index number, which I tried to decrypt with this dictionary:</p> <pre><code>legend = { 0: 'type_1', 1: 'type_2', 2: 'type_3', 3: 'type_4', 4: 'type_5', 5: 'type_6', } </code></pre> <p>by passing it to label argument: <code>p = Bar(etypes, label=legend)</code>, but it didn't work. Also passing the <code>list(legend.values())</code> does not work.</p> <p>Any ideas how to add custom legend on pandas series in bokeh Bar chart?</p>
2
2016-08-02T22:29:21Z
38,731,759
<p>Convert the series to a DataFrame, add the legend as a new column and then reference that column name in quotes for label. For example, if you call your DataFrame 'etypes', data column 'values', and your legend column 'legend':</p> <pre><code>p = Bar(etypes, values='values', label='legend') </code></pre> <p>If you absolutely must use a series, you can pass the series into a data object and then pass that to bokeh. For example:</p> <pre><code>legend = ['type1', 'type2', 'type3', 'type4', 'type5', 'type6'] data = { 'values': etypes 'legend': legend } p = Bar(data, values='values', label='legend') </code></pre>
1
2016-08-02T22:57:59Z
[ "python", "pandas", "bokeh" ]
Django: How to call a function once a button is clicked?
38,731,497
<p>I have a method written in my views.py that sends a sub-process command.</p> <p>I want to be able to click a button on my Django application and it initiates the method I wrote.</p> <p>How can I do this?</p> <p>This is currently my function in my views.py</p> <pre><code> def send_command(request): output = subprocess.check_output('ls', shell=True) print(output) return render(request, 'button.html') </code></pre> <p>I also have a button in a .html file</p> <pre><code> &lt;center&gt;&lt;button type='submit' class='btn btn-lg'&gt;Button&lt;/button&gt;&lt;/center&gt; </code></pre> <p>I'm VERY new to this so but any help would be appreciated. Please feel free to ask for more info. </p>
0
2016-08-02T22:29:54Z
38,731,991
<p>If you are not sending content which will be saved in the server you could change your button to behave like a url</p> <p>url.py</p> <pre><code>from views import send_command urlpatterns = [ url(r'^send_command$', send_command, name='send_command'), ] </code></pre> <p>html</p> <pre><code>&lt;a href="{% url 'send_command' %}" class='btn btn-lg'&gt;Button&lt;/a&gt; </code></pre>
0
2016-08-02T23:25:07Z
[ "python", "html", "django", "methods", "views" ]
Recursively replace characters in string using Python
38,731,503
<pre><code>def replaceChar(myString, oldChar, newChar): # if myString has no characters left, return newString if myString == '': return newString elif myString[0] == oldChar: # then add newChar to newString else: # then add myString[0] to newString # Chop the first character off of myString myString = myString[1:] # recurse replaceChar(myString, oldChar, newChar) </code></pre> <p>Since strings are immutable, I can't add newChar or oldChar to newString. I can't make newString a list, because it will get overwritten with each recursive loop. I also can't define that list outside of the function because the rules state that everything must be inside the function. How can I add these characters to my new string?</p>
0
2016-08-02T22:30:19Z
38,731,761
<p>Obviously you would never actually use a recursive solution like this for this type of problem, but here it is anyway:</p> <pre><code>def replaceChar(inval, old, new): if inval == '': return '' if inval[0] == old: return new + replaceChar(inval[1:], old, new) return inval[0] + replaceChar(inval[1:], old, new) </code></pre> <p>And</p> <pre><code>print(replaceChar('Do you have some sample input', 'o', 'X')) </code></pre> <p>yields</p> <pre><code>DX yXu have sXme sample input </code></pre>
1
2016-08-02T22:58:00Z
[ "python", "recursion" ]
Fastest Way to Compress Video Size Using Library or Algo
38,731,535
<p>I'm trying to compress high quality video into less size and I'm able to reduce the size of video that I've compressed using the following objective-c code:</p> <pre><code> - (BOOL)convertMovieToMP4:(NSString ) originalMovPath andStoragePath:(NSString ) compMovPath { NSURL *tmpSourceUrl = [NSURL fileURLWithPath:originalMovPath]; compMovPath = [compMovPath stringByReplacingOccurrencesOfString:[compMovPath pathExtension] withString:@"mp4"]; NSURL *tmpDestUrl = [NSURL fileURLWithPath:compMovPath]; AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:tmpSourceUrl options:nil]; AVMutableComposition* mixComposition = [AVMutableComposition composition]; AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid]; AVAssetTrack *clipVideoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]; [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:clipVideoTrack atTime:kCMTimeZero error:nil]; [compositionVideoTrack setPreferredTransform:[[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] preferredTransform]]; CGSize videoSize = [[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize]; CATextLayer *titleLayer = [CATextLayer layer]; titleLayer.string = @"Ojatro"; titleLayer.font = (_bridge CFTypeRef Nullable)(@"Helvetica"); titleLayer.fontSize = videoSize.height / 8; titleLayer.shadowOpacity = 0.2; titleLayer.alignmentMode = kCAAlignmentCenter; titleLayer.bounds = CGRectMake(0, 0, videoSize.width, videoSize.height / 6); titleLayer.position=CGPointMake(videoSize.width/2, videoSize.height/2); CALayer *parentLayer = [CALayer layer]; CALayer *videoLayer = [CALayer layer]; parentLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height); videoLayer.frame = CGRectMake(0, 0, videoSize.width, videoSize.height); [parentLayer addSublayer:videoLayer]; [parentLayer addSublayer:titleLayer]; AVMutableVideoComposition* videoComp = [AVMutableVideoComposition videoComposition]; videoComp.renderSize = videoSize; videoComp.frameDuration = CMTimeMake(1, 30); videoComp.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer]; AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction]; instruction.timeRange = CMTimeRangeMake(kCMTimeZero, [mixComposition duration]); AVAssetTrack *videoTrack = [[mixComposition tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]; AVMutableVideoCompositionLayerInstruction* layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack]; instruction.layerInstructions = [NSArray arrayWithObject:layerInstruction]; videoComp.instructions = [NSArray arrayWithObject: instruction]; AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetMediumQuality];//AVAssetExportPresetPasst _assetExport.videoComposition = videoComp; //NSString* videoName = @"mynewwatermarkedvideo.mov"; NSString *tmpDirPath = [compMovPath stringByReplacingOccurrencesOfString:[compMovPath lastPathComponent] withString:@""]; if ([Utility makeDirectoryAtPath:tmpDirPath]) { NSLog(@"Directory Created"); } //exportPath=[exportPath stringByAppendingString:videoName]; NSURL *exportUrl = tmpDestUrl; if ([[NSFileManager defaultManager] fileExistsAtPath:compMovPath]) { [[NSFileManager defaultManager] removeItemAtPath:compMovPath error:nil]; } _assetExport.outputURL = exportUrl; _assetExport.shouldOptimizeForNetworkUse = YES; _assetExport.outputFileType = AVFileTypeMPEG4; //[strRecordedFilename setString: exportPath]; [_assetExport exportAsynchronouslyWithCompletionHandler: ^(void ) { switch (_assetExport.status) { case AVAssetExportSessionStatusUnknown: NSLog(@"Export Status Unknown"); break; case AVAssetExportSessionStatusWaiting: NSLog(@"Export Waiting"); break; case AVAssetExportSessionStatusExporting: NSLog(@"Export Status"); break; case AVAssetExportSessionStatusCompleted: NSLog(@"Export Completed"); totalFilesCopied++; [self startProgressBar]; break; case AVAssetExportSessionStatusFailed: NSLog(@"Export failed"); break; case AVAssetExportSessionStatusCancelled: NSLog(@"Export canceled"); break; } } ]; return NO; } </code></pre> <p>But my main problem is that when I compress the 500MB video (i.e average video) file and it takes approximately 20 to 30+ minutes. It reduce the video size to approximately 130MB. I'm using the Native AVFoundation Library to compress the video to reduce its size.</p> <p>I need to compress the video size very fast just like Apple Compressor application, it compresses the 500MB file within 30 seconds only...</p> <p><a href="https://itunes.apple.com/en/app/compressor/id424390742?mt=12">https://itunes.apple.com/en/app/compressor/id424390742?mt=12</a></p> <p>I've also used FFMPEG library for that, but that is also slow I did not found that library anymore useful. </p> <p>I've also tried to find the solution using other languages like, java, python. but did not found any solution was found.</p> <p>If anyone has the solution for this particular problem, or has some libraries (i.e Paid library or Open Source Library) that can do the compression with less time at least 1 minute... Please do share with me. Or some other piece of code that can overcome the compression time problem from 20 - 30 minutes to at least 1 minute.</p> <p>Thanks...</p>
8
2016-08-02T22:33:35Z
38,745,037
<p>Here is a document, which contains some RnD on video compression: <a href="https://drive.google.com/file/d/0BySTUFVtfzJmM3pYeVRiWmxSLVU/view" rel="nofollow">https://drive.google.com/file/d/0BySTUFVtfzJmM3pYeVRiWmxSLVU/view</a></p> <p>It also contains a sample code for quick compression of videos in objective-C. It uses <code>AVAssetExportSession</code> for compressing videos.</p>
2
2016-08-03T13:28:45Z
[ "java", "python", "objective-c", "osx", "ffmpeg" ]
PyQt4 button click registering multiple times when clicked
38,731,543
<p>I am new to PyQt4 and after several searches I have not found info on the issue I am seeing in my GUI.</p> <p>The issue is that when a user clicks on getSingleItems button, the function runs the same amount of times that the user has clicked getAllItems. An example is if the user clicks getAllItems to populate the items field, and then they click on getSingleItem, getitems runs once and they will get the result printed once per expectation. But if the user selects another item from list and clicks on getAllItems again, then on getSingleItem, the results is that getitem runs 2x and therefore prints 2x. This increments with each run through so clicking getAllItems 4x, even without changing selection, then clicking getitem will run 4x with a single click on getSingleItem. Only way to refresh it is to close the GUI and reopen. Any help is appreciated.</p> <pre><code>class UpdateItem(QDialog, updateitem_ui.Ui_updateitem): def __init__(self): QDialog.__init__(self) self.setupUi(self) tests = ['Test1', 'Test2', 'Test3'] self.list.addItems(tests) self.exit.clicked.connect(self.close) self.setFocus() self.getAllItems.clicked.connect(self.getitems) def getitems(self): self.items.clear() self.items.addItems(self.list.currentText()) self.getSingleItem.clicked.connect(self.getitem) def getitem(self): self.item_id = self.items.currentText() print(self.item_id) app = QApplication(sys.argv) gui = UpdateItem() gui.show() app.exec_() </code></pre>
0
2016-08-02T22:34:02Z
38,731,931
<p>Apparently you are are adding new connection to <code>getSingleItem.clicked</code> in each run of <code>getitems</code>, so the <code>clicked</code> signal gets connected multiple times to the same slot, which causes the behaviour you observe. </p> <p>Moving the line </p> <pre><code>self.getSingleItem.clicked.connect(self.getitem) </code></pre> <p>from <code>getitems</code> to <code>__init__</code> should fix the issue, I guess.</p>
1
2016-08-02T23:18:17Z
[ "python", "user-interface", "pyqt4" ]
How to update my forks of Evernote SDK for Python to track latest updates?
38,731,556
<p>First of all, I'm hoping that Evernote will start maintaining its Python SDK (<a href="https://github.com/evernote/evernote-sdk-python" rel="nofollow">evernote/evernote-sdk-python for Python 2</a> and <a href="https://github.com/evernote/evernote-sdk-python3" rel="nofollow">evernote/evernote-sdk-python3 for Python 3</a>). In the meantime, I'm looking for advice on how to update my forks of these SDK to bring them up-to-speed with the latest changes in the <a href="https://dev.evernote.com/doc/reference/" rel="nofollow">Evernote API</a>. Specifically:</p> <ol> <li><p>Can someone from Evernote indicate whether these SDKs will be supported or are we on our own?</p></li> <li><p>For <a href="https://github.com/evernote/evernote-sdk-python" rel="nofollow">evernote/evernote-sdk-python for Python 2</a>, it looks like a good place to start is to merge the <a href="https://github.com/matthewayne/evernote-sdk-python" rel="nofollow">matthewayne/evernote-sdk-python</a> fork and then pick and choose from the <a href="https://github.com/evernote/evernote-sdk-python/pulls" rel="nofollow">outstanding pull requests</a>. Has someone already gone down this path?</p></li> <li><p>For (<a href="https://github.com/evernote/evernote-sdk-python" rel="nofollow">https://github.com/evernote/evernote-sdk-python</a>) and <a href="https://github.com/evernote/evernote-sdk-python3" rel="nofollow">evernote/evernote-sdk-python3 for Python 3</a>), has anyone tried <a href="https://github.com/evernote/evernote-sdk-python3/pull/11/files" rel="nofollow">Merge latest python2 sdk by ahxxm · Pull Request #11 · evernote/evernote-sdk-python3</a>?</p></li> <li><p>Where can I find the latest Thrift IDL files for Evernote? <a href="https://github.com/evernote/evernote-thrift" rel="nofollow">evernote/evernote-thrift: Thrift IDL files for the Evernote Cloud API</a> hasn't been updated since June 2013 (to match version 1.25 of the Evernote API. (Are we up to <a href="https://github.com/matthewayne/evernote-sdk-python/commit/2cf00691aec81ea94b3ed401af8a8d4660986080" rel="nofollow">version 1.28</a> at the very least of the API?) BTW, what is the current version number of the API?</p></li> <li><p>How do I go about compiling the Thrift IDL files into Python code for the Evernote SDK? </p></li> </ol> <p>Thanks in advance!</p>
1
2016-08-02T22:34:47Z
38,732,275
<p>We haven't put too much work into our SDKs lately but we're hoping to change that in the coming weeks. As a first step we (finally) updated our <a href="https://dev.evernote.com/doc/reference/" rel="nofollow">API reference</a> (another, minor update coming soon) and the next step is our SDKs. There's a lot of work to do here, since we have SDKs for quite a few languages, and the few of us that are working on this stuff are doing so in between core product work. Part of that is adding newly generated thrift files, so you shouldn't need to worry about that.</p> <p>Thank you for your patience!</p>
1
2016-08-02T23:56:39Z
[ "python", "evernote" ]
Adding scss file type to new context menu of PyCharm
38,731,597
<p>The JetBrains IDE PyCharm supports scss files, but I can't figure out how to add it to the "New" context menu that pops up when right-clicking the directory where I want to add the file. I see alot of other file types, and looking at registering a new file type, I see scss is already there. But I can't figure out how to add it to the "New" context menu.</p> <p>Any suggestions would be greatly appreciated.</p> <p>Thanks!</p> <p>Doug </p>
0
2016-08-02T22:39:06Z
38,791,478
<p>New SCSS files can be created via <code>File/New/Stylesheeet</code>. But you can create your own SCSS file template in <code>Preferences | Editor | File and code templates</code> (see <a href="https://www.jetbrains.com/help/pycharm/2016.1/creating-and-editing-file-templates.html" rel="nofollow">https://www.jetbrains.com/help/pycharm/2016.1/creating-and-editing-file-templates.html</a>) - new templates will appear in <code>File/New</code> menu.</p>
1
2016-08-05T14:17:48Z
[ "python", "sass", "pycharm", "jetbrains" ]
Pad the exponential index with zeros
38,731,609
<p>Let's say I have a double precision value</p> <pre><code>a = 1.5838619160273860E-021 </code></pre> <p>Is there a way to create a string <code>b</code></p> <pre><code>b = '1.5838619160273860E-021' </code></pre> <p>Note the index has three digits here <code>E-021</code> instead of <code>E-21</code>. I know <code>format(int, '0.16f')</code> can control the decimal place, but no idea how to manipulate the index.</p> <p>Any input will be appreciated</p>
1
2016-08-02T22:40:23Z
38,732,242
<p>You need another case for when its +21 instead of -21</p> <pre><code>&gt;&gt;&gt; x = '1.5838619160273860E-21' &gt;&gt;&gt; a,b = x.split('E-') &gt;&gt;&gt; 'E-'.join((a,b.zfill(3))) '1.5838619160273860E-021' </code></pre>
0
2016-08-02T23:51:59Z
[ "python" ]
How to flatten a dictionary with nested sequences into a single sequence with all values and keys?
38,731,614
<p>I have a workable solution that returns a set:</p> <pre><code>&gt;&gt;&gt; a = {'a': {'1', '2', '3'}, 'b': {'4', '5', '6'}, 'c': {'7', '8', '9'}} &gt;&gt;&gt; def flatten_nested(a): temp = set( [value for value_set in a.values() for value in value_set] ) return temp | a.keys() &gt;&gt;&gt; flatten_nested(a) &gt;&gt;&gt; {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c'} </code></pre> <p>I wondered if there was some <code>itertools.chain</code>-like function already built in to Python to do something similar?</p>
2
2016-08-02T22:40:56Z
38,731,658
<p>I guess more simple is this:</p> <pre><code>&gt;&gt;&gt; set.union(set(a), *a.values()) {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c'} </code></pre> <p>Or, here's the same thing via the bound method:</p> <pre><code>&gt;&gt;&gt; set(a).union(*a.values()) {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c'} </code></pre>
3
2016-08-02T22:45:51Z
[ "python" ]
How to flatten a dictionary with nested sequences into a single sequence with all values and keys?
38,731,614
<p>I have a workable solution that returns a set:</p> <pre><code>&gt;&gt;&gt; a = {'a': {'1', '2', '3'}, 'b': {'4', '5', '6'}, 'c': {'7', '8', '9'}} &gt;&gt;&gt; def flatten_nested(a): temp = set( [value for value_set in a.values() for value in value_set] ) return temp | a.keys() &gt;&gt;&gt; flatten_nested(a) &gt;&gt;&gt; {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c'} </code></pre> <p>I wondered if there was some <code>itertools.chain</code>-like function already built in to Python to do something similar?</p>
2
2016-08-02T22:40:56Z
38,731,757
<p>If the values are already sets then <a href="http://stackoverflow.com/a/38731658/2141635">wims answer</a> is the simplest, but to work for iterables like a list, tuples etc.. you would have to map to a set i.e <code>set(a).union(map(set, a.values())</code> or you could union the <a href="https://docs.python.org/3/library/itertools.html#itertools.chain" rel="nofollow">chain</a> of all the values with the view of the keys:</p> <pre><code>from itertools import chain def flatten_nested(a): return a.keys() | chain(*a.values()) # a.viewkeys() python2 </code></pre>
1
2016-08-02T22:57:54Z
[ "python" ]
Google App Engine - Issue authenticating deployed version of app
38,731,779
<p>I built a simple python application to be run on the Google App Engine. Code:</p> <pre><code>import webapp2 from oauth2client.contrib.appengine import AppAssertionCredentials from apiclient.discovery import build from googleapiclient import discovery from oauth2client.client import GoogleCredentials class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.write('BigQuery App') credentials = AppAssertionCredentials( 'https://www.googleapis.com/auth/sqlservice.admin') service = discovery.build('bigquery', 'v2', credentials=credentials) projectId = '&lt;Project-ID&gt;' query_request_body = { "query": "SELECT a from Data.test LIMIT 10" } request = service.jobs().query(projectId=projectId, body=query_request_body) response = request.execute() self.response.write(response) app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True) </code></pre> <p>I am able to deploy this code locally (<a href="http://localhost:8080" rel="nofollow">http://localhost:8080</a>) and everything works correctly, however I get the following error 500 Server Error when I try to deploy it to GAE using:</p> <pre><code>appcfg.py -A &lt;Project-Id&gt; -V v1 update . </code></pre> <p>This is the error I get from the Error Report Console:</p> <pre><code>error: An error occured while connecting to the server: DNS lookup failed for URL:http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/https://www.googleapis.com/auth/sqlservice.admin/?recursive=True </code></pre> <p>I believe it is an auth issue and to make sure my service account was authorized I went through the gcloud authentification for service accounts and I also set the set environment variables from the SDK.</p> <p>I have been trying to get around this for a while, any pointers are very appreciated. Thank you.</p> <p>Also, I have been using Service Account Auth by following these docs: <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount" rel="nofollow">https://developers.google.com/identity/protocols/OAuth2ServiceAccount</a> where it says that I shouldn't be able to run AppAsseritionCredenitals locally, which adds to my confusion because I actually can with no errors.</p> <p>EDIT: </p> <p>After reuploading and reauthorizing my service account I was able to connect to the server. However, the authorization error continues with this:</p> <pre><code>HttpError: &lt;HttpError 403 when requesting https://www.googleapis.com/bigquery/v2/projects/sqlserver-1384/queries?alt=json returned "Insufficient Permission"&gt; </code></pre>
0
2016-08-02T22:59:45Z
38,732,504
<p>To fix the "error while connecting to the server", follow the instructions listed in this answer: <a href="http://stackoverflow.com/questions/31651973/default-credentials-in-google-app-engine-invalid-credentials-error#_=_">http://stackoverflow.com/questions/31651973/default-credentials-in-google-app-engine-invalid-credentials-error#<em>=</em></a> and then re-upload the app</p> <p>Then, to fix the HttpError 403 when requesting ... returned "Insufficient Permission", you have to change the scope you were requesting. In my case I was requesting: </p> <pre><code>credentials = AppAssertionCredentials( 'https://www.googleapis.com/auth/sqlservice.admin') </code></pre> <p>however, the correct scope for Google BigQuery is: <a href="https://www.googleapis.com/auth/bigquery" rel="nofollow">https://www.googleapis.com/auth/bigquery</a>. Which looks like this:</p> <pre><code>credentials = AppAssertionCredentials( 'https://www.googleapis.com/auth/bigquery') </code></pre> <p>If you are using a different API, use whichever scope is outlined in the documentations.</p>
0
2016-08-03T00:28:43Z
[ "python", "google-app-engine", "google-api", "google-bigquery" ]
Where to Run Scripts at a PyCharm Debugger Breakpoint?
38,731,788
<p>When running the PyCharm debugger and having stopped at a break point, is there a console to run and display some computation with the local variable exposed to me?</p> <p>What I have in mind is the debugger setup in Matlab, where when stopped at a break point in a function, one can run scripts using the variables inside the function.</p>
1
2016-08-02T23:00:40Z
38,740,819
<p>If I have understood well what do you mean, yes, PyCharm provides you a console where you can run local scripts or just see the variable's value at breakpoint time.</p> <p>Start PyCharm debugger and at the bottom of your window you should see the main console.</p> <p>You have to press a botton named "Show Python Prompt". Now, you should be able to write in console.</p> <p>Look at the picture for more details.</p> <p><a href="http://i.stack.imgur.com/tlbUY.png" rel="nofollow"><img src="http://i.stack.imgur.com/tlbUY.png" alt="enter image description here"></a></p>
1
2016-08-03T10:20:12Z
[ "python", "pycharm" ]
Where to Run Scripts at a PyCharm Debugger Breakpoint?
38,731,788
<p>When running the PyCharm debugger and having stopped at a break point, is there a console to run and display some computation with the local variable exposed to me?</p> <p>What I have in mind is the debugger setup in Matlab, where when stopped at a break point in a function, one can run scripts using the variables inside the function.</p>
1
2016-08-02T23:00:40Z
38,767,434
<p>You can use <a href="https://www.jetbrains.com/help/pycharm/2016.1/adding-editing-and-removing-watches.html" rel="nofollow"><code>Evaluate Expression</code></a> and <a href="https://www.jetbrains.com/help/pycharm/2016.1/adding-editing-and-removing-watches.html" rel="nofollow"><code>Watches</code></a> features to run code while debugging.</p>
1
2016-08-04T12:31:40Z
[ "python", "pycharm" ]
Complex matrix in Python
38,731,796
<p>I have a problem with this Python code:</p> <pre><code>A = np.zeros((2*M + 2,nt)) A[1, :] = d[0,0] * np.ones((1,nt)) </code></pre> <p>where <code>d[0,0]</code> is complex. I received this error:</p> <pre><code>ComplexWarning: Casting complex values to real discards the imaginary part </code></pre> <p>during </p> <pre><code>A[1, :] = d[0,0] * np.ones((1,nt)) </code></pre>
0
2016-08-02T23:01:45Z
38,731,862
<p>This is because by default <code>numpy</code> array holds zeros which is <code>int</code> type and you are trying to assign a complex array to integer array. If you write <code>A = np.zeros((2*M+2, nt), dtype=np.complex)</code> it should fix the problem. <code>dtype</code> parameter basically tells numpy to cast elements complex 0 which is actually <code>0+0.j</code>.</p>
0
2016-08-02T23:09:28Z
[ "python", "python-2.7", "python-3.x" ]
Complex matrix in Python
38,731,796
<p>I have a problem with this Python code:</p> <pre><code>A = np.zeros((2*M + 2,nt)) A[1, :] = d[0,0] * np.ones((1,nt)) </code></pre> <p>where <code>d[0,0]</code> is complex. I received this error:</p> <pre><code>ComplexWarning: Casting complex values to real discards the imaginary part </code></pre> <p>during </p> <pre><code>A[1, :] = d[0,0] * np.ones((1,nt)) </code></pre>
0
2016-08-02T23:01:45Z
38,731,921
<p>Are you trying to compute a <em>complex</em> valued array <code>A</code>, or a <em>real</em> valued array <code>A</code>? If the former, then declare <code>A</code> as:</p> <pre><code>A = np.zeros((2*M + 2,nt), dtype=complex) </code></pre> <p>Otherwise, cast your complex value <code>d[0, 0]</code> to a real using:</p> <pre><code>A[1, :] = (1+4j).real * np.ones((1,1)) </code></pre>
0
2016-08-02T23:17:32Z
[ "python", "python-2.7", "python-3.x" ]
I have a nested if statement and the inside statement nullifies the outter
38,731,820
<pre><code>board=[[1,0,8,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] def move(): while board[0][6]!= 0 and board[1][6]!=0 and board[2][6]!=0 and board[3][6]!=0: user_choice= int(raw_input('&gt;')) for lists in board: for i in range(len(lists)): if lists[i]== user_choice-1 and lists[i+1]==0: lists[i+1]= user_choice print print_board(board) for a in board: for i in range(len(a)): if a[i]==user_choice: a[i]=0 print print_board(board) </code></pre> <p>I am making a game where the user inputs a number (user_choice). The program will find the number 1 smaller than user_choice. Say the user picks 8, the game will find the number 7 on the board and if the number after 7 is 0 the program swaps the location of the 0 and the 8. </p> <p>The code I have works except when the second if statement runs the output undoes the first if statement</p> <p>here is a typical output for user_choice=8:</p> <pre><code>[[1,0,8,5,12,16,24],[7,8,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] None [[1,0,8,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] None [[1,0,0,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] </code></pre> <p>The first output replaced the 0 after the 7 with an 8.<br> The second output seems to show the initial board.<br> The third output replaces the 8 in the initial board with a 0. </p> <p>I want one output that both replaces the 0 after the 7 with an 8 and replaces the initial 8 with a 0.</p>
2
2016-08-02T23:04:16Z
38,731,961
<p>Change the order in which you edit the board. First replace any other '8's by zero, then change the zero after a 7 to an 8.</p> <pre><code> for i in range(len(lists)-1): if lists[i]== user_choice-1 and lists[i+1]==0: for a in board: for j in range(len(a)): if a[j]==user_choice: a[j]=0 print print_board(board) lists[i+1]= user_choice print print_board(board) </code></pre> <p>I've also used different variables i, and j and tried to avoid an <code>IndexError</code>, if <code>i+1 == len(lists)</code> </p> <p>Order of operations is significant here. If you start by replacing the 0 following a 7 by an 8, and then replace all 8s by 0s, the overall effect is to replace the 0 following a 7 by a 0. Not what you want</p> <p>If you change the other 8s to zeros first, and then change the zero after a 7 to an 8, the overall effect is what you want.</p> <p>I think that there may still be bugs here.. For example, can there be more than one 7 followed by an 0? What happens if there is a 7 followed by an 8 already on the board? Solving these bugs means thinking very carefully about exactly what you want the computer to do, since it won't do the thinking for you!</p>
0
2016-08-02T23:21:25Z
[ "python", "if-statement" ]
I have a nested if statement and the inside statement nullifies the outter
38,731,820
<pre><code>board=[[1,0,8,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] def move(): while board[0][6]!= 0 and board[1][6]!=0 and board[2][6]!=0 and board[3][6]!=0: user_choice= int(raw_input('&gt;')) for lists in board: for i in range(len(lists)): if lists[i]== user_choice-1 and lists[i+1]==0: lists[i+1]= user_choice print print_board(board) for a in board: for i in range(len(a)): if a[i]==user_choice: a[i]=0 print print_board(board) </code></pre> <p>I am making a game where the user inputs a number (user_choice). The program will find the number 1 smaller than user_choice. Say the user picks 8, the game will find the number 7 on the board and if the number after 7 is 0 the program swaps the location of the 0 and the 8. </p> <p>The code I have works except when the second if statement runs the output undoes the first if statement</p> <p>here is a typical output for user_choice=8:</p> <pre><code>[[1,0,8,5,12,16,24],[7,8,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] None [[1,0,8,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] None [[1,0,0,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] </code></pre> <p>The first output replaced the 0 after the 7 with an 8.<br> The second output seems to show the initial board.<br> The third output replaces the 8 in the initial board with a 0. </p> <p>I want one output that both replaces the 0 after the 7 with an 8 and replaces the initial 8 with a 0.</p>
2
2016-08-02T23:04:16Z
38,732,084
<p>Not the most elegant solution in the world, but here is mine:</p> <pre><code>board = [ [1, 0, 8, 5, 12, 16, 24], [7, 0, 6, 2, 20, 4, 18], [13, 0, 9, 10, 22, 23, 17], [19, 0, 11, 3, 14, 15, 21] ] def print_board(): for row in board: print " ".join("{:2}".format(x) for x in row) while any(row[6] for row in board): print_board() user_choice = int(raw_input('-&gt; ')) replace_match = False for i, row in enumerate(board): pairs = zip(row, row[1:]) for j, pair in enumerate(pairs): if pair == (user_choice - 1, 0): board[i][j+1] = user_choice replace_match = (i, j+1) print pair break else: if replace_match: for i, row in enumerate(board): board[i] = [x if (x != user_choice or (i, j) == replace_match) else 0 for j, x in enumerate(row)] </code></pre>
0
2016-08-02T23:34:50Z
[ "python", "if-statement" ]
I have a nested if statement and the inside statement nullifies the outter
38,731,820
<pre><code>board=[[1,0,8,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] def move(): while board[0][6]!= 0 and board[1][6]!=0 and board[2][6]!=0 and board[3][6]!=0: user_choice= int(raw_input('&gt;')) for lists in board: for i in range(len(lists)): if lists[i]== user_choice-1 and lists[i+1]==0: lists[i+1]= user_choice print print_board(board) for a in board: for i in range(len(a)): if a[i]==user_choice: a[i]=0 print print_board(board) </code></pre> <p>I am making a game where the user inputs a number (user_choice). The program will find the number 1 smaller than user_choice. Say the user picks 8, the game will find the number 7 on the board and if the number after 7 is 0 the program swaps the location of the 0 and the 8. </p> <p>The code I have works except when the second if statement runs the output undoes the first if statement</p> <p>here is a typical output for user_choice=8:</p> <pre><code>[[1,0,8,5,12,16,24],[7,8,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] None [[1,0,8,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] None [[1,0,0,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] </code></pre> <p>The first output replaced the 0 after the 7 with an 8.<br> The second output seems to show the initial board.<br> The third output replaces the 8 in the initial board with a 0. </p> <p>I want one output that both replaces the 0 after the 7 with an 8 and replaces the initial 8 with a 0.</p>
2
2016-08-02T23:04:16Z
38,732,213
<p>I think you will find things easier if you break the problem into smaller functions. Here a simple example:</p> <pre><code>board = [[1,0,8,5,12,16,24],[7,0,6,2,20,4,18],[13,0,9,10,22,23,17],[19,0,11,3,14,15,21]] # See if item is in lst. If so, return xy location def in_list(item, lst): for i in range(0, len(lst)): for j in range(0, len(lst[i])): if lst[i][j] == item: return i, j return -1,-1 def print_board(): for i in board: for j in i: print j, ' ', print def game_over(): return board[0][6] == 0 and board[1][6] == 0 and board[2][6] == 0 and board[3][6] == 0 while (False == game_over()): print_board() user_choice = int(input("Enter a number: ")) # ux,uy are co-ords of user choice ux, uy = in_list(user_choice, board) if (-1 != ux): # mx,my are co-ords of user choice+1 mx, my = in_list(user_choice - 1, board) if (-1 != mx): if (0 == board[mx][my + 1]): board[ux][ux] = 0 board[mx][my + 1] = user_choice </code></pre>
0
2016-08-02T23:48:28Z
[ "python", "if-statement" ]
How to get a random (bootstrap) sample from pandas multiindex
38,731,858
<p>I'm trying to create a bootstrapped sample from a multiindex dataframe in Pandas. Below is some code to generate the kind of data I need.</p> <pre><code>from itertools import product import pandas as pd import numpy as np df = pd.DataFrame({'group1': [1, 1, 1, 2, 2, 3], 'group2': [13, 18, 20, 77, 109, 123], 'value1': [1.1, 2, 3, 4, 5, 6], 'value2': [7.1, 8, 9, 10, 11, 12] }) df = df.set_index(['group1', 'group2']) print df </code></pre> <p>The df dataframe looks like:</p> <pre><code> value1 value2 group1 group2 1 13 1.1 7.1 18 2.0 8.0 20 3.0 9.0 2 77 4.0 10.0 109 5.0 11.0 3 123 6.0 12.0 </code></pre> <p>I want to get a random sample from the first index. For example let's say the random values <code>np.random.randint(3,size=3)</code> produces [3,2,2]. I'd like the resultant dataframe to look like:</p> <pre><code> value1 value2 group1 group2 3 123 6.0 12.0 2 77 4.0 10.0 109 5.0 11.0 2 77 4.0 10.0 109 5.0 11.0 </code></pre> <p>I've spent a lot of time researching this and I've been unable to find a similar example where the multiindex values are integers, the secondary index is of variable length, and the primary index samples are repeating. This is how I think an appropriate implementation for bootstrapping would work.</p>
3
2016-08-02T23:08:31Z
38,732,215
<p>Try:</p> <pre><code>df.unstack().sample(3, replace=True).stack() </code></pre> <p><a href="http://i.stack.imgur.com/KwgFP.png" rel="nofollow"><img src="http://i.stack.imgur.com/KwgFP.png" alt="enter image description here"></a></p>
2
2016-08-02T23:48:41Z
[ "python", "pandas", "sampling", "multi-index" ]
Seaborn jointplot hex option does not produce figure
38,731,897
<p>I am plotting a Pandas DataFrame as a Seaborn jointplot and would like to use the 'hex' function:</p> <pre><code>g = sns.jointplot("Xs", "Ys", data=PlotData, kind='hex', color="#4CB391") </code></pre> <p>The DataFrame is all floats and does not contain any NaNs:</p> <pre><code>In [34]: PlotData.describe() Out[34]: Xs Ys count 47856.000000 47856.000000 mean 2.125714 -0.458991 std 0.423019 1.750042 min 0.000000 -23.829382 25% 2.000000 -1.195314 50% 2.000000 0.000000 75% 2.301030 0.000000 max 5.939478 11.099151 </code></pre> <p>The result is a blank figure, though it does produce the marginal distributions and the regression statistics:</p> <p><a href="http://i.stack.imgur.com/OH3yU.png" rel="nofollow"><img src="http://i.stack.imgur.com/OH3yU.png" alt="enter image description here"></a></p> <p>What might I be missing? I am using Python 3.4, Seaborn 0.7, and Pandas 0.18. Thanks!</p> <p><strong>UPDATE</strong> When making the change suggested by Peter below, here is the result:</p> <p><a href="http://i.stack.imgur.com/0P0Sp.png" rel="nofollow"><img src="http://i.stack.imgur.com/0P0Sp.png" alt="enter image description here"></a></p> <p>So it appears that the concentrated points near x=2 are causing extreme scaling.</p>
1
2016-08-02T23:13:51Z
38,732,478
<p>It seems like there is one pixel close to the mean (2, -0.5) that is colored. The standard deviation of your data set is also low, so perhaps the bins are too small and there are too many outliers to see the actual distribution. I would suggest either removing the outliers and trying again or explicitly setting the axis limits using <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.jointplot.html" rel="nofollow">jointplot</a>.</p>
2
2016-08-03T00:23:21Z
[ "python", "python-3.x", "pandas", "seaborn" ]
Can matplotlib only update the newest point to the figure?
38,731,903
<p>Is it possible for matplotlib only update the newest point to the figure instead of re-draw the whole figure? </p> <p>For example: this may be the fastest way for dynamic plotting</p> <pre><code>initiate: fig1 = Figure(figsize = (8.0,8.0),dpi = 100) axes1 = fig1.add_subplot(111) line1, = axes1.plot([],[],animated = True) when new data is coming: line1.set_data(new_xarray,new_yarray) axes1.draw_artist(line1) fig1.canvas.update() fig1.canvas.flush_events() </code></pre> <p>But this will re-draw the whole figure! I'm think whether this is possible:</p> <pre><code>when new data is coming: axes1.draw_only_last_point(new_x,new_y) update_the_canvas() </code></pre> <p>It will only add this new point(new_x,new_y) to the axes instead of re-draw every point.</p> <p>And if you know which graphic library for python can do that, please answer or comment, thank you so much!!!!!</p> <p>Really appreciate your help!</p>
1
2016-08-02T23:14:33Z
38,744,975
<p>Is only redrawing the entire figure the problem, i.e. it is ok to redraw the line itself as long as the figure is unchanged? Is the data known beforehand?</p> <p>If the answer to those questions are NO, and YES, then it might be worth looking into the <code>animate</code>-class for matplotlib. One example where the data is known beforehand, but the points are plotted one by one is <a href="http://matplotlib.org/1.4.1/examples/animation/animate_decay.html" rel="nofollow">this example</a>. In the example, the figure is redrawn if the newest point is outside of the current x-lim. If you know the range of your data you can avoid it by setting the limits beforehand.</p> <p>You might also want to look into <a href="http://stackoverflow.com/questions/10944621/dynamically-updating-plot-in-matplotlib">this answer</a>, the <a href="http://matplotlib.org/1.4.1/examples/animation/index.html" rel="nofollow">animate example list</a> or the <a href="http://matplotlib.org/api/animation_api.html" rel="nofollow">animate documentation</a>.</p>
0
2016-08-03T13:26:09Z
[ "python", "opencv", "matplotlib" ]
Can matplotlib only update the newest point to the figure?
38,731,903
<p>Is it possible for matplotlib only update the newest point to the figure instead of re-draw the whole figure? </p> <p>For example: this may be the fastest way for dynamic plotting</p> <pre><code>initiate: fig1 = Figure(figsize = (8.0,8.0),dpi = 100) axes1 = fig1.add_subplot(111) line1, = axes1.plot([],[],animated = True) when new data is coming: line1.set_data(new_xarray,new_yarray) axes1.draw_artist(line1) fig1.canvas.update() fig1.canvas.flush_events() </code></pre> <p>But this will re-draw the whole figure! I'm think whether this is possible:</p> <pre><code>when new data is coming: axes1.draw_only_last_point(new_x,new_y) update_the_canvas() </code></pre> <p>It will only add this new point(new_x,new_y) to the axes instead of re-draw every point.</p> <p>And if you know which graphic library for python can do that, please answer or comment, thank you so much!!!!!</p> <p>Really appreciate your help!</p>
1
2016-08-02T23:14:33Z
38,903,254
<p>this is my (so far) little experience.<br> I started some month ago with Python(2.x) and openCV (2.4.13) as graphic library.I found in may first project that openCV for python works with numpy structure as much as matplotlib and (with slight difference) they can work together.</p> <p>I had to update some pixel after some condition. I first did my elaboration from images with opencv obtaining a numpy 2D array, like a matrix. The trick is: opencv mainly thinks about input as images, in terms of X as width first, then Y as height. The numpy structure wants rows and columns wich in fact is Y before X. </p> <p>With this in mind I updated pixel by pixel the image-matrix A and plot it again with a colormap</p> <pre><code>import matplotlib as plt import cv2 A = cv2.imread('your_image.png',0) # 0 means grayscale # now you loaded an image in a numpy array A for every new x,y pixel A[y,x] = new pixel intensity value plot = plt.imshow(A, 'CMRmap') plt.show() </code></pre> <p>If you want images again, consider use this</p> <pre><code>import matplotlib.image as mpimg #previous code mpimg.imsave("newA.png", A) </code></pre> <p>If you want to work with colors remember that images in colour are X by Y by 3 numpy array but matplotlib has RGB as the right order of channels, openCv works with BGR order. So</p> <pre><code>C = cv2.imread('colour_reference.png',1) # 1 means BGR A[y,x,0] = newRedvalue = C[y,x][2] A[y,x,1] = newGreenvalue = C[y,x][1] A[y,x,2] = newBluevalue = C[y,x][0] </code></pre> <p>I hope this will help you in some way</p>
0
2016-08-11T18:04:19Z
[ "python", "opencv", "matplotlib" ]
Get indicated string in list
38,731,927
<p>I got the list such as:</p> <pre><code>[Margaret, Peter, Julia-noCP-L,Parker-CP-T, Jessica, Monica-CP-T, Mark, Peter-noCP] </code></pre> <p>I want to obtain or objects which contain only CP in string:</p> <pre><code>['Parker-CP-T', 'Monica-CP-T'] </code></pre> <p>I made it in the following way:</p> <pre><code>headers = ['Margaret', 'Peter', 'Julia-noCP-L', 'Parker-CP-T', 'Jessica', 'Monica-CP-T', 'Mark, Peter-noCP'] headers_CPs = [] for i in headers: if "CP" in i: headers_CPs.append(i) filtr = filter(lambda x: x.split('-')[1] != "noCP", headers_CPs) print filter </code></pre> <p>I want to learn how to write efficient codes. Therefore I want to ask you whether you have some ideas how to solve that simple task easier. Maybe on one line? </p>
0
2016-08-02T23:17:49Z
38,731,974
<p>Check out <a href="https://docs.python.org/3.4/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehensions</a>. With that you can do something like this:</p> <pre><code>headers_CP = [x for x in headers if 'CP' in x] </code></pre> <p>This will pull out all items in the list <code>headers</code> that contain the string 'CP'.</p>
0
2016-08-02T23:23:11Z
[ "python" ]
Get indicated string in list
38,731,927
<p>I got the list such as:</p> <pre><code>[Margaret, Peter, Julia-noCP-L,Parker-CP-T, Jessica, Monica-CP-T, Mark, Peter-noCP] </code></pre> <p>I want to obtain or objects which contain only CP in string:</p> <pre><code>['Parker-CP-T', 'Monica-CP-T'] </code></pre> <p>I made it in the following way:</p> <pre><code>headers = ['Margaret', 'Peter', 'Julia-noCP-L', 'Parker-CP-T', 'Jessica', 'Monica-CP-T', 'Mark, Peter-noCP'] headers_CPs = [] for i in headers: if "CP" in i: headers_CPs.append(i) filtr = filter(lambda x: x.split('-')[1] != "noCP", headers_CPs) print filter </code></pre> <p>I want to learn how to write efficient codes. Therefore I want to ask you whether you have some ideas how to solve that simple task easier. Maybe on one line? </p>
0
2016-08-02T23:17:49Z
38,731,975
<p>One way is just accepting the items that are contain <code>-CP-</code> instead of checking the existence of <code>CP</code> and then filtering the result. You can do this within a <a href="http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Comprehensions.html" rel="nofollow"><em>list comprehension</em></a>:</p> <pre><code>[item for item in headers if '-CP-' in item] </code></pre> <p>If you are not sure about the delimiter (here <code>'-'</code>) you can check it with regex.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; &gt;&gt;&gt; headers = ['Margaret', 'Peter', 'Julia-noCP-L', 'Parker-CP-T', 'Jessica', 'Monica-CP-T', 'Mark, Peter-noCP'] &gt;&gt;&gt; [item for item in headers if re.search(r'\bCP\b', item)] ['Parker-CP-T', 'Monica-CP-T'] </code></pre> <p>The regular expression <code>r'\bCP\b'</code> will only match the <code>CP</code> literals that are surrounded with none-word characters (<code>\b</code> is a word boundary modifier in regex).</p>
0
2016-08-02T23:23:11Z
[ "python" ]
Python: Add egg or do pip install from the Jupyter notebook interface
38,732,053
<p>I am using a Jupyter notebook installed on a server. I am wondering is it possible to upload an egg file, or do a pip install from the notebook interface since I don't want to bother the system administrator for every single package I am experimenting. Thanks!</p> <p><a href="http://i.stack.imgur.com/0LF0z.png" rel="nofollow"><img src="http://i.stack.imgur.com/0LF0z.png" alt="enter image description here"></a></p>
0
2016-08-02T23:31:51Z
38,739,858
<p>There is already a page on this issue <a href="http://stackoverflow.com/questions/12332975/installing-python-module-within-code">here</a>.</p> <p>This is what you should be able to do in the notebook, if you want to install any given 'package':</p> <p>import pip pip.main(['install', 'package'])</p>
0
2016-08-03T09:37:54Z
[ "python", "jupyter-notebook" ]
Compare Django-taggit tags from multiple queries and list objects from matching tags
38,732,054
<p>I have a site that sells parts and tools. The site was originally built with separate models for tools and documents for those tools. The documents were just iterated over on a document page and linked to from the tool page. We use Django-taggit to tag everything, but I have tagged myself into a corner :) </p> <p>I need to list the documents that belong to a particular tool, on the tool detail page and not on separate document page. </p> <p>The problem is there is no relationship with the documents to the tool, so I am trying to query the tags on the tool and the tags on the documents and any document that has the same tag as the tool, would be listed on the page. </p> <p>Below is what I've come up with so far and it works in the sense that it matches the tags, but it duplicates every document. For example, if I have tag names "one" and "two" on both the tool and the documents, it will list all matching documents multiplied by the number of matched tags. I hope that makes sense... I've also included a screenshot to show an example. I know why my code is duplicating, but my Python chops are not seasoned enough to write the code needed to solve it(I also know this can be written dryer - that's my next challenge). Thank you for your help.</p> <p><a href="http://i.stack.imgur.com/q3uFj.png" rel="nofollow"><img src="http://i.stack.imgur.com/q3uFj.png" alt="enter image description here"></a></p> <p>View</p> <pre><code>def tool_detail(request, tool): contact_form(ContactForm, request) tags = Tool.tags.all() tool = get_object_or_404(Tool, slug=tool) uploads = tool.uploads.all() doc = Document.objects.all() return render(request, 'products/tool_detail.html', {'tool': tool, 'tags': tags, 'doc': doc, 'form': ContactForm, 'uploads': uploads}) </code></pre> <p>Template </p> <pre><code>... &lt;tbody&gt; {% for d in doc %} {% for tag in tool.tags.all %} {% if tag.name in d.tags.get.name %} &lt;tr&gt; &lt;td&gt;{{ d.title }}&lt;/td&gt; &lt;td style="text-align: center;"&gt;&lt;a href="{{ d.file.url }}"&gt;&lt;i class="fa fa-cloud-download"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; {% endif %} {% endfor %} {% endfor %} &lt;/tbody&gt; ... </code></pre>
0
2016-08-02T23:31:53Z
38,732,548
<p>First of all, it's a bad practice placing your business logic in template - it should be done in view. Having said that, on to your question. First - the view (see comments in code):</p> <pre><code>def tool_detail(request, tool): contact_form(ContactForm, request) tags = Tool.tags.all() tool = get_object_or_404(Tool, slug=tool) uploads = tool.uploads.all() # filter the documents to find the ones that have identical tags, # add .distinct() to filter out duplicate documents doc = Document.objects.filter(tags__in=tool.tags.all()).distinct() return render(request, 'products/tool_detail.html', {'tool': tool, 'tags': tags, 'doc': doc, 'form': ContactForm, 'uploads': uploads}) </code></pre> <p>and the form would simply be:</p> <pre><code>... &lt;tbody&gt; {% for d in doc %} &lt;tr&gt; &lt;td&gt;{{ d.title }}&lt;/td&gt; &lt;td style="text-align: center;"&gt;&lt;a href="{{ d.file.url }}"&gt;&lt;i class="fa fa-cloud-download"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; ... </code></pre> <p>Read more about filtering and field lookups in the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/" rel="nofollow">documentation</a>.</p>
1
2016-08-03T00:34:13Z
[ "python", "django", "django-models", "django-templates", "django-views" ]
ssh by a python cgi script is not working
38,732,098
<p>I have a couple of things to ask.I am getting following error while trying to ssh remote host from a python CGI.</p> <pre><code>Could not create directory '/var/www/.ssh'. Failed to add the RSA host key for IP address '17.172.221.39' to the list of known hosts (/var/www/.ssh/known_hosts). Permission denied (gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive). </code></pre> <p>Is this becuse its not taking my password or is it because of apache eing user and ssh is not allowed...</p> <p>How to make sure ssh happens without having to do ssh key initiation for this on all hosts.</p> <p>how can i Run a cgi script as root user and not as apache user. I have to run few scripts only as root.I cant use SuExec etc.Please provide the work around for these 2 issues i am facing</p>
0
2016-08-02T23:36:16Z
38,736,171
<p>Web server process is owned by apache user not as root.</p> <ol> <li>Make sure that apache user have password less access to other server</li> <li>SELinux should be disabled</li> </ol> <p>Refer : <a href="http://wccandlinux.blogspot.in/2016/07/how-to-run-ssh-command-from-apache.html" rel="nofollow">http://wccandlinux.blogspot.in/2016/07/how-to-run-ssh-command-from-apache.html</a></p>
0
2016-08-03T06:41:20Z
[ "python", "linux", "apache", "ssh", "cgi" ]
How do reindex multilevel columns
38,732,188
<p>Version info:</p> <pre><code>print(sys.version) 3.5.1 |Anaconda 4.1.0 (64-bit)| (default, Jun 15 2016, 15:29:36) [MSC v.1900 64 bit (AMD64)] </code></pre> <p>I have columns in a data frame that look like this (latitude and longitude are multilevel columns):</p> <pre><code>+------------+---------------+--------------+--------------+ | CustomerId | StreetAddress | Latitude | Longitude | +------------+---------------+-------+------+-------+------+ | | count | mean | count | mean | +----------------------------+-------+------+-------+------+ </code></pre> <p>I would like to get this:</p> <pre><code>+------------+---------------+-----------+----------+-----------+----------+ | CustomerId | StreetAddress | Lat_count | Lat_mean | Lon_count | Lon_mean | +------------+---------------+-----------+----------+-----------+----------+ </code></pre> <p>I tried this:</p> <pre><code>newColumns = ['CustomerId','StreetAddress','Lat_count','Lat_mean','Lon_count','Lon_mean'] data2 = data1.reindex(columns=newColumns) </code></pre> <p>But that absolutely did not work! I ended up with some kind of crazy multilevel columns with each letter of each string in <code>newColumns</code> being a new level.</p> <h1>Update</h1> <p>Here are my columns</p> <pre><code>data1.columns.to_series() CustomerId (CustomerId, ) StreetAddress (StreetAddress, ) Latitude count (Latitude, count) mean (Latitude, mean) Longitude count (Longitude, count) mean (Longitude, mean) </code></pre>
3
2016-08-02T23:45:38Z
38,732,337
<p>This will do the trick:</p> <pre><code>data2 = pd.DataFrame(data1.values, columns=newColumns) </code></pre> <p>And also this:</p> <pre><code>data1.columns = newColumns </code></pre>
2
2016-08-03T00:05:16Z
[ "python", "windows", "pandas" ]
Jupyter NoteBook: draw a graph on the Notebook instead of save the file to the disk
38,732,204
<p>I have the following code:</p> <p><a href="http://i.stack.imgur.com/SPvGB.png" rel="nofollow"><img src="http://i.stack.imgur.com/SPvGB.png" alt="enter image description here"></a></p> <p>Is it possible to print the graph just inside the Notebook instead of saving as a file? Thanks!</p>
0
2016-08-02T23:47:14Z
38,732,289
<p>Yes, use <code>matplotlib</code>:</p> <pre><code> import matplotlib.pyplot as plt nx.draw(G) plt.show() </code></pre> <p><a href="http://www.python-course.eu/networkx.php" rel="nofollow">source</a></p>
0
2016-08-02T23:57:46Z
[ "python", "jupyter-notebook" ]
Jupyter NoteBook: draw a graph on the Notebook instead of save the file to the disk
38,732,204
<p>I have the following code:</p> <p><a href="http://i.stack.imgur.com/SPvGB.png" rel="nofollow"><img src="http://i.stack.imgur.com/SPvGB.png" alt="enter image description here"></a></p> <p>Is it possible to print the graph just inside the Notebook instead of saving as a file? Thanks!</p>
0
2016-08-02T23:47:14Z
38,732,344
<p>Use draw in the following manner :</p> <pre><code>draw(G, show='ipynb') </code></pre> <p>If you want all graphs to be drawn inline, then you can set a global parameter.</p> <pre><code>from nxpd import nxpdParams nxpdParams['show'] = 'ipynb' draw(G) </code></pre> <p>But im not sure this will work with Jupyter, this will work for ipython though.</p>
0
2016-08-03T00:06:03Z
[ "python", "jupyter-notebook" ]
Jupyter NoteBook: draw a graph on the Notebook instead of save the file to the disk
38,732,204
<p>I have the following code:</p> <p><a href="http://i.stack.imgur.com/SPvGB.png" rel="nofollow"><img src="http://i.stack.imgur.com/SPvGB.png" alt="enter image description here"></a></p> <p>Is it possible to print the graph just inside the Notebook instead of saving as a file? Thanks!</p>
0
2016-08-02T23:47:14Z
38,735,487
<p>If you are looking to plot the plots inline inside your jupiter-notebook:</p> <pre><code>import matplotlib.pyplot as plt %matplotlib inline </code></pre> <p><a href="http://i.stack.imgur.com/xvagS.png" rel="nofollow"><img src="http://i.stack.imgur.com/xvagS.png" alt="Plotting inline in the notebook"></a></p>
1
2016-08-03T05:56:08Z
[ "python", "jupyter-notebook" ]
How do I loop through UID's in Firebase
38,732,279
<p>I am using Python to go through a Firebase DB to return an array of objects, then pick one at random and return its values. I've been using a small test JSON DB that I manually build and import into Firebase. When I do this, the DB's child node's are <code>0, 1, 2</code> etc... Using the code below - I can iterate through the data and grab what I need.</p> <p>I've been building a CMS that will let me input data directly into Firebase (instead of importing a local JSON doc) using the <code>push()</code> method. </p> <p>Accordingly, the child nodes become obfuscated timestamps that look like this: <code>K036VOR90fh8sd80, KO698fhs7Hf8sfds</code> etc...</p> <p>Now when I attempt to for-loop through the nodes, I get the following error at <code>ln9</code> <code>caption=....</code>: </p> <p><code>TypeError: string indices must be integers</code></p> <p>I'm assuming this is happening because the child nodes are strings now. Since I have to use the CMS - how do I now loop through these nodes?</p> <p>Code:</p> <pre><code>if 'Item' in intent['slots']: chosen_item = intent['slots']['Item']['value'] result = firebase.get(chosen_item, None) if result: item_object = [] for item in result: item_object.append(item) random_item = (random.choice(item_object)) caption = random_item['caption'] audio_src = random_item['audioPath'] </code></pre> <p>Here is an approximation of what the Firebase looks like: </p> <pre><code> { "1001" : { "-K036VOR90fh8sd80EQ" : { "audioPath" : "https://s3.amazonaws.com/bucket-output/audio/audio_0_1001.mp3", "caption" : "Record 0 from 1001" }, "-KO698fhs7Hf8sfdsWJS" : { "audioPath" : "https://s3.amazonaws.com/bucket-output/audio/audio_1_1001.mp3", "caption" : "Record 1 from 1001" } }, "2001" : { "-KOFsPBMKVtwHSOfiDJ" : { "audioPath" : "https://s3.amazonaws.com/bucket-output/audio/audio_0_2001.mp3", "caption" : "Record 0 from 2001" }, "-KOFsQvwgF9icSIolU" : { "audioPath" : "https://s3.amazonaws.com/bucket-output/audio/audio_1_2001.mp3", "caption" : "Record 1 from 2001" } } } </code></pre>
0
2016-08-02T23:57:00Z
38,751,033
<p>What needs to be done is to strip the dictionary <code>result</code> of the parent nodes using a <code>for-loop</code> and the <code>.items()</code> Python method - through the key-values (<code>k,v</code>) and <code>.append</code> the values (<code>v</code>). </p> <p>This strips the <code>result</code> of the parent Firebase dictionary keys i.e <code>-KOFsQvwgF9icSIolU</code>. </p> <pre><code>if 'Item' in intent['slots']: chosen_item = intent['slots']['Item']['value'] result = firebase.get(chosen_item, None) if result: item_object = [] for k,v in result.items(): item_object.append(v) random_item = (random.choice(item_object)) caption = random_item['caption'] audio_src = random_item['audioPath'] </code></pre>
0
2016-08-03T18:23:11Z
[ "python", "arrays", "json", "firebase", "firebase-database" ]
Can Python Staticmethod Call Another Local Method?
38,732,287
<p>In Python, within a class, can a staticmethod call on another local function/method defined within the same class?</p> <p>I tried the following code and obtained an error message saying foo1() is not defined.</p> <pre><code>class trialOne(object): @staticmethod def foo1(): a = 3.1 return a @staticmethod def foo(): a = foo1() return a obj = trialOne() b = obj.foo() </code></pre>
-2
2016-08-02T23:57:35Z
38,732,351
<pre><code>class Tester: def local(self): print "I'm a local!" @staticmethod def another_stat(): print "I'm a static!" @staticmethod def stat(inst): inst.local() Tester.another_stat() t = Tester() Tester.stat(t) # Out: # I'm a local! # I'm a static! </code></pre> <p>Yes, you can! By definition, instance methods need an instance to associate themselves with, but as long as you have that instance, you can call local methods just as you normally would.</p> <p>To go into this in a little more depth, there's nothing special about the word <code>self</code>. That's a variable just like any other. Any instance method of a class MUST take in an instance of that class as its first parameter, and it's convention to call that parameter <code>self</code>, but you could just as easily use any other name.</p> <p>If it helps you understand the distinction, these two statements are semantically equivalent:</p> <p><code>t.local()</code></p> <p><code>Tester.local(t)</code></p> <p>The first is just syntactic sugar for the second. The second is using the class name to reference a method of the Tester class, then passes in the instance as the first parameter. The first simply pretends that <code>local</code> is a field of <code>t</code> and calls it, but that call is transformed into <code>Tester.local(t)</code> by the Python interpreter.</p> <p>Thus, calling a static method is the same syntax as <code>Tester.local(t)</code>, except the first parameter <strong>does not</strong> have to be an instance of that class.</p> <p>So classmethods and staticmethods are called in the same way, but the difference is that a class method "knows" what class it's coming from. The first parameter of a class method is always a variable that contains the class that it's being invoked from. That way if the method is inherited, it knows which method it's coming from, where a staticmethod would not know. In your comment, you said this:</p> <pre><code>@classmethod def stat(cls): cls.another_stat() </code></pre> <p>In this example, <code>cls</code> is a variable that contains the class that the method is being called from, <strong><em>not</em></strong> an instance of the class that it is being called from. That is why you can call static methods with <code>cls</code> - because it is equivalent to <code>Tester</code></p>
1
2016-08-03T00:06:50Z
[ "python", "static-methods" ]
Set bottom, top, left, right tick visibility in matplotlibrc
38,732,407
<p><a href="http://stackoverflow.com/a/12998531/6421322">Here</a> is a question about turning off the ticks on a given side of a set of axes by using the <code>tick_params</code> method. I want to change the <code>top</code> and <code>right</code> properties to off by default in my <code>matplotlibrc</code> but I don't see how that is to be done, as the ticks section of the <code>matplotlibrc</code> file deals with things in terms of <code>xtick</code> and <code>ytick</code>. What am I missing?</p>
4
2016-08-03T00:14:18Z
38,744,038
<p>I'm pretty new to matplotlib myself, but i belive you can do something like this:</p> <pre><code>pl.tick_params(bottom="off", top="off") </code></pre>
1
2016-08-03T12:43:04Z
[ "python", "matplotlib" ]
Set bottom, top, left, right tick visibility in matplotlibrc
38,732,407
<p><a href="http://stackoverflow.com/a/12998531/6421322">Here</a> is a question about turning off the ticks on a given side of a set of axes by using the <code>tick_params</code> method. I want to change the <code>top</code> and <code>right</code> properties to off by default in my <code>matplotlibrc</code> but I don't see how that is to be done, as the ticks section of the <code>matplotlibrc</code> file deals with things in terms of <code>xtick</code> and <code>ytick</code>. What am I missing?</p>
4
2016-08-03T00:14:18Z
38,750,147
<p>After sleuthing around on the matplotlib github, I found what I was looking for: the <a href="https://github.com/matplotlib/matplotlib/blob/v2.x/matplotlibrc.template" rel="nofollow">upcoming version 2.x branch</a>, at the time I am writing this, has <code>xtick.top</code>, etcetera, as parameters in the new matplotlibrc template.</p> <p>So the answer is that at the time of this writing, that functionality may not be available for templates, and @user2927356's method may be all I can use until matplotlib 2.x comes out.</p>
1
2016-08-03T17:28:27Z
[ "python", "matplotlib" ]
How should I properly use Selenium
38,732,496
<p>I'm trying to get one number from Yahoo Finance (<a href="http://finance.yahoo.com/quote/AAPL/financials?p=AAPL" rel="nofollow">http://finance.yahoo.com/quote/AAPL/financials?p=AAPL</a>), Balance Sheet, Total Stockholder Equity. If I inspect the element I get this:</p> <pre><code>&lt;span data-reactid=".1doxyl2xoso.1.$0.0.0.3.1.$main-0-Quote-Proxy.$main-0-Quote.0.2.0.2:1:$BALANCE_SHEET.0.0.$TOTAL_STOCKHOLDER_EQUITY.1:$0.0.0"&gt;119,355,000&lt;/span&gt; </code></pre> <p>I would like to get, scrap the number: 119,355,000.</p> <p>If I understand correctly, web page is coded in Java Script and I need to use Selenium to get to the desired number. My attempt (I'm complete beginner) is not working no matter what I do, Bellow are three of many attempts. I tried to use 'data-reactid' and few other tings and I'm running out of ideas :-)</p> <pre><code>elem = Browser.find_element_by_partial_link_text('TOTAL_STOCKHOLDER_EQUITY') elem = browser.find_element_by_id('TOTAL_STOCKHOLDER_EQUITY') elem = browser.find_elem_by_id('TOTAL_STOCKHOLDER_EQUITY') </code></pre>
1
2016-08-03T00:27:06Z
38,733,659
<p>Actually your all locator looks like invalid, try using <code>find_element_by_css_selector</code> as below :-</p> <pre><code>elem = browser.find_element_by_css_selector("span[data-reactid *= 'TOTAL_STOCKHOLDER_EQUITY']") </code></pre> <p>Note: <code>find_element_by_partial_text</code> is use to locate only <code>a</code> with paritially match of text content not their attribute text and <code>find_element_by_id</code> is use to locate any element with their <code>id</code> attribute which will match exactly with passing value.</p> <p><strong>Edited</strong> :- There are more elements found with the provided locator, so you should try to find exact row of <code>Total Stockholder Equity</code> means <code>tr</code> element then find all their <code>td</code> elements as below :-</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC browser = webdriver.Chrome() browser.get('http://finance.yahoo.com/quote/AAPL/financials?p=AAPL') browser.maximize_window() wait = WebDriverWait(browser, 5) try: #first try to find balance sheet link and click on it balanceSheet = wait.until(EC.element_to_be_clickable((By.XPATH, "//span[text() = 'Balance Sheet']"))) balanceSheet.click() #Now find the row element of Total Stockholder Equity totalStockRow = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "tr[data-reactid *= 'TOTAL_STOCKHOLDER_EQUITY']"))) #Now find all the columns included with Total Stockholder Equity totalColumns = totalStockRow.find_elements_by_tag_name("td") #Now if you want to print single value just pass the index into totalColumns other wise print all values in the loop #Now print all values in the loop for elem in totalColumns: print elem.text #it will print value as #Total Stockholder Equity #119,355,000 #111,547,000 #123,549,000 except: print('Was not able to find the element with that name.') </code></pre> <p>Hope it helps...:)</p>
1
2016-08-03T02:57:38Z
[ "python", "python-3.x", "selenium-webdriver", "web-scraping", "yahoo-finance" ]
TensorFlow Master and Worker Service
38,732,502
<p>I am trying to understand the exact roles of the master and worker service in TensorFlow.</p> <p>So far I understand that each TensorFlow task that I start is associated with a <code>tf.train.Server</code> instance. This instance exports a "master service" and "worker service" by implementing the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/cc/ClassSession.html#class-tensorflow-session" rel="nofollow"><code>tensorflow::Session</code></a> interface" (master) and <a href="https://github.com/tensorflow/tensorflow/blob/27eeb441bad8bcaa1bcba42a4b4ee49fb50ea0d3/tensorflow/core/protobuf/worker_service.proto" rel="nofollow"><code>worker_service.proto</code></a> (worker).</p> <p><strong>1st Question: Am I right that this means, that ONE task is only associated with ONE worker?</strong></p> <hr> <p><em>Furthermore, I understood...</em></p> <p><em>...about the Master:</em> It is the scope of the master service...</p> <p>(1) ...to offer functions to the client so that the client can run a session for example.</p> <p>(2) ...to delegate work to the available workers in order to compute a session run.</p> <p><strong>2nd Question: In case we execute a graph distributed using more than one task, does only one master service get used?</strong></p> <p><strong>3rd Question: Should tf.Session.run get only called once?</strong></p> <p>This is at least how I interpret this figure from <a href="http://download.tensorflow.org/paper/whitepaper2015.pdf" rel="nofollow">the whitepaper</a>:</p> <p><a href="http://i.stack.imgur.com/mf8Dx.png" rel="nofollow"><img src="http://i.stack.imgur.com/mf8Dx.png" alt="enter image description here"></a></p> <hr> <p><em>... about the Worker:</em> It is the scope of the worker service...</p> <p>(1) to execute the nodes (which got delegated to him by the master service) on the devices the worker manages.</p> <p><strong>4th Question: How does one worker make use of multiple devices? Does a worker decide automatically how to distribute single operations?</strong></p> <hr> <p>Please also correct me in case I came up with wrong statements! Thank you in advance!!</p>
2
2016-08-03T00:28:05Z
38,749,421
<blockquote> <p>1st Question: Am I right that this means, that ONE task is only associated with ONE worker?</p> </blockquote> <p>This is the typical configuration, yes. Each <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#Server" rel="nofollow"><code>tf.train.Server</code></a> instance contains a full TensorFlow runtime, and the default configuration assumes that this runtime has exclusive access to the machine (in terms of how much memory it allocates on GPUs, etc.).</p> <p>Note that you can create multiple <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#Server" rel="nofollow"><code>tf.train.Server</code></a> instances in the same process (and we sometimes do this <a href="https://github.com/tensorflow/tensorflow/blob/27eeb441bad8bcaa1bcba42a4b4ee49fb50ea0d3/tensorflow/python/training/server_lib_test.py" rel="nofollow">for testing</a>). However, there is little resource isolation between these instances, so running multiple instances in a single task is unlikely to yield good performance (with the current version).</p> <blockquote> <p>2nd Question: In case we execute a graph distributed using more than one task, does only one master service get used?</p> </blockquote> <p>It depends on the <a href="https://www.tensorflow.org/versions/r0.10/how_tos/distributed/index.html#replicated-training" rel="nofollow">form of replication</a> you are using. If you use "in-graph replication", you can use a single master service that knows about all replicas of the model (i.e. worker tasks). If you use "between-graph replication", you would use multiple master services, each of which knows about a single replica of the model, and is typically colocated with the worker task on which it runs. In general, we have found it more performant to use between-graph replication, and the <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#Supervisor" rel="nofollow"><code>tf.train.Supervisor</code></a> library is designed to simplify operation in this mode.</p> <blockquote> <p>3rd Question: Should <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/client.html#Session.run" rel="nofollow"><code>tf.Session.run()</code></a> get only called once?</p> </blockquote> <p>(I'm assuming this means "once per training step". A simple TensorFlow program for training a model will call <code>tf.Session.run()</code> in a loop.)</p> <p>This depends on the form of replication you are using, <strong>and</strong> the coordination you want between training updates.</p> <ul> <li><p>Using <strong>in-graph</strong> replication, you can make <strong>synchronous</strong> updates by aggregating the losses or gradients in a single <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#Optimizer" rel="nofollow"><code>tf.train.Optimizer</code></a>, which gives a single <code>train_op</code> to run. In this case, you only call <code>tf.Session.run(train_op)</code> once per training step. </p></li> <li><p>Using <strong>in-graph</strong> replication, you make <strong>asynchronous</strong> updates by defining one <code>tf.train.Optimizer</code> per replica, which gives multiple <code>train_op</code> operations to run. In this case, you typically call each <code>tf.Session.run(train_op[i])</code> from a different thread, concurrently.</p></li> <li><p>Using <strong>between-graph</strong> replication, you make <strong>synchronous</strong> updates using the <a href="https://github.com/tensorflow/tensorflow/blob/27eeb441bad8bcaa1bcba42a4b4ee49fb50ea0d3/tensorflow/python/training/sync_replicas_optimizer.py" rel="nofollow"><code>tf.train.SyncReplicasOptimizer</code></a>, which is constructed separately in each replica. Each replica has its own training loop that makes a single call to <code>tf.Session.run(train_op)</code>, and the <code>SyncReplicasOptimizer</code> coordinates these so that the updates are applied synchronously (by a background thread in one of the workers).</p></li> <li><p>Using <strong>between-graph</strong> replication, you make <strong>asynchronous</strong> updates by using another <code>tf.train.Optimizer</code> subclass (other than <code>tf.train.SyncReplicasOptimizer</code>), using a training loop that similar to the synchronous case, but without the background coordination.</p></li> </ul> <blockquote> <p>4th Question: How does one worker make use of multiple devices? Does a worker decide automatically how to distribute single operations or...?</p> </blockquote> <p>Each worker runs the same placement algorithm that is used in single-process TensorFlow. Unless instructed otherwise, the placer will put operations on the GPU if one is available (and there is a GPU-accelerated implementation), otherwise it will fall back to the CPU. The <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#replica_device_setter" rel="nofollow"><code>tf.train.replica_device_setter()</code></a> device function can be used to shard variables across tasks that act as "parameter servers". If you have more complex requirements (e.g. multiple GPUs, local variables on the workers, etc.) you can use explicit <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#device" rel="nofollow"><code>with tf.device(...):</code></a> blocks to assign subgraphs to a particular device.</p>
2
2016-08-03T16:48:30Z
[ "python", "tensorflow" ]
Passing xPath translate function in Scrapy not working for special characters
38,732,516
<p>I'm building a Scrapy spider which takes the xpath query as an input parameter.</p> <p>The specific page I'm trying to scrape has line feeds, new lines and other characters within the price text field and I'm using the <code>translate()</code> function to remove them.</p> <p>The selector works fine with the translate if explicitly included in the code but the translate doesn't work if passed as a parameter.</p> <p>Here is my spider:</p> <pre><code>import scrapy from spotlite.items import SpotliteItem class GenericSpider(scrapy.Spider): name = "generic" xpath_string = "" def __init__(self, start_url, allowed_domains, xpath_string, *args, **kwargs): super(GenericSpider, self).__init__(*args, **kwargs) self.start_urls = ['%s' % start_url] self.allowed_domains = ['%s' % allowed_domains] self.xpath_string = xpath_string def parse(self, response): self.logger.info('URL is %s', response.url) self.logger.info('xPath is %s', self.xpath_string) item = SpotliteItem() item['url'] = response.url item['price'] = response.xpath(self.xpath_string).extract() return item </code></pre> <p>And I use the following to call the spider.</p> <pre><code>scrapy crawl generic -a start_url=https://www.danmurphys.com.au/product/DM_4034/penfolds-kalimna-bin-28-shiraz -a allowed_domains=danmurphys.com.au -a "xpath_string=translate((//span[@class='price'])[1]/text(),',$\r\n\t','')" </code></pre> <p>The issue seems to be passing specical characters in the argument i.e. \r\n\t. </p> <p>The '$'character is correctly removed but the \r\n\t characters are not as per the output below.</p> <pre><code>{'price': [u'\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t27.50\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t'], 'url': 'https://www.danmurphys.com.au/product/DM_4034/penfolds-kalimna-bin-28-shiraz.jsp;jsessionid=B0211294F13A980CA41261379CD83541.ncdlmorasp1301?bmUID=loERXI6'} </code></pre> <p>Any assistance or advice will be appreciated!</p> <p>Thanks,</p> <p>Michael</p>
0
2016-08-03T00:30:38Z
38,733,484
<p>Try using the <code>normalize-space()</code> XPath function in your selector:</p> <pre><code>scrapy crawl generic -a start_url=&lt;URL&gt; -a \ allowed_domains=danmurphys.com.au \ -a "xpath_string=normalize-space(//span[@class='price'][1]/text())" </code></pre> <p>In your <code>parse</code> method, you can use the <a href="http://doc.scrapy.org/en/latest/topics/selectors.html#id1" rel="nofollow"><code>extract_first()</code></a> to get the price as a single string object, instead of a list:</p> <pre><code>item['price'] = response.xpath(self.xpath_string).extract_first() </code></pre> <p>You could also use the <a href="http://doc.scrapy.org/en/latest/topics/selectors.html#using-selectors-with-regular-expressions" rel="nofollow"><code>re_first()</code></a> method to remove the <code>$</code> sign from the string:</p> <pre><code>item['price'] = response.xpath(self.xpath_string).re_first("\$(.+)") </code></pre>
0
2016-08-03T02:39:03Z
[ "python", "xpath", "scrapy" ]
My recursive solution in Python is appending and replacing all current items in answer list with the current list
38,732,529
<p>I am trying to implement a Python solution to the programming question of finding all subsets in an integer array. I should return an array that contains all subsets of the integer array with no duplicates and sorted.</p> <pre><code>def subsetHelper(cur_set, index, A, ans): if index &gt;= len(A): print "appending ", cur_set ans.append(cur_set) print "ans: ", ans return # don't include current number subsetHelper(cur_set, index+1, A, ans) # include current number cur_set.append(A[index]) subsetHelper(cur_set, index+1, A, ans) cur_set.pop() def subsets(A): A.sort() ans = [] cur_set = [] # dont include current number subsetHelper(cur_set, 0, A, ans) return ans </code></pre> <p>Implementing this same logic in C++ results in the correct return value. However when I do this in Python all I get are a collection of empty lists at the very end, while during iteration it's copying the same current list to all items in the list, even though the print out shows its appending the correct subset each time. Why is this happening? Here is the output:</p> <pre><code>print subsets([1,2,3]) appending [] ans: [[]] appending [3] ans: [[3], [3]] appending [2] ans: [[2], [2], [2]] appending [2, 3] ans: [[2, 3], [2, 3], [2, 3], [2, 3]] appending [1] ans: [[1], [1], [1], [1], [1]] appending [1, 3] ans: [[1, 3], [1, 3], [1, 3], [1, 3], [1, 3], [1, 3]] appending [1, 2] ans: [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2]] appending [1, 2, 3] ans: [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] [[], [], [], [], [], [], [], []] </code></pre>
4
2016-08-03T00:32:21Z
38,732,712
<p>there are 2 problem here: the problem first is that you <code>ans.extend</code> instead of <code>ans.append</code>, once change that we get the second problem which is empty list at the end and the reason is that append only add to the list <code>ans</code> a reference to <code>cur_set</code> which you end up removing all element in the course of the recursion so you end up with several references to the same list that is empty at the end, to fix this you only need to append a copy of the current content of the list with <code>list(cur_set)</code> for instance. </p> <p>Also there is no reason to make this a class</p> <pre><code>def subsetHelper(cur_set, index, A, ans): if index &gt;= len(A): print "appending ", cur_set ans.append(list(cur_set)) # &lt;--- here was the problem print "ans: ", ans return # don't include current number subsetHelper(cur_set, index+1, A, ans) # include current number cur_set.append(A[index]) self.subsetHelper(cur_set, index+1, A, ans) cur_set.pop() def subsets(A): A.sort() ans = [] cur_set = [] # dont include current number subsetHelper(cur_set, 0, A, ans) return ans </code></pre> <p>test</p> <pre><code>&gt;&gt;&gt; subsets([1,2,3]) appending [] ans: [[]] appending [3] ans: [[], [3]] appending [2] ans: [[], [3], [2]] appending [2, 3] ans: [[], [3], [2], [2, 3]] appending [1] ans: [[], [3], [2], [2, 3], [1]] appending [1, 3] ans: [[], [3], [2], [2, 3], [1], [1, 3]] appending [1, 2] ans: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2]] appending [1, 2, 3] ans: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] &gt;&gt;&gt; </code></pre>
1
2016-08-03T00:55:21Z
[ "python", "list" ]
My recursive solution in Python is appending and replacing all current items in answer list with the current list
38,732,529
<p>I am trying to implement a Python solution to the programming question of finding all subsets in an integer array. I should return an array that contains all subsets of the integer array with no duplicates and sorted.</p> <pre><code>def subsetHelper(cur_set, index, A, ans): if index &gt;= len(A): print "appending ", cur_set ans.append(cur_set) print "ans: ", ans return # don't include current number subsetHelper(cur_set, index+1, A, ans) # include current number cur_set.append(A[index]) subsetHelper(cur_set, index+1, A, ans) cur_set.pop() def subsets(A): A.sort() ans = [] cur_set = [] # dont include current number subsetHelper(cur_set, 0, A, ans) return ans </code></pre> <p>Implementing this same logic in C++ results in the correct return value. However when I do this in Python all I get are a collection of empty lists at the very end, while during iteration it's copying the same current list to all items in the list, even though the print out shows its appending the correct subset each time. Why is this happening? Here is the output:</p> <pre><code>print subsets([1,2,3]) appending [] ans: [[]] appending [3] ans: [[3], [3]] appending [2] ans: [[2], [2], [2]] appending [2, 3] ans: [[2, 3], [2, 3], [2, 3], [2, 3]] appending [1] ans: [[1], [1], [1], [1], [1]] appending [1, 3] ans: [[1, 3], [1, 3], [1, 3], [1, 3], [1, 3], [1, 3]] appending [1, 2] ans: [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2], [1, 2]] appending [1, 2, 3] ans: [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] [[], [], [], [], [], [], [], []] </code></pre>
4
2016-08-03T00:32:21Z
38,732,840
<p>The problem is you're re-using the cur_set list object between calls so even after <code>cur_set</code> has been added to <code>ans</code>, futures calls to <code>susetHelper</code> still modify the list, specifically future calls to <code>cur_set.pop()</code> empty the list. You can solve this problem by storing a copy of <code>cur_set</code> instead of the exact object.</p> <pre><code>def subsetHelper(cur_set, index, A, ans): if index &gt;= len(A): print "appending ", cur_set ans.append(cur_set[:]) print "ans: ", ans return # don't include current number subsetHelper(cur_set, index+1, A, ans) # include current number cur_set.append(A[index]) subsetHelper(cur_set, index+1, A, ans) cur_set.pop() def subsets(A): A.sort() ans = [] cur_set = [] # dont include current number subsetHelper(cur_set, 0, A, ans) return ans print subsets([12, 13]) </code></pre> <p>Not that you're mixing state based oop and functional programing styles here. There is nothing wrong with that in principle, but debugging state based recursion can be very frustrating. If this is a learning exercise, I'd suggest you try to solve this problem in a purely functional way first (recursive way) then do it again in a purely state based way. Doing it both ways will give you a better understanding of the problem.</p>
0
2016-08-03T01:17:20Z
[ "python", "list" ]
If myStr = 'test', why does myStr[4] produce error out of range but myStr[4:] does not?
38,732,601
<p>I'm using recursion to iterate through the values of a string. When I get past the last character, it's allowing me to use that index position as an empty string <code>""</code> instead of giving an error. Why is that?</p> <pre><code>myStr = 'test' print(myStr[4]) </code></pre> <p>produces an error</p> <pre><code>print(myStr[4:]) </code></pre> <p>does not produce any error.</p>
3
2016-08-03T00:40:25Z
38,732,612
<p>Slicing is not bounds-checked by the built-in types. If the array indices are out of bounds, it will automatically truncate then at the right places.</p>
6
2016-08-03T00:42:53Z
[ "python", "recursion" ]
If myStr = 'test', why does myStr[4] produce error out of range but myStr[4:] does not?
38,732,601
<p>I'm using recursion to iterate through the values of a string. When I get past the last character, it's allowing me to use that index position as an empty string <code>""</code> instead of giving an error. Why is that?</p> <pre><code>myStr = 'test' print(myStr[4]) </code></pre> <p>produces an error</p> <pre><code>print(myStr[4:]) </code></pre> <p>does not produce any error.</p>
3
2016-08-03T00:40:25Z
38,732,669
<p><a href="https://docs.python.org/3/tutorial/introduction.html#strings" rel="nofollow">Python 3.0 documentation </a>says about strings that</p> <blockquote> <p>Attempting to use an index that is too large will result in an error</p> </blockquote> <p>and</p> <blockquote> <p>out of range slice indexes are handled gracefully when used for slicing</p> </blockquote>
0
2016-08-03T00:49:10Z
[ "python", "recursion" ]
If myStr = 'test', why does myStr[4] produce error out of range but myStr[4:] does not?
38,732,601
<p>I'm using recursion to iterate through the values of a string. When I get past the last character, it's allowing me to use that index position as an empty string <code>""</code> instead of giving an error. Why is that?</p> <pre><code>myStr = 'test' print(myStr[4]) </code></pre> <p>produces an error</p> <pre><code>print(myStr[4:]) </code></pre> <p>does not produce any error.</p>
3
2016-08-03T00:40:25Z
38,732,703
<p>Because array accesses are defined such that it's an error for a lone index to be out of range, but not for (part or all of) a slice to be. If any part of a slice is out of range, it simply yields no results, rather than triggering an error.</p>
0
2016-08-03T00:53:28Z
[ "python", "recursion" ]
How do I have two elements inside an index when using python list comprehensions?
38,732,615
<p>I am trying to fully capitalise a word as well as include its length in a new list, using list comprehension.</p> <p>For example if I entered <code>wordLengths(["hello","bye","greetings"])</code> I am wanting this output.</p> <pre><code>[("HELLO",5),("BYE",3),("GREETINGS",9)] </code></pre> <p>This is my current code</p> <pre><code>def wordLengths(myWords): return [i.upper() for i in myWords], [len(i) for i in myWords] </code></pre> <p>And this is the current output</p> <pre><code>(['HELLO', 'BYE', 'GREETINGS'], [5, 3, 9]) </code></pre>
1
2016-08-03T00:43:08Z
38,732,636
<p>You need to do the both in one list comprehension:</p> <pre><code>[(i.upper(), len(i)) for i in myWords] </code></pre>
4
2016-08-03T00:45:38Z
[ "python", "list-comprehension" ]
How do I have two elements inside an index when using python list comprehensions?
38,732,615
<p>I am trying to fully capitalise a word as well as include its length in a new list, using list comprehension.</p> <p>For example if I entered <code>wordLengths(["hello","bye","greetings"])</code> I am wanting this output.</p> <pre><code>[("HELLO",5),("BYE",3),("GREETINGS",9)] </code></pre> <p>This is my current code</p> <pre><code>def wordLengths(myWords): return [i.upper() for i in myWords], [len(i) for i in myWords] </code></pre> <p>And this is the current output</p> <pre><code>(['HELLO', 'BYE', 'GREETINGS'], [5, 3, 9]) </code></pre>
1
2016-08-03T00:43:08Z
38,732,637
<p>Your method is returning a tuple of two lists, and what you are actually trying to do is create a list of tuples.</p> <p>Your comprehension would simply be: </p> <pre><code>[(word.upper(), len(word)) for word in words] </code></pre> <p>So, your method can now be re-written as: </p> <pre><code>def wordLengths(myWords): return [(word.upper(), len(word)) for word in myWords] </code></pre> <p>Demo: </p> <pre><code>words = ["hello", "bye", "greetings"] print(wordLengths(words)) # outputs # [('HELLO', 5), ('BYE', 3), ('GREETINGS', 9)] </code></pre>
2
2016-08-03T00:45:42Z
[ "python", "list-comprehension" ]
Drawing a cuboid to image
38,732,635
<p>I'm in the process of moving a significant application to Python from PHP. All is well, except one particular issue that I can't seem to get to the bottom of.</p> <p>The old application uses a PHP library Image_3D to draw some cuboids to an image (SVG, though that's not important) and display them on the web page.</p> <p>I've migrated almost everything to Flask(w/SQLAlchemy) except fo the imaging. I've tried <code>matplotlib</code>, <code>vpython</code> and almost got desperate enough to reach for <code>OpenGL</code> bindings.</p> <p>This is how PHP currently renders a few examples:</p> <p><img src="http://www.offblast.si/content/vulcan/cut/11001/11001.svg"></p> <p><img src="http://www.offblast.si/content/vulcan/cut/11297/11297.svg"></p> <p>You can see that it remains readable enough even in extreme situations.</p> <p>My best attempt at Python does fairly poorly:</p> <p><img src="http://www.offblast.si/vulcan_env/vulcan/6968.png"></p> <p><img src="http://www.offblast.si/vulcan_env/vulcan/6081.png"></p> <p>The image is entirely unreadable. I didn't fill in the content, because, frankly, there's no point to it - you can't make anything out. Any attempt at fixing the view with <code>ax.init_view</code> was even worse, no matter the elevation or azimuth.</p> <p>The code is just a bunch of points, rendered with</p> <pre><code>fig = plt.figure(frameon=False) ax = fig.gca(projection='3d') ax.set_axis_off() ax.set_aspect('equal') ax.plot_wireframe(points[:, 0], points[:, 1], points[:, 2], color="b") plt.savefig(filename, bbox_inches='tight', pad_inches=0) </code></pre> <p>I'm sure I'm doing something wrong, but I can't figure out how to make readable renders work in Python / <code>matplotlib</code> or if there's a different library better suited for the task.</p> <h3>Update 1</h3> <p>It occurs to me I haven't described the problem correctly - it's a business-restricted subset of the knapsack problem. The container and cuboids within are thus arbitrarily positioned. The visualization module recieves dimensions and positions and needs to render them. The regularity of the previous examples is just a first-order optimal solution and is found often, but not in the majority of situations.</p> <p>Some more examples to illustrate:</p> <p><img src="http://www.offblast.si/content/vulcan/cut/123241/123241.svg"></p> <p><img src="http://www.offblast.si/content/vulcan/cut/124298/124298.svg"></p> <h3>Update 2</h3> <p>A better solution with <code>matplotlib</code>, folowing the answer below. It doesn't seem easy to get MPL to rotate the entire plot as to show a useful overview. <code>ax.view_init</code> should allow for changing the height, but it seems the FOV is too wide for such a narrow plot and all it does is transform the edges slightly.</p> <p><img src="http://www.offblast.si/vulcan_env/vulcan/7489.png"></p>
0
2016-08-03T00:45:33Z
38,757,150
<p>You could use either VPython of matplotlib for this. In matplotlib I'd use a 3d box for your bars, and than another for the frame, and turn off the axes. Here's an examples:</p> <p><a href="http://i.stack.imgur.com/AsfX4.png" rel="nofollow"><img src="http://i.stack.imgur.com/AsfX4.png" alt="enter image description here"></a></p> <pre><code>from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection = "3d") ax.autoscale(enable=False) xpos = np.arange(5) ypos = np.zeros(5) zpos = np.zeros(5) dx = np.ones(5) dy = 5*np.ones(5) dz = 5 + 5*np.random.random(5) colors = ['r', 'c', 'g', 'y', 'm'] ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors, alpha=1) ax.bar3d(0, 0, 0, 5, 5, 25, color=(1, 1, 1, 0)) ax.set_axis_off() plt.show() </code></pre>
1
2016-08-04T01:37:14Z
[ "python", "matplotlib" ]
Python Kivy Raspberrypi Error GPIO Channel
38,732,644
<p>Im create class for add widgets rectangle in many different positions my layout. Im runing return error GPIO most setup(), im configure port in line 11, whats problem in my code ?</p> <pre><code>&gt; Traceback (most recent call last): File "plantadeira.py", line 50, &gt; in &lt;module&gt; &gt; MainApp().run() File "/usr/local/lib/python2.7/dist-packages/kivy/app.py", line 828, in run &gt; runTouchApp() File "/usr/local/lib/python2.7/dist-packages/kivy/base.py", line 487, in &gt; runTouchApp &gt; EventLoop.window.mainloop() File "/usr/local/lib/python2.7/dist-packages/kivy/core/window/window_egl_rpi.py", &gt; line 90, in mainloop &gt; self._mainloop() File "/usr/local/lib/python2.7/dist-packages/kivy/core/window/window_egl_rpi.py", &gt; line 85, in _mainloop &gt; EventLoop.idle() File "/usr/local/lib/python2.7/dist-packages/kivy/base.py", line 327, in &gt; idle &gt; Clock.tick() File "/usr/local/lib/python2.7/dist-packages/kivy/clock.py", line 581, in &gt; tick &gt; self._process_events() File "kivy/_clock.pyx", line 368, in kivy._clock.CyClockBase._process_events &gt; (/tmp/pip-NKJIwl-build/kivy/_clock.c:7219) File "kivy/_clock.pyx", &gt; line 398, in kivy._clock.CyClockBase._process_events &gt; (/tmp/pip-NKJIwl-build/kivy/_clock.c:7102) File "kivy/_clock.pyx", &gt; line 396, in kivy._clock.CyClockBase._process_events &gt; (/tmp/pip-NKJIwl-build/kivy/_clock.c:7032) File "kivy/_clock.pyx", &gt; line 168, in kivy._clock.ClockEvent.tick &gt; (/tmp/pip-NKJIwl-build/kivy/_clock.c:3109) File "plantadeira.py", &gt; line 26, in update &gt; if self.read_Sensor(pin) == False: File "plantadeira.py", line 36, in read_Sensor &gt; sensor = GPIO.wait_for_edge(int(pin), GPIO.RISING, timeout=1000) RuntimeError: You must setup() the GPIO channel as an input first </code></pre> <p>This is my code python:</p> <pre><code>from kivy.app import App from kivy.clock import Clock from kivy.graphics import Color, Rectangle from kivy.properties import NumericProperty from kivy.uix.floatlayout import FloatLayout from kivy.uix.widget import Widget import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) pin_1 = 17 class MainLayout(FloatLayout): pass class bar(Widget): r = NumericProperty(1) def __init__(self, pin, p1, p2, s1, s2, **kwargs): super(bar, self).__init__(**kwargs) Clock.schedule_interval(self.update, 0.5) def update(self, pin): if self.read_Sensor(pin) == False: with self.canvas: Color(self.r, 0, 0, 1) Rectangle(pos=(p1,p2), size=(s1,s2)) else: with self.canvas: Color(self.r, 1, 1, 1) Rectangle(pos=(p1,p2), size=(s1,s2)) def read_Sensor(self, pin): sensor = GPIO.wait_for_edge(int(pin), GPIO.RISING, timeout=1000) if sensor is None: return False else: return True class MainApp(App): def build(self): self.mainlayout = Widget() bar1 = bar(pin_1, 1, 10, 60, 100) self.mainlayout.add_widget(bar1) return self.mainlayout if __name__ == '__main__': MainApp().run() </code></pre>
0
2016-08-03T00:46:28Z
38,747,861
<p>The problem in your code is when you call:<br> <code>GPIO.wait_for_edge(int(pin), GPIO.RISING, timeout=1000)</code><br> you can not use <code>int(pin)</code> but rather <code>pin_1</code> which you defined before the class.<br> So you could call it like this instead:<br> <code>GPIO.wait_for_edge(pin_1, GPIO.RISING, timeout=1000)</code> </p> <p>If you want to use <code>pin</code> in your code, you must define it as <code>self.pin = pin</code> in the initiation of the object. (<strong>init</strong>). And then refer to it as <code>self.pin</code> anywhere in the class. You dont need to pass it as parameter in your update -> read_Sensor method in this case. Unless you got several pins, but then you need to pass a number to the read_Sensor method. You dont do that in your code. You dont pass any number to the update method.<br> pin in your case becomes Clocks <code>dt</code>, (delta time) as from the docs <a href="https://kivy.org/docs/api-kivy.clock.html" rel="nofollow">https://kivy.org/docs/api-kivy.clock.html</a></p> <p>If you look at the error you see that <code>int(pin)</code> was never set to be a input. As mentioned before <code>int(pin)</code> is the Clocks delta time, so it will never be the same. <code>RuntimeError: You must setup() the GPIO channel as an input first</code></p> <p>And just to show how you can rewrite this: </p> <pre><code>from kivy.app import App from kivy.clock import Clock from kivy.graphics import Color, Rectangle from kivy.properties import NumericProperty from kivy.uix.floatlayout import FloatLayout from kivy.uix.widget import Widget import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) pin_1 = 17 class MainLayout(FloatLayout): pass class bar(Widget): r = NumericProperty(1) def __init__(self, pin, p1, p2, s1, s2, **kwargs): super(bar, self).__init__(**kwargs) Clock.schedule_interval(self.update, 0.5) self.pin = pin def update(self, dt): if self.read_Sensor() == False: with self.canvas: Color(self.r, 0, 0, 1) Rectangle(pos=(p1,p2), size=(s1,s2)) else: with self.canvas: Color(self.r, 1, 1, 1) Rectangle(pos=(p1,p2), size=(s1,s2)) def read_Sensor(self, pin=self.pin): # you dont need to pass anything to this method. It will default to self.pin. But if you need it for other sensors, you can pass an integer. sensor = GPIO.wait_for_edge(pin, GPIO.RISING, timeout=1000) if sensor is None: return False else: return True class MainApp(App): def build(self): self.mainlayout = Widget() bar1 = bar(pin_1, 1, 10, 60, 100) self.mainlayout.add_widget(bar1) return self.mainlayout if __name__ == '__main__': MainApp().run() </code></pre>
0
2016-08-03T15:29:30Z
[ "python", "raspberry-pi", "kivy", "gpio" ]
Regular Expression to match multiple postive lookahead groups
38,732,671
<p>Here is the regex I have so far: </p> <pre><code>^(?=.*(option1|option2))(?=.*(option3|option4))(?=.*(option5|option6))(?=.*(option7|option8))(?=.*(option9|option10)).*$ </code></pre> <p>I am not hip on the regex language so I'll make my own definitions:</p> <p>category 1 is (option1|option2), category 2 is (option3|option4), category 3 is (option5|option6), etc.</p> <p>I would like to capture values where at least 1 option from 3 or more of the categories is found, like this:</p> <p>some text <strong>option3</strong> some more text <strong>option8</strong> some more text <strong>option1</strong></p> <p>OR</p> <p>some text <strong>option3</strong> some more text <strong>option8</strong> some more text <strong>option1</strong> some more text <strong>option6</strong></p> <p>I don't want to capture values like this:</p> <p>some text <strong>option3</strong> some more text <strong>option8</strong> - only 2 categories are represented</p> <p>OR </p> <p>some text <strong>option3</strong> some more text <strong>option4</strong> some more text <strong>option1</strong> (options 3 and 4 are from the same category)</p> <p>The options can appear in any order in the text, so that is why I was using the positive lookahead, but I don't know how to put a quantifier on multiple positive lookaheads. </p> <p>As far as regex engine goes, I have to use a front end UI that is powered by python in the background. I can only use regex, I don't have the ability to use any other python functions. Thanks!</p>
2
2016-08-03T00:49:28Z
38,732,724
<p>I don't think this is implementable with regex, or if it is (maybe in some steps), it's not a proper way to go.</p> <p>Instead you can store your options in a set like:</p> <pre><code>options = {(option1, option2), (option3, option4), (option5, option6), (option7, option8), (option9, option10)} </code></pre> <p>Then check the membership like following:</p> <pre><code>if sum(i in my_text or j in my_text for i, j in options) &gt;= 3: # do something </code></pre> <p>Here is a Demo:</p> <pre><code>&gt;&gt;&gt; s1 = "some text option8 some more text option3 some more text option1" &gt;&gt;&gt; s2 = "some text option3 some more text option4 some more text option1" &gt;&gt;&gt; s3 = "some text option3 some more text option8" &gt;&gt;&gt; &gt;&gt;&gt; options = {('option1', 'option2'), ('option3', 'option4'), ('option5', 'option6'), ('option7', 'option8'), ('option9', 'option10')} &gt;&gt;&gt; &gt;&gt;&gt; sum(i in s1 or j in s1 for i, j in options) 3 &gt;&gt;&gt; sum(i in s2 or j in s2 for i, j in options) 2 &gt;&gt;&gt; sum(i in s3 or j in s3 for i, j in options) 2 </code></pre>
1
2016-08-03T00:57:39Z
[ "python", "regex", "regex-lookarounds" ]
Regular Expression to match multiple postive lookahead groups
38,732,671
<p>Here is the regex I have so far: </p> <pre><code>^(?=.*(option1|option2))(?=.*(option3|option4))(?=.*(option5|option6))(?=.*(option7|option8))(?=.*(option9|option10)).*$ </code></pre> <p>I am not hip on the regex language so I'll make my own definitions:</p> <p>category 1 is (option1|option2), category 2 is (option3|option4), category 3 is (option5|option6), etc.</p> <p>I would like to capture values where at least 1 option from 3 or more of the categories is found, like this:</p> <p>some text <strong>option3</strong> some more text <strong>option8</strong> some more text <strong>option1</strong></p> <p>OR</p> <p>some text <strong>option3</strong> some more text <strong>option8</strong> some more text <strong>option1</strong> some more text <strong>option6</strong></p> <p>I don't want to capture values like this:</p> <p>some text <strong>option3</strong> some more text <strong>option8</strong> - only 2 categories are represented</p> <p>OR </p> <p>some text <strong>option3</strong> some more text <strong>option4</strong> some more text <strong>option1</strong> (options 3 and 4 are from the same category)</p> <p>The options can appear in any order in the text, so that is why I was using the positive lookahead, but I don't know how to put a quantifier on multiple positive lookaheads. </p> <p>As far as regex engine goes, I have to use a front end UI that is powered by python in the background. I can only use regex, I don't have the ability to use any other python functions. Thanks!</p>
2
2016-08-03T00:49:28Z
38,734,652
<p>Here's a regex that does what you want (in <code>VERBOSE</code> mode):</p> <pre><code>^ (?= .* (?: option1 | option2 ) () )? (?= .* (?: option3 | option4 ) () )? (?= .* (?: option5 | option6 ) () )? (?= .* (?: option7 | option8 ) () )? (?= .* (?: option9 | option10 ) () )? .*$ (?: \1\2\3 | \1\2\4 | \1\2\5 | \1\3\4 | \1\3\5 | \1\4\5 | \2\3\4 | \2\3\5 | \2\4\5 | \3\4\5 ) </code></pre> <p>The empty groups serve as check boxes: if the enclosing lookahead doesn't succeed, a backreference to that group won't succeed. The non-capturing group at the end contains all possible combinations of three out of five backreferences.</p> <p>The limitations of this approach are obvious; you need only add one more set of <code>option</code>s for it to get completely out of hand. I think you'd be better off with a non-regex solution.</p>
1
2016-08-03T04:52:46Z
[ "python", "regex", "regex-lookarounds" ]
Matasano challenge Python Set 1-> 3, unknown errors in code
38,732,699
<p>I'm trying to solve the Matasano challenge set 1-> 3 that is Single-byte XOR cipher and reverse it . I think i understand the concept to solve but my solution is giving some errors : </p> <pre><code> Traceback (most recent call last): File "C:\crypto\python\breakXor.py", line 59, in &lt;module&gt; print(transforma(unhex)) File "C:\crypto\python\breakXor.py", line 51, in transforma if(scoreBoard(xored) &gt; r): File "C:\crypto\python\breakXor.py", line 40, in scoreBoard c=chr(i).lower() TypeError: an integer is required </code></pre> <p>I'm given this erros and i dont really understand why</p> <pre><code>import binascii freqs = { 'a': 0.08167, 'b': 0.01492, 'c': 0.02782, 'd': 0.04253, 'e': 0.12702, 'f': 0.02228, 'g': 0.02015, 'h': 0.06094, 'i': 0.06966, 'j': 0.00153, 'k': 0.00772, 'l': 0.04025, 'm': 0.02406, 'n': 0.06749, 'o': 0.07507, 'p': 0.01929, 'q': 0.00095, 'r': 0.05987, 's': 0.06327, 't': 0.09056, 'u': 0.02758, 'v': 0.00978, 'w': 0.02361, 'x': 0.00150, 'y': 0.01974, 'z': 0.00074, ' ': 0.19281 } def xor(xs, ys): return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys)) def scoreBoard(inp): r = 0 for i in inp: c=chr(i).lower() if c in freqs : r += freqs[c] return r def transforma(inp): r = 0 for i in range(0,256): xored = xor(inp,list(str(i))) if(scoreBoard(xored) &gt; r): resultado = scoreBoard(xored) indice = i return (indice,resultado) if __name__ == "__main__": inp = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' unhex = binascii.unhexlify(inp) print(transforma(unhex)) </code></pre> <p>Any improvements to the solution of an explanation for the erros and how to fix them would be awesome </p> <p>Ps : i'm a noob in python and in OOP so any advise is welcome </p>
0
2016-08-03T00:52:54Z
38,732,716
<p>xor is expecting 2 lists; you are passing it a list and an integer.</p>
0
2016-08-03T00:56:10Z
[ "python", "cryptography" ]
Matasano challenge Python Set 1-> 3, unknown errors in code
38,732,699
<p>I'm trying to solve the Matasano challenge set 1-> 3 that is Single-byte XOR cipher and reverse it . I think i understand the concept to solve but my solution is giving some errors : </p> <pre><code> Traceback (most recent call last): File "C:\crypto\python\breakXor.py", line 59, in &lt;module&gt; print(transforma(unhex)) File "C:\crypto\python\breakXor.py", line 51, in transforma if(scoreBoard(xored) &gt; r): File "C:\crypto\python\breakXor.py", line 40, in scoreBoard c=chr(i).lower() TypeError: an integer is required </code></pre> <p>I'm given this erros and i dont really understand why</p> <pre><code>import binascii freqs = { 'a': 0.08167, 'b': 0.01492, 'c': 0.02782, 'd': 0.04253, 'e': 0.12702, 'f': 0.02228, 'g': 0.02015, 'h': 0.06094, 'i': 0.06966, 'j': 0.00153, 'k': 0.00772, 'l': 0.04025, 'm': 0.02406, 'n': 0.06749, 'o': 0.07507, 'p': 0.01929, 'q': 0.00095, 'r': 0.05987, 's': 0.06327, 't': 0.09056, 'u': 0.02758, 'v': 0.00978, 'w': 0.02361, 'x': 0.00150, 'y': 0.01974, 'z': 0.00074, ' ': 0.19281 } def xor(xs, ys): return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys)) def scoreBoard(inp): r = 0 for i in inp: c=chr(i).lower() if c in freqs : r += freqs[c] return r def transforma(inp): r = 0 for i in range(0,256): xored = xor(inp,list(str(i))) if(scoreBoard(xored) &gt; r): resultado = scoreBoard(xored) indice = i return (indice,resultado) if __name__ == "__main__": inp = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' unhex = binascii.unhexlify(inp) print(transforma(unhex)) </code></pre> <p>Any improvements to the solution of an explanation for the erros and how to fix them would be awesome </p> <p>Ps : i'm a noob in python and in OOP so any advise is welcome </p>
0
2016-08-03T00:52:54Z
38,733,056
<p>Your algorithm is wrong, the <code>scoreBoard</code> similar this, refs <a href="https://github.com/tomdeakin/Matasano-Crypto-Challenges/blob/master/textutils.py" rel="nofollow">Matasano-Crypto-Challenges from github</a></p> <pre><code>def scoreBoard(text): text = text.upper() frequencies = {} for letter in text: if letter in frequencies: frequencies[letter] += 1. else: frequencies[letter] = 1. total = sum(frequencies.values()) for letter in frequencies.keys(): frequencies[letter] /= total score = 0.0 for l in freqs.keys(): if l not in frequencies: frequencies[l] = 0.0 score += math.sqrt(frequencies[l] * freqs[l]) return score </code></pre>
0
2016-08-03T01:49:20Z
[ "python", "cryptography" ]
Is there way merge PDF files in reportlib with python3?
38,732,722
<p>I want to merge several PDF files and make single PDF file</p> <p>but I couldnt find API in reportilb width python </p> <p>How can I find that?</p> <p>I also use ubuntu OS is there any good utility for my question?</p>
2
2016-08-03T00:57:34Z
38,732,749
<p>Use <a href="https://www.pdflabs.com/tools/pdftk-server/" rel="nofollow">pdftk</a>, a nice command-line tool for this kind of thing.</p>
2
2016-08-03T01:02:19Z
[ "python", "ubuntu" ]
readline() returns bracket
38,732,799
<p>I wrote some codes to get some lines from .txt like below and its keep returning lines with brackets which I did not intend. Could you help me?</p> <p>codes:</p> <pre><code>#!/bin/python i=1 f=open("name.txt","r") while(i&lt;=225): x=f.readline().splitlines() print("mol new %s.bgf"%(x)) i+=1 f.close() </code></pre> <p>name.txt</p> <pre><code>02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c 04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c 09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c 17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c 18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c </code></pre> <p>And it returns</p> <pre><code>mol new ['02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c'].bgf mol new ['04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c'].bgf mol new ['09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c'].bgf mol new ['17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c'].bgf mol new ['18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c'].bgf </code></pre>
4
2016-08-03T01:09:52Z
38,732,847
<p>The <code>readline</code> function reads a single line from the file. Then you ask to split the line into a <strong><em>list</em></strong> of lines (which will give you a list of only one line since that's what you have).</p> <p>Don't split the <em>single line</em>. Instead <em>strip</em> the string (to remove leading and trailing "white-space").</p> <p>Please read <a href="https://docs.python.org/3/library/stdtypes.html#string-methods" rel="nofollow">the string reference</a> for more information about both <a href="https://docs.python.org/3/library/stdtypes.html#str.splitlines" rel="nofollow"><code>splitlines</code></a> and <a href="https://docs.python.org/3/library/stdtypes.html#str.strip" rel="nofollow"><code>strip</code></a>.</p>
3
2016-08-03T01:17:57Z
[ "python", "readline" ]
readline() returns bracket
38,732,799
<p>I wrote some codes to get some lines from .txt like below and its keep returning lines with brackets which I did not intend. Could you help me?</p> <p>codes:</p> <pre><code>#!/bin/python i=1 f=open("name.txt","r") while(i&lt;=225): x=f.readline().splitlines() print("mol new %s.bgf"%(x)) i+=1 f.close() </code></pre> <p>name.txt</p> <pre><code>02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c 04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c 09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c 17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c 18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c </code></pre> <p>And it returns</p> <pre><code>mol new ['02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c'].bgf mol new ['04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c'].bgf mol new ['09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c'].bgf mol new ['17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c'].bgf mol new ['18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c'].bgf </code></pre>
4
2016-08-03T01:09:52Z
38,732,860
<p>This is because <code>f.readline().splitlines()</code> returns the line in a list form containing a single element. </p> <p>Try this instead:</p> <pre><code>x = f.readline().splitlines() x = x[0] </code></pre>
1
2016-08-03T01:20:14Z
[ "python", "readline" ]
readline() returns bracket
38,732,799
<p>I wrote some codes to get some lines from .txt like below and its keep returning lines with brackets which I did not intend. Could you help me?</p> <p>codes:</p> <pre><code>#!/bin/python i=1 f=open("name.txt","r") while(i&lt;=225): x=f.readline().splitlines() print("mol new %s.bgf"%(x)) i+=1 f.close() </code></pre> <p>name.txt</p> <pre><code>02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c 04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c 09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c 17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c 18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c </code></pre> <p>And it returns</p> <pre><code>mol new ['02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c'].bgf mol new ['04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c'].bgf mol new ['09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c'].bgf mol new ['17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c'].bgf mol new ['18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c'].bgf </code></pre>
4
2016-08-03T01:09:52Z
38,732,890
<p>Making minimal changes to your code, try:</p> <pre><code>i=1 f=open("name.txt","r") while(i&lt;=225): x=f.readline().rstrip('\n') print("mol new %s.bgf"%(x)) i+=1 f.close() </code></pre> <p>This produces output like:</p> <pre><code>mol new 02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c.bgf mol new 04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c.bgf mol new 09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c.bgf mol new 17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c.bgf mol new 18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c.bgf </code></pre> <p>Further improvements:</p> <pre><code>with open("name.txt","r") as f: for i, line in enumerate(f): if i &gt;= 225: break print("mol new %s.bgf"%(line.rstrip('\n'))) </code></pre> <p>Notes:</p> <ol> <li><p>You want to use <code>with open("name.txt","r") as f</code> to assure that the file <code>f</code> gets closed regardless.</p></li> <li><p>Looping over <code>i</code> as a counter as in <code>i=1; while(i&lt;=225): i+=1</code> is not pythonic. Use enumerate instead.</p></li> <li><p><code>readline</code> reads in a line. There is no need for <code>splitlines</code>.</p></li> <li><p>By looping over the lines in the file with <code>for i, line in enumerate(f):</code>, we eliminate the need to read the whole file in at once. This makes the program suitable for handling very large files.</p></li> <li><p>In python, when a line is read from a file, it still has the newline at the end of it. We use <code>rstrip('\n')</code> to safely remove it.</p></li> </ol>
4
2016-08-03T01:24:51Z
[ "python", "readline" ]
readline() returns bracket
38,732,799
<p>I wrote some codes to get some lines from .txt like below and its keep returning lines with brackets which I did not intend. Could you help me?</p> <p>codes:</p> <pre><code>#!/bin/python i=1 f=open("name.txt","r") while(i&lt;=225): x=f.readline().splitlines() print("mol new %s.bgf"%(x)) i+=1 f.close() </code></pre> <p>name.txt</p> <pre><code>02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c 04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c 09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c 17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c 18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c </code></pre> <p>And it returns</p> <pre><code>mol new ['02.ala.r49r50.TRK820.no_0.rnd_1.c14421.f.c'].bgf mol new ['04.ala.r44r45.TRK820.no_0.rnd_1.c48608.h.c'].bgf mol new ['09.ala.r46r47.TRK820.no_0.rnd_1.c14682.t.c'].bgf mol new ['17.ala.r47r48.TRK820.no_0.rnd_1.c9610.th.c'].bgf mol new ['18.ala.r48r49.TRK820.no_59.rnd_1.c19106.t.c'].bgf </code></pre>
4
2016-08-03T01:09:52Z
38,732,935
<p>You don't need to call the splitlines() method on the results of readline()<p> file.readline() returns one line of the file, including the trailing newline. <p> .splitlines() is getting rid of the newline by using it as a delimiter and giving you a LIST of lines with only 1 item. The brackets are coming from the str representation of that 1 item list</p> <p>you want this:</p> <pre><code>x = f.readline().rstrip() </code></pre> <p>to remove the newline or you could also <em>slice</em> off the newline like this</p> <pre><code>x = f.readline()[:-1] </code></pre> <p>another thing you might consider is changing your code to use the file object as an iterable. It is more idiomatic in Python to write</p> <pre><code>for line in fileobject: print line[:-1] </code></pre> <p>than to use a while loop and .readline()</p>
1
2016-08-03T01:31:15Z
[ "python", "readline" ]
Create object which has nested orderDict
38,732,803
<p>my store_categories_data has a nested orderDict like below</p> <pre><code>store_categories_data OrderedDict([('product', OrderedDict([('image', OrderedDict([('image', &lt;InMemoryUploadedFile: bag.jpg (image/jpeg)&gt;)])), ('name_of_product', 'Ladies Pink Bag'), ('description', 'description'), ('price', Decimal('1600')), ('active', True)])), ('store_category', 'BAGS')]) </code></pre> <p>I want to pass all the product information like Image, Name, Description etc. But there is 3 orderDict. How can i pass value to get_or_create() for creating store_categories object?</p> <p><strong>My code</strong></p> <pre><code>class ProductSerializers(ModelSerializer): image = ProductImageSerializer() class Meta: model = Product fields=('id','image','name_of_product','description','price','active',) class StoreCategorySerializer(ModelSerializer): product = ProductSerializers() class Meta: model = StoreCategory class StoreCreateSerializer(ModelSerializer): store_categories = StoreCategorySerializer() merchant = UserSerializer() class Meta: model = Store fields=("id", "merchant", "store_categories", "name_of_legal_entity", "pan_number", "registered_office_address", "name_of_store", "store_contact_number", "store_long", "store_lat", "store_start_time", "store_end_time", "store_off_day", ) def create(self,validated_data): store_categories_data = validated_data.pop('store_categories') merchant_data = validated_data.pop('merchant') for merchantKey, merchantVal in merchant_data.items(): try: merchant,created = User.objects.get_or_create(username=merchantVal) print('merchant',merchant) print(type(merchant)) validated_data['merchant']=merchant store = Store.objects.create(**validated_data) print('__________________________________') image = store_categories_data["product"].pop("image") image_instance = ProductImage(**image) print('image_instance',image_instance) product = store_categories_data["product"] print('product creation returns',product['name_of_product']) product_instance = Product( image=image_instance, name_of_product=product['name_of_product'], description=product['description'], price=product['price'], active=product['active'] ) print('product_instance',product_instance) store_category = store_categories_data['store_category'] print('store_category',store_category) store_category = StoreCategory(product=product_instance, store_category=store_category) print('store category instance',store_category) return store except User.DoesNotExist: raise NotFound('not found') </code></pre> <p><strong>Models.py</strong></p> <pre><code>class Store(models.Model): merchant = models.ForeignKey(User) name_of_legal_entity = models.CharField(max_length=250) pan_number = models.CharField(max_length=20) registered_office_address = models.CharField(max_length=200) name_of_store = models.CharField(max_length=100) store_off_day = MultiSelectField(choices=DAY, max_length=7, default='Sat') store_categories = models.ManyToManyField('StoreCategory',blank=True) class Product(models.Model): store = models.ForeignKey(Store) image = models.ForeignKey('ProductImage',blank=True,null=True) name_of_product = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=20) active = models.BooleanField(default=True) class ProductImage(models.Model): image = models.ImageField(upload_to='products/images/') @property def imageName(self): return str(os.path.basename(self.image.name)) class StoreCategory(models.Model): product = models.ForeignKey(Product,null=True, on_delete=models.CASCADE,related_name="store_category") store_category = models.CharField(choices=STORE_CATEGORIES, default='GROCERY', max_length=10) </code></pre>
1
2016-08-03T01:10:15Z
38,735,241
<p>assuming the nesting in your OrderedDict maps to foreign key relationships in a relational database, you just need to explicitly create all 3 records in order, from the inside out. Something like the below should be enough to carry it the rest of the way.</p> <p>Note: unpacking dicts to keyword args with <code>**</code> only works for newer versions of python >= <code>Python3.5</code>.</p> <pre><code>image = store_categories_data["product"].pop("image") image_instance = Image(**image) product = store_categories_data["product"] product_instance = Product(image=image_instance, product=product) store_category = store_categories_data['store_category'] store_category = StoreCategory(product=product_instance, store_category=store_category) </code></pre>
0
2016-08-03T05:39:12Z
[ "python", "django", "api", "python-3.x", "django-rest-framework" ]
Count number of characters for each line pyspark
38,732,846
<p>I am able to count total number of each character in the entire document.</p> <p>My document:</p> <pre><code>ATATCCCCGGGAT ATCGATCGATAT </code></pre> <p>Calculating total number of each characters in the document:</p> <pre><code>data=sc.textFile("data.txt") counts=data.flatMap(lambda x:[(c,1) for c in x]).reduceByKey(add) </code></pre> <p>Result:</p> <pre><code>[(u'A', 7), (u'C', 6), (u'T', 7), (u'G', 5)] </code></pre> <p>My Implementation<br></p> <pre><code>counts=data.map(lambda x:[(c,1)for c in x]) for row in counts.collect(): print sc.parallelize(row).reduceByKey(lambda x,y:x+y).collect() </code></pre> <p>Is there a better way to do it?</p>
0
2016-08-03T01:17:43Z
38,749,464
<p>Try:</p> <pre><code>&gt;&gt;&gt; counts.values().sum() 25 </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; sum(counts.collectAsMap().values()) 25 </code></pre>
1
2016-08-03T16:50:56Z
[ "python", "apache-spark", "pyspark" ]
Count number of characters for each line pyspark
38,732,846
<p>I am able to count total number of each character in the entire document.</p> <p>My document:</p> <pre><code>ATATCCCCGGGAT ATCGATCGATAT </code></pre> <p>Calculating total number of each characters in the document:</p> <pre><code>data=sc.textFile("data.txt") counts=data.flatMap(lambda x:[(c,1) for c in x]).reduceByKey(add) </code></pre> <p>Result:</p> <pre><code>[(u'A', 7), (u'C', 6), (u'T', 7), (u'G', 5)] </code></pre> <p>My Implementation<br></p> <pre><code>counts=data.map(lambda x:[(c,1)for c in x]) for row in counts.collect(): print sc.parallelize(row).reduceByKey(lambda x,y:x+y).collect() </code></pre> <p>Is there a better way to do it?</p>
0
2016-08-03T01:17:43Z
38,757,187
<p>If what you want is "Count the number of characters for each line with pyspark" and <strong>not</strong> the total number of each characters for each line, this will do the trick:</p> <pre><code>data.map(lambda x:len(x)).collect() &gt;&gt;&gt; [13, 12] </code></pre> <p>If you want the index of the line among the number of characters:</p> <pre><code>data.map(lambda x:len(x)).zipWithIndex().collect() &gt;&gt;&gt; [(13, 0), (12, 1)] </code></pre> <p>Now, to count the number of each character for each line, this may help:</p> <pre><code>def count_occur(str): uniq = set(str) li = list(str) dict = {} for key in uniq: dict[key] = str.count(key) return dict data.map(lambda x: count_occur(x)).collect() &gt;&gt;&gt; [{'C': 4, 'T': 3, 'A': 3, 'G': 3}, {'C': 2, 'T': 4, 'A': 4, 'G': 2}] </code></pre> <p>Again, if you want the index of the line <code>zipWithIndex</code> do the trick:</p> <pre><code>data.map(lambda x: count_occur(x)).zipWithIndex().collect() &gt;&gt;&gt; [({'C': 4, 'T': 3, 'A': 3, 'G': 3}, 0), ({'C': 2, 'T': 4, 'A': 4, 'G': 2}, 1)] </code></pre> <p>Hope it helps.</p>
0
2016-08-04T01:43:17Z
[ "python", "apache-spark", "pyspark" ]
Join and delete lines
38,732,944
<p>NOTE: The solution needs to be something I can embed in python. </p> <p>I have a file with 800,000+ lines. The lines are grouped. The beginning of each group of rows starts with "IMAGE" followed by one row that starts with "HISTO" and then at least one, but usually multiple, rows that start with "FRAG".</p> <p>I need to:<br> 1. Delete/discard any row that starts with "HISTO".<br> 2. For each "FRAG" line I need to join it with the previous "IMAGE" row. Here is an example. </p> <pre><code>IMAGE ...data1... HISTO usually numbers 0 0 1 1 0 1 0 FRAG ...data1... FRAG ...data2... IMAGE ...data2... HISTO usually numbers 0 0 1 1 0 1 0 FRAG ...data1... FRAG ...data2... FRAG ...data3... FRAG ...data4... </code></pre> <p>The result needs to look like this: </p> <pre><code>IMAGE ...data1... FRAG ...data1... IMAGE ...data1... FRAG ...data2... IMAGE ...data2... FRAG ...data1... IMAGE ...data2... FRAG ...data2... IMAGE ...data2... FRAG ...data3... IMAGE ...data2... FRAG ...data4... </code></pre> <p>It is possible to have many FRAG lines before it starts over with an IMAGE line. </p> <p>This is based on a previous question but now I need to use python for some consistency. Here is the code I was using that works. </p> <pre><code>&gt; sed 's/&gt;//' Input.txt|awk '/^IMAGE/{a=$0;next;} /^FRAG/{print "&gt;"a,$0}' </code></pre> <p>Credit to AwkMan for the previous solution.</p>
-1
2016-08-03T01:33:22Z
38,733,003
<h3>Python solution</h3> <pre><code>with open('Input.txt') as f: for line in f: line = line.rstrip() if line.startswith('&gt;IMAGE'): img = line continue if line.startswith('&gt;HIST'): continue print('%s %s' % (img, line.lstrip('&gt;'))) </code></pre> <p>This produces:</p> <pre><code>&gt;IMAGE ...data1... FRAG ...data1... &gt;IMAGE ...data1... FRAG ...data2... &gt;IMAGE ...data2... FRAG ...data1... &gt;IMAGE ...data2... FRAG ...data2... &gt;IMAGE ...data2... FRAG ...data3... &gt;IMAGE ...data2... FRAG ...data4... </code></pre> <h3>Awk solution</h3> <p>Try:</p> <pre><code>awk '/^&gt;IMAGE/{img=$0;next} /^&gt;HISTO/{next} {print img,substr($0,2)}' Input.txt </code></pre> <h3>Example</h3> <p>With this as the input file:</p> <pre><code>$ cat Input.txt &gt;IMAGE ...data1... &gt;HISTO usually numbers 0 0 1 1 0 1 0 &gt;FRAG ...data1... &gt;FRAG ...data2... &gt;IMAGE ...data2... &gt;HISTO usually numbers 0 0 1 1 0 1 0 &gt;FRAG ...data1... &gt;FRAG ...data2... &gt;FRAG ...data3... &gt;FRAG ...data4... </code></pre> <p>Our code produces:</p> <pre><code>$ awk '/^&gt;IMAGE/{img=$0;next} /^&gt;HISTO/{next} {print img,substr($0,2)}' Input.txt &gt;IMAGE ...data1... FRAG ...data1... &gt;IMAGE ...data1... FRAG ...data2... &gt;IMAGE ...data2... FRAG ...data1... &gt;IMAGE ...data2... FRAG ...data2... &gt;IMAGE ...data2... FRAG ...data3... &gt;IMAGE ...data2... FRAG ...data4... </code></pre> <h3>How it works</h3> <p>Awk implicitly reads through a file line by line. We save the IMAGE line in the variable <code>img</code> and print out FRAG lines as they occur.</p> <p>In more detail:</p> <ul> <li><p><code>/^&gt;IMAGE/{img=$0;next}</code></p> <p>For any line that begins with <code>&gt;IMAGE</code>, we save the line in the variable <code>img</code> and then skip the rest of the commands and jump to start over on the <code>next</code> line.</p></li> <li><p><code>/^&gt;HISTO/{next}</code></p> <p>For any line that begins with <code>&gt;HISTO</code>, we skip the rest of the commands and jump to start over on the <code>next</code> line.</p></li> <li><p><code>print img,substr($0,2)</code></p> <p>For all other lines, we print <code>img</code> followed by the current line minus its first character (which is <code>&gt;</code> in the sample input).</p></li> </ul>
1
2016-08-03T01:40:48Z
[ "python" ]
Join and delete lines
38,732,944
<p>NOTE: The solution needs to be something I can embed in python. </p> <p>I have a file with 800,000+ lines. The lines are grouped. The beginning of each group of rows starts with "IMAGE" followed by one row that starts with "HISTO" and then at least one, but usually multiple, rows that start with "FRAG".</p> <p>I need to:<br> 1. Delete/discard any row that starts with "HISTO".<br> 2. For each "FRAG" line I need to join it with the previous "IMAGE" row. Here is an example. </p> <pre><code>IMAGE ...data1... HISTO usually numbers 0 0 1 1 0 1 0 FRAG ...data1... FRAG ...data2... IMAGE ...data2... HISTO usually numbers 0 0 1 1 0 1 0 FRAG ...data1... FRAG ...data2... FRAG ...data3... FRAG ...data4... </code></pre> <p>The result needs to look like this: </p> <pre><code>IMAGE ...data1... FRAG ...data1... IMAGE ...data1... FRAG ...data2... IMAGE ...data2... FRAG ...data1... IMAGE ...data2... FRAG ...data2... IMAGE ...data2... FRAG ...data3... IMAGE ...data2... FRAG ...data4... </code></pre> <p>It is possible to have many FRAG lines before it starts over with an IMAGE line. </p> <p>This is based on a previous question but now I need to use python for some consistency. Here is the code I was using that works. </p> <pre><code>&gt; sed 's/&gt;//' Input.txt|awk '/^IMAGE/{a=$0;next;} /^FRAG/{print "&gt;"a,$0}' </code></pre> <p>Credit to AwkMan for the previous solution.</p>
-1
2016-08-03T01:33:22Z
38,733,582
<p>Try this solution:</p> <pre><code>with open('in.txt', 'r') as fin, open('out.txt', 'w') as fout: for line in fin: if line.startswith('HISTO'): continue elif line.startswith('IMAGE'): prefix = line.strip() elif line.startswith('FRAG'): fout.write(prefix + ' ' + line) </code></pre> <p>Consider also that when you have an already working line command, like "John1024" awk command, you can execute it with a subprocess:</p> <pre><code>import subprocess with open('input.txt', 'r') as fin, open('out.txt', 'w') as fout: subprocess.run(["awk", "/^IMAGE/{img=$0;next} /^HISTO/{next} {print img,substr($0,1)}", "input.txt"], stdout=fout) </code></pre>
0
2016-08-03T02:49:04Z
[ "python" ]
Generalized numpy point-matrix multiplication function that produces consistent outputs with inputs of varying shapes
38,732,961
<p>I want to make a generalized function that does point-matrix transformations with inputs of varying shapes, using the following definitions:</p> <ul> <li>Array <code>p</code> is an array of points of any shape, with leaf elements of xyz vectors such as: (Parent shape P,...,leaf xyz vector p)</li> <li>Array <code>M</code> is an array of matrices of any shape, with leaf elements of shape (4,4) matrices such as: (Parent shape M,...,leaf (4,4) shape)</li> <li>The desired output should have the shape: <code>(Parent shape M, Parent shape P, leaf xyz vector p)</code></li> </ul> <p>Because i'm not quite clear as to how <code>numpy.dot</code> orders its output, i came up with a clumsy shape matching scheme. I look at the shape of <code>numpy.dot</code>, walk it until i find the index of the matching matrix "container shape", and then use the info to reshape the result into the desired input.</p> <p>Here's the code i came up with:</p> <pre><code>import numpy as np np.set_printoptions(suppress=True) def pointMatrixMultiply(p,M): """ Multiplies an array of 3D points p by an array of 4x4 transformation (4x4) matrices M. Both inputs can be of any shape as long as these 2 conditions are met at the leaf level: - p is a 3D (xyz) point - M is a right handed 4x4 transformation (4x4) where M[3,:3] is the translation vector Result: An array with shape corresponding to [parent matrix shape][point shape] ex: p.shape (3, 3, 3) x M.shape (2, 4, 4) = (2, 3, 3, 3) P P p M m m M P P p ex: p.shape (2, 4, 3, 3) x M.shape (6, 3, 4, 4) = (6, 3, 2, 4, 3, 3) P P P p M M m m M M P P P p """ # Debug input print 'p.shape: %s'%str(p.shape) print 'M.shape: %s'%str(M.shape) dot = np.dot(p[...,:3],M[...,:3,:3]) + M[...,3,:3] print 'dot.shape: %s'%str(dot.shape) # Reorder dot to match our desired output scheme. # I won't lie, this part below is a montrous hack that i'm not proud of. a = list(dot.shape) b = list(M.shape[:-2]) match = [range(i, i+len(b)) for i in range(len(a))[::-1] if a[i:i+len(b)] == b][0][::-1] if match: match = match[0:1] + match[1:][::-1] diff = [i for i in range(len(a)) if not i in match] indices = match + diff print 'indices: %s'%indices dot = np.transpose(dot,indices) print 'dot.shape: %s'%str(dot.shape) # Get rid of empty dimentions? dot = np.squeeze(dot) print 'match: %s'%str(dot.shape[-len(p.shape):] == p.shape) print '' print '' print dot return dot </code></pre> <p>And are some test values:</p> <pre><code># Sample points to transform. p = np.array([[-0.023846 , -0.81775031, -0.57507895], [-0.86622112, -0.04231112, 0.49786619], [ 0.97552607, 0.19235066, 0.10653691]]) # A sample 4x4 Transformation Matrix. # Translation is set to p[0] so that when multiplied with the # inverse matrix, p[...,0,:] = [0,0,0] M = np.array([[ 0.07396536, 0.77190679, 0.63141827, 0. ], [-0.66843676, 0.50824585, -0.54302713, 0. ], [-0.74008204, -0.38189798, 0.55356346, 0. ], [ p[0][0] , p[0][1] , p[0][2] , 1. ]]) # Different mix and match scenarions, uncomment as you wish #p = p[0] # A #p = np.array([p,p]) # B #p = np.array([p,p,p]) # C #M = np.array([M,M,M]) # D #M = np.array([M,M]) # E # Inverse M so that result will show that p[...,0,:] = [0,0,0] I = np.linalg.inv(M) pointMatrixMultiply(p,I) # Results: #p.shape: (3L, 3L) #M.shape: (4L, 4L) #dot.shape: (3L, 3L) #match: True #[[-0. 0. 0. ] #[ 1.21373736 0.37454991 0.92123126] #[ 1.28400743 -0.52477331 -0.74805521]] </code></pre> <p>Unfortunately my flawed scheme gets confused, usually when both points and matrices have similar <code>container shapes</code>. And i'm sure i'm making this waaaay more complex than i need it to. So i'm hoping somebody can show me the proper way to get my desired output </p>
2
2016-08-03T01:35:14Z
38,733,517
<p>I like to make test cases where dimensions differ as much as possible. So for example if <code>p</code> has a last dimension of <code>3</code>, the first will anything but 3. And if the last dimensions of <code>M</code> are <code>(4,4)</code> I'd avoid use of 4 in the other dimensions as well. That way if the correct dimensions don't line up I get quick and obvious errors.</p> <pre><code>p.shape (3, 3, 3) x M.shape (2, 4, 4) = (2, 3, 3, 3) P P p M m m M P P p p.shape (2, 4, 3, 3) x M.shape (6, 3, 4, 4) = (6, 3, 2, 4, 3, 3) P P P p M M m m M M P P P p </code></pre> <p>Does it matter whether the first dimensions are 2d or 1d? In other words can I combine a <code>(P,3)</code> array with a <code>(M,4,4)</code>? Say a (2,3) with a (1,4,4)?</p> <p>Usually when using <code>dot</code> or <code>einsum</code> (a potentially useful alternative) one or more of the dimensions match, e.g.</p> <pre><code>np.einsum('ijk,lmk-&gt;ijlm',A,B) # sum on last dimension (2,3,4),(5,6,4)-&gt;(2,3,5,6) </code></pre> <p>Sometimes the arrays shapes almost write the <code>einsum</code> expression directly</p> <pre><code>M = np.array([[ 0.07396536, 0.77190679, 0.63141827, 0. ], [-0.66843676, 0.50824585, -0.54302713, 0. ], [-0.74008204, -0.38189798, 0.55356346, 0. ], [ p[0,0] , p[0,1] , p[0,2] , 1. ]]) </code></pre> <p>In this expression, <code>M</code> looks like a (3,3) array concatenated with a row of <code>p</code>, and the extra column.</p> <pre><code>M = np.hstack((np.vstack((m,p[0,:])),np.array([0,0,0,1])[:,None])) </code></pre> <p>With einsum, this expression is:</p> <pre><code>dot = np.dot(p[...,:3],M[...,:3,:3]) + M[...,3,:3] np.einsum('...i,...ij-&gt;...j', p, M[...,:3,:3]) + M[...,3,:3] </code></pre> <p>But why <code>p[...,:3]</code>? Isn't <code>p</code> guaranteed to have a size 3 last dim?</p> <p>How does that last dimension of <code>p</code> combine with the last 2 of <code>M</code>? Sum on the 2nd to the last. The addition is the last <code>row</code> of <code>M</code> (selected on 2nd to the last dim), a <code>p</code> like value. With <code>:3</code>, the last column of <code>M</code> is not used, right? In these expressions, the <code>...</code> represent exactly the same dimensions (possibly generalized in numpy broadcasting terms).</p> <p>=====================</p> <p>Is this the kind of calculation you are doing?</p> <pre><code>In [58]: np.dot(np.ones((2,5,3)),np.ones((7,8,3,3))).shape Out[58]: (2, 5, 7, 8, 3) </code></pre> <p>The <code>einsum</code> equivalent is:</p> <pre><code>In [59]: np.einsum('ijp,klpq-&gt;ijklq',np.ones((2,5,3)),np.ones((7,8,3,3))).shape Out[59]: (2, 5, 7, 8, 3) </code></pre> <p>and just to make sure I am pairing the last dimensions right</p> <pre><code>In [60]: np.dot(np.ones((2,5,3)),np.ones((7,8,3,1))).shape Out[60]: (2, 5, 7, 8, 1) In [61]: np.einsum('ijp,klpq-&gt;ijklq',np.ones((2,5,3)),np.ones((7,8,3,1))).shape Out[61]: (2, 5, 7, 8, 1) </code></pre> <p>This a case where <code>dot</code> is better, since <code>einsum</code> iterates on a product dimension space, which with 6 dimensions will get awfully large. </p> <p>My original einsum is equivalent to:</p> <pre><code>np.einsum('...i,...ij-&gt;...j', p, M[...,:3,:3]) np.einsum('ijp,ijpq-&gt;ijq`, p, M[...,:3,:3]) </code></pre> <p>In other words, it keeps the initial <code>ij</code> dimensions coordinated, rather than broadcasting to a large space.</p> <pre><code>In [62]: np.einsum('...p,...pq-&gt;...q', np.ones((2,5,3)), np.ones((2,5,3,1))).shape Out[62]: (2, 5, 1) </code></pre>
0
2016-08-03T02:42:38Z
[ "python", "arrays", "numpy", "matrix" ]
Python import fails when called from PHP Page
38,732,974
<p>When I am running my code from the terminal I am getting the output. But when I am running the same from my php page using the following:</p> <pre><code>$command = escapeshellcmd($commandstring); $output = shell_exec($command); </code></pre> <p>It gives no output..no error..nothing..</p> <p>When I remove this import from my python code</p> <pre><code>from sklearn.ensemble import RandomForestClassifier </code></pre> <p>then it shows an error in output</p> <blockquote> <p>name 'RandomForestClassifier' is not defined</p> </blockquote> <p>then I used</p> <pre><code>import sys; print sys.path </code></pre> <p>to see the differences b/w running from PHP and from terminal</p> <pre><code>.local/lib/python2.7/site-packages </code></pre> <p>this one is not there while running from the php.</p> <p>Any permanent solution for this?</p> <p>It will be better for me if I can fix it with the php code itself. </p> <p>Well I am able to run other python code from php easily and they are showing the output. But this one has to import this line</p> <pre><code>from sklearn.ensemble import RandomForestClassifier </code></pre>
0
2016-08-03T01:37:14Z
38,733,025
<p>You can try to add " 2>&amp;1" at the end of $commandstring, so the stderr will be redirect to stdout and will be catched by shell_exec(). Maybe some error message will appear.</p> <p>If this didn't solve your issue, try to run a simple "Hello world" python script from your PHP. You will know if the problem come from the PHP part or the python part.</p>
0
2016-08-03T01:45:27Z
[ "php", "python" ]
Using openpyxl to search for a cell in one column and then to print out the row for that relevant cell
38,732,979
<p>For instance, I want to be able to type into my program via user input the data and then print the row relevant to that cell. Ideally, if 1/08/2016 was inputted into the program then it will run through column 'A' and then locates the relevant date. If date is found then it will print the date and then the relevant data in that row. This is what I have currently below. Any type of suggestions will be great if a direct answer cannot be found.</p> <p>EDIT: I changed x to date.</p> <pre><code>from openpyxl import * wb = load_workbook('C:/Users/W-_-C/PycharmProjects/IT SAT_data doc.xlsx') ws = wb.get_sheet_by_name('101') date = input("Prompt: ") for row in ws.iter_rows('A{}:A{}'.format(ws.min_row, ws.max_row)): for cell in row: if ws.cell(row=row, column=0).value == date: print(ws.cell.value) </code></pre>
0
2016-08-03T01:37:26Z
38,760,574
<p>If you only want to look in column A for the input I would do something like this:</p> <pre><code>for i in range(1,ws.max_row): if ws.cell(row=row, column=0).value == date: for j in range(i, ws.max_column): print (ws.cell(row=i, column=j).value) </code></pre> <p>Assuming you want to print every column on the row matching the input</p>
0
2016-08-04T07:04:34Z
[ "python", "excel", "openpyxl" ]
I am getting this error using django taggit "Can't call add with a non-instance manager"
38,733,072
<p>I'm trying to add a few tags to my post object when I save them, using django taggit. So I tried this</p> <pre><code> def panties(): from lxml import html pan_url = 'http://www.ideos.org' shtml = requests.get(pan_url, headers=headers) soup = BeautifulSoup(shtml.text, 'html5lib') video_row = soup.find_all('div', {'class': 'video'}) name = 'pan videos' author = User.objects.get(id=1) tags = Post.tags.add("Musica", "video") &lt;------here def youtube_link(url): youtube_page = requests.get(url, headers=headers) soupdata = BeautifulSoup(youtube_page.text, 'html5lib') video_row = soupdata.find_all('script', {'type': 'text/javascript'}) entries = [{'text': str(div), } for div in video_row] tubby = str(entries[4]) urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tubby) return urls def embed(url): new_embed = url.replace("watch?v=", "embed/") return new_embed entries = [{'href': div.a.get('href'), 'src': youtube_link(div.a.get('href'))[1], 'text': div.h4.text, 'comments': div.h4.text, 'name': name, 'url': div.a.get('href'), 'embed': embed(youtube_link(div.a.get('href'))[0]), 'author': author, 'video': True, 'tag': tags &lt;------here } for div in video_row][:13] </code></pre> <p>but that gave me the error message</p> <pre><code>Can't call add with a non-instance manager </code></pre> <p>So I then tried this</p> <pre><code> def panties(): from lxml import html pan_url = 'http://www.ideos.org' shtml = requests.get(pan_url, headers=headers) soup = BeautifulSoup(shtml.text, 'html5lib') video_row = soup.find_all('div', {'class': 'video'}) name = 'pan videos' author = User.objects.get(id=1) post = Post() &lt;------created instance tags = post.tags.add("Musica", "video") def youtube_link(url): youtube_page = requests.get(url, headers=headers) soupdata = BeautifulSoup(youtube_page.text, 'html5lib') video_row = soupdata.find_all('script', {'type': 'text/javascript'}) entries = [{'text': str(div), } for div in video_row] tubby = str(entries[4]) urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tubby) return urls def embed(url): new_embed = url.replace("watch?v=", "embed/") return new_embed entries = [{'href': div.a.get('href'), 'src': youtube_link(div.a.get('href'))[1], 'text': div.h4.text, 'comments': div.h4.text, 'name': name, 'url': div.a.get('href'), 'embed': embed(youtube_link(div.a.get('href'))[0]), 'author': author, 'video': True, 'tag': tags } for div in video_row][:13] </code></pre> <p>and it gave me this error message</p> <p>Post objects need to have a primary key value before you can access their tags. How Can I make this work? is what I'm doing even possible? Any help would be appreciated.</p>
0
2016-08-03T01:51:41Z
38,735,096
<p>You are trying to add tags to the Post manager. You want to add tags to a Post instance.</p> <p>You need a saved Post instance before you can add the tags</p> <p>e.g.</p> <p><code>post_instance = Post.objects.get_or_create(foo=bar) tags = post_instance.tags.add("Musica", "video") </code></p>
1
2016-08-03T05:28:44Z
[ "python", "django", "django-taggit" ]
I am getting this error using django taggit "Can't call add with a non-instance manager"
38,733,072
<p>I'm trying to add a few tags to my post object when I save them, using django taggit. So I tried this</p> <pre><code> def panties(): from lxml import html pan_url = 'http://www.ideos.org' shtml = requests.get(pan_url, headers=headers) soup = BeautifulSoup(shtml.text, 'html5lib') video_row = soup.find_all('div', {'class': 'video'}) name = 'pan videos' author = User.objects.get(id=1) tags = Post.tags.add("Musica", "video") &lt;------here def youtube_link(url): youtube_page = requests.get(url, headers=headers) soupdata = BeautifulSoup(youtube_page.text, 'html5lib') video_row = soupdata.find_all('script', {'type': 'text/javascript'}) entries = [{'text': str(div), } for div in video_row] tubby = str(entries[4]) urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tubby) return urls def embed(url): new_embed = url.replace("watch?v=", "embed/") return new_embed entries = [{'href': div.a.get('href'), 'src': youtube_link(div.a.get('href'))[1], 'text': div.h4.text, 'comments': div.h4.text, 'name': name, 'url': div.a.get('href'), 'embed': embed(youtube_link(div.a.get('href'))[0]), 'author': author, 'video': True, 'tag': tags &lt;------here } for div in video_row][:13] </code></pre> <p>but that gave me the error message</p> <pre><code>Can't call add with a non-instance manager </code></pre> <p>So I then tried this</p> <pre><code> def panties(): from lxml import html pan_url = 'http://www.ideos.org' shtml = requests.get(pan_url, headers=headers) soup = BeautifulSoup(shtml.text, 'html5lib') video_row = soup.find_all('div', {'class': 'video'}) name = 'pan videos' author = User.objects.get(id=1) post = Post() &lt;------created instance tags = post.tags.add("Musica", "video") def youtube_link(url): youtube_page = requests.get(url, headers=headers) soupdata = BeautifulSoup(youtube_page.text, 'html5lib') video_row = soupdata.find_all('script', {'type': 'text/javascript'}) entries = [{'text': str(div), } for div in video_row] tubby = str(entries[4]) urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tubby) return urls def embed(url): new_embed = url.replace("watch?v=", "embed/") return new_embed entries = [{'href': div.a.get('href'), 'src': youtube_link(div.a.get('href'))[1], 'text': div.h4.text, 'comments': div.h4.text, 'name': name, 'url': div.a.get('href'), 'embed': embed(youtube_link(div.a.get('href'))[0]), 'author': author, 'video': True, 'tag': tags } for div in video_row][:13] </code></pre> <p>and it gave me this error message</p> <p>Post objects need to have a primary key value before you can access their tags. How Can I make this work? is what I'm doing even possible? Any help would be appreciated.</p>
0
2016-08-03T01:51:41Z
38,750,035
<p>With the aide of @luke_aus answer I figured it out. this is just what my code looks like now for others who may want to see how to actually do it. It went from this.</p> <pre><code> for entry in entries: post = Post() post.title = entry['text'] title = post.title if not Post.objects.filter(title=title): post.title = entry['text'] post.name = entry['name'] post.url = entry['url'] post.body = entry['comments'] post.image_url = entry['src'] post.video_path = entry['embed'] post.author = entry['author'] post.video = entry['video'] post.status = 'draft' post.save() </code></pre> <p>to this</p> <pre><code> for entry in entries: post = Post() post.title = entry['text'] title = post.title if not Post.objects.filter(title=title): post.title = entry['text'] post.name = entry['name'] post.url = entry['url'] post.body = entry['comments'] post.image_url = entry['src'] post.video_path = entry['embed'] post.author = entry['author'] post.video = entry['video'] post.status = 'draft' post.save() saved_post = Post.objects.get(title=title) tags = saved_post.tags.add("Musica", "video") post.tags = tags post.save() </code></pre> <p>hope this helps someone</p>
0
2016-08-03T17:21:39Z
[ "python", "django", "django-taggit" ]
Django JSON AJAX data order not right when attached to table
38,733,160
<p>What I want is, at the front-end, when the button pressed, retrieve the data from the back-end using Ajax, then attach them to a table. I'm using Django 1.9.</p> <p>I managed to do so. However, each value does not match each column, just as the picture shows:</p> <p><img src="http://i.stack.imgur.com/cdxzC.png" alt="data Order is not right"></p> <p>So that is my problem. CDK should be name, instead of price.</p> <p>In views.py, I have:</p> <pre><code>def ajax_dict(reuqest): dicWCWishlist = [{"CDK":"Fallout 4","Price":"¥199", "Addin-Date":"Gifted! Thank you!"}, {"CDK":"Far Cry Primal","Price":"€59.99", "Addin-Date":"2015-12-5"}, {"CDK":"iPhone 6S plus","Price":"$749", "Addin-Date":"2016-1-15"}, {"CDK":"wrong", "Price":"$$999", "Addin-Date":"1980-3-9"}] return JsonResponse(dicWCWishlist, safe = False) </code></pre> <p>In runAjax.html, I have:</p> <pre><code> $("#btnJJDBZ").click(function() { // alert("Boom!"); $.get("../ajax_dict/", function(res) { for(var i = 0; i &lt; res.length; i++) { var ntr = $("&lt;tr&gt;&lt;/tr&gt;"); $.each(res[i], function(key, value) { var ntd = $("&lt;td&gt;&lt;/td&gt;") ntd.html(value); ntr.append(ntd); }) $("#tbodyWishlist").append(ntr); } }); }); </code></pre> <p>Besides, more strangely, whenever I modify the views.py file, the received data order randomly change again. Like when I add a space at any end of the line, or I change price $749 to $750, save and refresh the page, then the price column data moved to Add-in Date, or randomly under some column I don't know.</p> <h2>-------------------------------------------------------------------------</h2> <hr> <p>The problem is solved for now, thanks to @luke_aus 's help.</p> <p>In runAjax.html, change the jquery code with it follows:</p> <pre><code> $("#btnJJDBZ").click(function(){ $.get("../ajax_dict", function(res) { $.each(res, function(){ $.each(this, function(key, value){ var ntr = $("&lt;tr&gt;&lt;/tr&gt;"); var ntd1 = $("&lt;td class='CDK'&gt;&lt;/td&gt;"); var ntd2 = $("&lt;td class='Price'&gt;&lt;/td&gt;"); var ntd3 = $("&lt;td class='Addin-date'&gt;&lt;/td&gt;"); $.each(this, function(key, value){ switch(key){ case "CDK": ntd1.html(value); break; case "Price": ntd2.html(value); break; case "Addin-Date": ntd3.html(value); break; } }) ntr.append(ntd1).append(ntd2).append(ntd3); $("#tbodyWishlist").append(ntr); }); }); }); </code></pre> <p>I changed the data format, too.</p> <pre><code>dicWCWishlist = {"list":[{"CDK":"Fallout 4","Price":"¥199", "Addin-Date":"Gifted! Thank you!"}, {"CDK":"Far Cry Primal","Price":"€59.99", "Addin-Date":"2015-12-5"}, {"CDK":"iPhone 6S plus","Price":"$749", "Addin-Date":"2016-1-15"}, {"CDK":"wrong1", "Price":"$$999", "Addin-Date":"1980-3-9"}]} </code></pre> <p>What I did is basically, </p> <ol> <li>Create tr and 3 tds in advance</li> <li>When key comes, manually tell what key it is (using switch)</li> <li>Change the corresponded cell with correct value (using html())</li> </ol> <h2>However, the question is still there!</h2> <p>Why was my data order random?</p> <p>What did JsonResponse do to my JSON ?</p>
1
2016-08-03T02:00:45Z
38,735,769
<p>You can replace this</p> <pre><code>ntd.html(value); </code></pre> <p>with this</p> <pre><code>ntd.text(value) </code></pre> <p>Just try it,my brother.</p>
0
2016-08-03T06:15:23Z
[ "jquery", "python", "json", "ajax", "django" ]
Django JSON AJAX data order not right when attached to table
38,733,160
<p>What I want is, at the front-end, when the button pressed, retrieve the data from the back-end using Ajax, then attach them to a table. I'm using Django 1.9.</p> <p>I managed to do so. However, each value does not match each column, just as the picture shows:</p> <p><img src="http://i.stack.imgur.com/cdxzC.png" alt="data Order is not right"></p> <p>So that is my problem. CDK should be name, instead of price.</p> <p>In views.py, I have:</p> <pre><code>def ajax_dict(reuqest): dicWCWishlist = [{"CDK":"Fallout 4","Price":"¥199", "Addin-Date":"Gifted! Thank you!"}, {"CDK":"Far Cry Primal","Price":"€59.99", "Addin-Date":"2015-12-5"}, {"CDK":"iPhone 6S plus","Price":"$749", "Addin-Date":"2016-1-15"}, {"CDK":"wrong", "Price":"$$999", "Addin-Date":"1980-3-9"}] return JsonResponse(dicWCWishlist, safe = False) </code></pre> <p>In runAjax.html, I have:</p> <pre><code> $("#btnJJDBZ").click(function() { // alert("Boom!"); $.get("../ajax_dict/", function(res) { for(var i = 0; i &lt; res.length; i++) { var ntr = $("&lt;tr&gt;&lt;/tr&gt;"); $.each(res[i], function(key, value) { var ntd = $("&lt;td&gt;&lt;/td&gt;") ntd.html(value); ntr.append(ntd); }) $("#tbodyWishlist").append(ntr); } }); }); </code></pre> <p>Besides, more strangely, whenever I modify the views.py file, the received data order randomly change again. Like when I add a space at any end of the line, or I change price $749 to $750, save and refresh the page, then the price column data moved to Add-in Date, or randomly under some column I don't know.</p> <h2>-------------------------------------------------------------------------</h2> <hr> <p>The problem is solved for now, thanks to @luke_aus 's help.</p> <p>In runAjax.html, change the jquery code with it follows:</p> <pre><code> $("#btnJJDBZ").click(function(){ $.get("../ajax_dict", function(res) { $.each(res, function(){ $.each(this, function(key, value){ var ntr = $("&lt;tr&gt;&lt;/tr&gt;"); var ntd1 = $("&lt;td class='CDK'&gt;&lt;/td&gt;"); var ntd2 = $("&lt;td class='Price'&gt;&lt;/td&gt;"); var ntd3 = $("&lt;td class='Addin-date'&gt;&lt;/td&gt;"); $.each(this, function(key, value){ switch(key){ case "CDK": ntd1.html(value); break; case "Price": ntd2.html(value); break; case "Addin-Date": ntd3.html(value); break; } }) ntr.append(ntd1).append(ntd2).append(ntd3); $("#tbodyWishlist").append(ntr); }); }); }); </code></pre> <p>I changed the data format, too.</p> <pre><code>dicWCWishlist = {"list":[{"CDK":"Fallout 4","Price":"¥199", "Addin-Date":"Gifted! Thank you!"}, {"CDK":"Far Cry Primal","Price":"€59.99", "Addin-Date":"2015-12-5"}, {"CDK":"iPhone 6S plus","Price":"$749", "Addin-Date":"2016-1-15"}, {"CDK":"wrong1", "Price":"$$999", "Addin-Date":"1980-3-9"}]} </code></pre> <p>What I did is basically, </p> <ol> <li>Create tr and 3 tds in advance</li> <li>When key comes, manually tell what key it is (using switch)</li> <li>Change the corresponded cell with correct value (using html())</li> </ol> <h2>However, the question is still there!</h2> <p>Why was my data order random?</p> <p>What did JsonResponse do to my JSON ?</p>
1
2016-08-03T02:00:45Z
38,740,039
<p>One way to do it will be to create each row with td's with a class name that corresponds to the JSON object key for each object, then add the data from each object to the corresponding td.</p> <p>e.g. generate the table per ajax object (rather than per click as per this example) <a href="https://jsbin.com/sihudumere/edit?html,css,output" rel="nofollow">https://jsbin.com/sihudumere/edit?html,css,output</a></p> <p>Then place the data in the correct columns:</p> <p><code>jsonObj[key] = value newRow.children('.key).text(value) </code></p>
0
2016-08-03T09:46:14Z
[ "jquery", "python", "json", "ajax", "django" ]
Customising the output of items using django-autocomplete-light v3
38,733,177
<p>In earlier versions of django-autocomplete-light you could use a template to render each returned entry, which included the ability to insert custom HTML </p> <p>I can't figure out how to do that using the regular API, so I'm trying to add it in.</p> <p>So far I have a class like this which uses <code>mark_safe</code> and the HTML is being passed through:</p> <pre><code>class TemplateRenderSelect2QuerySetView(autocomplete.Select2QuerySetView): def get_result_label(self, result): """Return the label of a result.""" template = get_template("autocomplete_light/item.html") context = Context({"item": result}) return mark_safe(template.render(context)) </code></pre> <p>And the template <code>autocomplete_light/item.html</code> is:</p> <pre><code>&lt;b&gt;{{ item.name }}&lt;/b&gt; </code></pre> <p>But thats being rendered as:</p> <p><a href="http://i.stack.imgur.com/OJv8e.png" rel="nofollow"><img src="http://i.stack.imgur.com/OJv8e.png" alt="enter image description here"></a></p> <p>But the JSON is correct with the right tags:</p> <pre><code>{"pagination": {"more": false}, "results": [{"text": "&lt;b&gt;Victoria&lt;/b&gt;", "id": 11}]} </code></pre> <p>How can I get django-admin to render the HTML properly?</p> <hr> <p>edit: I found some <a href="http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html?highlight=data-html#displaying-results-using-custom-html" rel="nofollow">extra documentation</a> on custom HTML and tried setting <code>attrs={'data-html': 'true'}</code> against the widget, but its still not working</p>
0
2016-08-03T02:03:10Z
39,628,226
<p>As always the answer is subclassing, in this case the tip is to override <code>get_result_title</code>:</p> <pre><code>class CustomisableAutocomplete(autocomplete.Select2QuerySetView): template_name = "autocomplete_light/item.html" def get_result_title(self, result): """Return the label of a result.""" template = get_template(self.template_name) context = Context({"result": result}) return template.render(context) </code></pre> <p>If you want to have a title that isn't cluttered with tags, you can override <code>get_results</code> and return more data:</p> <pre><code>class CustomisableAutocomplete(autocomplete.Select2QuerySetView): template_name = "autocomplete_light/item.html" def get_result_title(self, result): """Return the title of a result.""" return six.text_type(result) def get_result_text(self, result): """Return the label of a result.""" template = get_template(self.template_name) context = Context({"result": result}) return template.render(context) def get_results(self, context): """Return data for the 'results' key of the response.""" return [ { 'id': self.get_result_value(result), 'title': self.get_result_title(result), 'text': self.get_result_text(result), } for result in context['object_list'] ] </code></pre>
0
2016-09-22T00:00:42Z
[ "jquery", "python", "django", "django-autocomplete-light" ]
Using Requests Post to login to this site not working
38,733,204
<p>I know there are tons of threads and videos on how to do this, I've gone through them all and am in need of a little advanced guidance.</p> <p>I am trying to log into this webpage where I have an account so I can send a request to download a report.<br> First I send the <code>get</code> request to the login page, then send the <code>post</code> request but when I <code>print(resp.content)</code> I get the code back for the login page. I do get a code[200] but I can't get to the index page. No matter what page I try to <code>get</code> after the post it keeps redirecting me back to the login page</p> <p>Here are a couple things I'm not sure if I did correctly:</p> <ul> <li>For the header I just put everything that was listed when I inspected the page</li> <li>Not sure if I need to do something with the cookies?</li> </ul> <p>Below is my code:</p> <pre><code>import requests import urllib.parse url = 'https://myurl.com/login.php' next_url = 'https://myurl.com/index.php' username = 'myuser' password = 'mypw' headers = { 'Host': 'url.myurl.com', 'Connection': 'keep-alive', 'Content-Length': '127', 'Cache-Control': 'max-age=0', 'Origin': 'https://url.myurl.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Referer': 'https://url.myurl.com/login.php?redirect=1', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.8', 'Cookie': 'PHPSESSID=3rgtou3h0tpjfts77kuho4nnm3' } login_payload = { 'XXX_login_name': username, 'XXX_login_password': password, } login_payload = urllib.parse.urlencode(login_payload) r = requests.Session() r.get(url, headers = headers) r.post(url, headers = headers, data = login_payload) resp = r.get(next_url, headers = headers) print(resp.content) </code></pre>
0
2016-08-03T02:05:42Z
38,741,904
<p>You don't need to send separate requests for authorization and file download. You need to send single POST with specifying credentials. Also in most cases you don't need to send headers. In common your code should looks like follow:</p> <pre><code>from requests.auth import HTTPBasicAuth url_to_download = "http://some_site/download?id=100500" response = requests.post(url_to_download, auth=HTTPBasicAuth('your_login', 'your_password')) with open('C:\\path\\to\\save\\file', 'w') as my_file: my_file.write(response.content) </code></pre>
1
2016-08-03T11:10:06Z
[ "python", "post", "login", "python-requests" ]