spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » PYTHON » Page 1
Python pandas cumsum() reset after hitting max
Here's an example of how you might do this by iterating over each row in the dataframe. I created new data for the example for simplicity: df = pd.DataFrame({'TimeDelta': np.random.normal( 900, 60, size=100)}) print df.head() TimeDelta 0 971.021295 1 734.359861 2 867.000397 3 992.166539 4 853.281131 So let's do an accumulator loop with your desired 3000 max: maxvalue = 3000 lastvalue

Categories : Python

Python: wget randomly prints "-1 / unknown"
Wget.download() needs a third argument for a progress bar which I left out. Just add bar=None to wget.download(url, out='cache/page'): wget.download(url, out='cache/page', bar=None)

Categories : Python

Looping over items in a List to return Dictionary Values Python
I dance - obviously returns juka-pinyi because 'i' is not in dictionary and you are lower casing the user input :) Otherwise, code seems fine. I am assuming it is a typo that the last line is incorrectly indented.

Categories : Python

How to send Google Maps API Marker from Python server?
There are a number of ways to handle this. I would create an API with the locations (lat, long). Then on the client side, use AJAX to consume the API and then use a loop to create new markers, appending each to the DOM. Make sense?

Categories : Python

Conditional Conjunction of two Iterables
Quick 'dirty' solution: s1 = set([1, 2, 3]) s2 = set([4, -2, 5]) res = [x for x in s1 | s2 if -x not in s1 and -x not in s2] 2 and -2 are opposite elements which we exclude. It gives [1, 3, 4, 5].

Categories : Python

Running part of python script
If you want something similar to Matlab, check out ipython - it comes with the goodness of python with a workflow similar to Matlab. ipython has the concept of Notebooks which are composed of cells. These cells can be executed individually giving you the behavior you expect.

Categories : Python

placement of widgets in kivy when useing a BoxLayout and no absolute coordinates
To restrict a label width to the texture width (same logic for height if you need), you can: Label: size_hint_x: None width: self.texture_size[0] If you use a such label in a BoxLayout, it will be left/bottom aligned by default. For your information, you can use pos_hint to place it somewhere else. I guess in your example, just using the method described above in your description Label

Categories : Python

Couchbase, 4 nodes with replicas (not sharding), select from 127.0.0.1
Couchbase does provide efficient sharding and replicas mechanism. So your #2 "no sharding" will be alien to Couchbase (but achievable via XCDR) Therefore, if you have 4 physical nodes with CB server instance on each I recommend the following setup (to achieve under 1 millisecond access times and HA 24/7 setup): Join all 4 instances into one cluster so you have real HA setup (if node is down, op

Categories : Python

Getting (in Python) the text output of executing a CMD command from Python
As Cyber mentioned, subprocess.check_output is a really easy way of doing it: import subprocess file = "foo.txt" text = "'comment'" output = subprocess.check_output(["BZR", "commit", file, "-m", text]) print(output) Disclaimer: This code will only work with Python 2.7+

Categories : Python

Enter interactive mode in piped python scripts
You'll need to reset stdin to come from the terminal, rather than the pipe. That is, before asking for input from the user (and assuming you're on a Unix-y environment) invoke sys.stdin = open("/dev/tty"). For example: import sys for line in sys.stdin.readlines(): print 'from s2: ' + line sys.stdin = open("/dev/tty") raw_input()

Categories : Python

ROS Python msg, send list of ints
When you do str(perc) you are creating a string like this '[0, 70, 85, 13, 54, 60, 67, 26]' you need to remove the brackets(first and last character) and then split it with the "," as delimiter like this: perc = [int(i) for i in emo_perc.percentage[1:-1].split(",")] Output: [0, 70, 85, 13, 54, 60, 67, 26]

Categories : Python

Matplotlib | Change the orientation to portrait
I think you're wanting to change the figure size, rather than anything having to do with page layout. The orientation kwarg to savefig really only applies to the PS and EPS backends. For a PDF, the page size is defined as equal to the figure size, so it has no effect. As a quick example of what your current results might look like: import matplotlib.pyplot as plt fig, ax = plt.subplots(nrows=7

Categories : Python

Django forms with clean_field(self) return empty element on raise
Sorry for answering my own question. My problem was at template level. my template was waging for a diatomite object because need to localize the date in the timezone of the user. but when there was an error in the form. the value did not contain a datetime object. just a buffer with the previous input. so the timezone date tags failed to parse the data. printing an empty value. now the part i

Categories : Python

Cannot compile two .py files into stand alone executable using py2exe
Add the background image as a data file: setup( options = {'py2exe': {'bundle_files': 1, 'compressed': True}}, windows=[{'script': "main.py"}], zipfile = None, data_files= [ ("prog",["background_image.py"])] )

Categories : Python

DrawingArea inside scrolledwindow fails to draw
You are using the GtkDrawingArea incorrectly. A drawing area is not a canvas on which you can draw only once and expect the system to refresh the drawing; it is a widget that allows (and requires) you to draw on it during the expose event. This is useful when you need to process the image, e.g. by scaling it to the area. If all you just need is a widget to show an existing image, use gtk.Image ins

Categories : Python

Mandrill API: Filter out scheduled emails list by metadata
The best bet would probably be to store the data when you schedule the email in the first place, in your own database, including the recipient, subject line, and what data you want to be able to display. If you need or want to be able to compare that to the messages scheduled in Mandrill, store the _id that's returned for each scheduled message, too, in your database, so you have a unique identifi

Categories : Python

When I read from a file, The last letter is printed twice
encoded=file.readline() When readline reads a line, it includes the newline character at the end of the line. So even though "eph" looks like it's three characters long in the text file, encoded will actually be "eph ". Try stripping the input of whitespace before doing anything with it. encoded=file.readline().strip() Without the strip, your loop will iterate four times, with letters being "

Categories : Python

How to perform custom sort in python on dictionary with custom class keys?
Just perform the lookup for free space in your key function: server = VIServer() server.connect(VSPHERE_IP, VSPHERE_USER, VSPHERE_PASS) datastores = server.get_datastores() ds_keys = sorted(datastores, key=lambda ds: VIProperty(server, ds).summary.freeSpace reverse=True) This produces a sorted list of the keys from datastores; you can use that to iterate in a

Categories : Python

Error "QObject::startTimer: QTimer can only be used with threads started with QThread" many times when closing application
Personally, I don't put any effort into chasing exit crashes anymore--just use pg.exit() and be done with it. (but if you do happen to find a bug in pyqtgraph, don't hesitate to open an issue on github)

Categories : Python

Simple map function error
I think what you're looking for is >>> list(map(lambda x: x, range(3))) [0, 1, 2] map returns an iterator. The message you are seeing is simply the object type for which you have just created an instance >>> map(lambda x: x, range(3)) <map object at 0x02E11F10>

Categories : Python

uWSGI env and PYTHON_EGG_CACHE configuration options
evn option exports an environment variables to the UWSGI web server process. The option can be specified manyt times to export multiple varibles. The values can be read from os.environ dict in Python. PYTHON_EGG_CACHE is not uWSGI specific and it is answered here: What is the Python egg cache (PYTHON_EGG_CACHE)? It is most likely related how Python eggs are deployed on your production server.

Categories : Python

Python: Appending to lists as keys within a dictionary
Two problems. First, everywhere you're using kingdom[1], you should just be using kingdom. Seems like you used to have a function that took a single list containing two sublists, and you didn't update the code to correspond to the new signature. Second, doing d[kingdom[j]] = b will cause all values in d to point to the exact same list. Appending to one of them will cause all the other ones to be

Categories : Python

Callbacks in Python Maya plugin
From the comments it sounds like there are two separate issues. Notificiations on object creation are 'free', in the sense that you can do this without the API by using a scriptJob. Here's a trivial example def new_object_callback(): print "created", cmds.ls(sl=True) cmds.scriptJob(e=('DagObjectCreated', new_object_callback)) The callback here is just a plain python script , but it could

Categories : Python

Python: how to locate a missing delimiter and append it to a text file
You simplify the code a lot by using re.sub function. ^(d+.*)(?<!//)$ Example usage: >>> file = open('input', 'r') >>> for line in file: ... print re.sub(r'^(d+.*)(?<!//)$', r'1//', line), Would produce an output as A string of information that does not require the delimiter 95 full !oe, !oeha // 96 new kaba// 100 name !uo5 // Regex ^ Anchors the regex at

Categories : Python

How to return .xlsx file?
You need to explicitly set the content-type header. The content-type for Excel files is application/vnd.ms-excel for .xls files or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet for .xlsx files, so try this: response.headers['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' Full code: @route('/download') def download(): response.heade

Categories : Python

Python Pyserial Serial Buffer
Yes, you can use the Serial.outWaiting() method to check how much data is still waiting to be sent. I'm not sure exactly how the Serial.write() method behaves, if it just adds the data to the internal buffer before returning. It would have to be that way in order for the above to be needed, but on the other hand there's nonblocking() to make it non-blocking. It's a bit confusing.

Categories : Python

"error: command 'x86_64-linux-gnu-gcc' failed with exit status 1" in virtualenv
I installed python2.7-dev via Synaptic Package Manager in Linux Mint 17. I could then accomplish the following in virtualenv: pip install pillow pip install pycrypto And then I installed libxml2-dev and libxslt1-dev via Synaptic and could accomplish the following: pip install lxml I also did this so that the pymongo install didn't have any errors: pip uninstall pymongo pip install pymong

Categories : Python

Dynamic number of loops
This can be extended to arbitrarily long chains. The ranges should be apparent, you simply pass in a dictionary of the function mappings and the values you want to evaluate all the terms of the outer product over. import itertools def f(x,y): return x+y def g(x,y): return 2*x-y def outer_product_thing(F,M): keys = M.keys() ranges = [M[k] for k in keys] for rx in itertools.product(

Categories : Python

zeromq load balacing in "divide and conquer"
In this case it is better to use ROUTER and REQ sockets. This is possible in python with client = context.socket(zmq.ROUTER) and worker = context.socket(zmq.REQ) A fully worked out example by Jeremy Avnet can be found in the zguide. One can observe that even with the code of the question added the runtime will be close to optimal. Why this works is described also in the in the section The

Categories : Python

python separating element in a list
Through re.search function. >>> lst = ['<div class="closeColor">0</div>', '<div class="closeColor">0</div>', '<div class="openColor">6</div>'] >>> [re.search(r'(?<=>)[^<>]*(?=<)', i).group() for i in lst] ['0', '0', '6'] Regular Expression: (?<= look behind to see if there is: >

Categories : Python

pandas rearrange dataframe to have all values in ascending order per every column independently
The desired sort ignores the index values, so the operation appears to be more like a NumPy operation than a Pandas one: import pandas as pd d = {'one':[None, 2, 3, 4], 'two':[4, 1, 4, 2], 'three':[3, 4, 6, 8],} df = pd.DataFrame(d, index = list('ABCD')) # one three two # A NaN 3 4 # B 2 4 1 # C 3 6 4 # D 4 8 2 arr = df.values arr.sort(a

Categories : Python

Extended class not running the constructor
You aren't calling the constructor in your subclass. You need to explicitly call it, either with Submission.__init__() or by using super(). Note also that as you're using Python 2, your base class should inherit from object to ensure it's a new-style class. class Submission(object): sender = None def __init__(self): self.sender = 'test sender' class SmsSubmission(Submission):

Categories : Python

How to write an Ansible task using with_dict in a loop (with_items)
I find very interesting this way of organizing variables for .ini files. I wanted to use it myself, so I worked on a plugin that allows to generate all the keys of an .ini file in one pass with the inifile module. It works fine and I use to manage my OpenStack configuration files. I am not a specialist in development, but I think this plugin can be useful for everyone, so if someone wants to ta

Categories : Python

How to parse a CLI command output (table) in python?
# Did this in Python 2.7 import re # Assume your input is in this file INPUT_FILE = 'text.txt' # Regex to only pay attention to lines starting with Ib # and capture the port info regex = re.compile(r'^(Ibs*S+)') result = [] # Store results in a list with open(INPUT_FILE, 'r') as theFile: for line in theFile: match = regex.search(line) if not match: continue result.append(match.grou

Categories : Python

How is it possible to use 'auth.navbar' for custom navigations?
Check out the auth.navbar signature. What you want can be achieved with this: {{=auth.navbar(separators=('', '', ''))}} You can also call auth.navbar(mode='bare'), which will return a dictionary with the relevant URLs and labels. You can then pass that dictionary to a custom navbar function to lay out and style the navbar as you like. For more details, see the docstring.

Categories : Python

How to preprocess time series data in Python for forecasting
You can easily construct your shifted array in one line. Here I used the range of integers to help you see what is going on - just replace A with your data. import numpy as np A = np.arange(10) cut = 6 B = np.array([A[k-cut:k] for k in xrange(cut,A.size)]) print B Giving: [[0 1 2 3 4 5] [1 2 3 4 5 6] [2 3 4 5 6 7] [3 4 5 6 7 8]] For parsing the dates, try looking to pandas, it's an excel

Categories : Python

BeautifulSoup: TypeError: 'NoneType' object is not subscriptable
My guess is that label_tag isn't actually returning the part of the soup you are looking for. This minimal example works: import bs4 text = '''<a class="Label" href="_link_">_text_</a>''' soup = bs4.BeautifulSoup(text) link = soup.find("a",{"class":"Label"}) print (link["href"]) Output: _link_

Categories : Python

How to use Django's ORM to retrieve an aggregation using subquery?
It may be a little easier to think about this if you rename related_to to parent_user and profile to child_profiles: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) parent_user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, related_name='child_profiles') ... Then, you can do something like this: metric_sums = Met

Categories : Python

Django Rest Framework organizing ViewSets and Routers
For what it's worth, I've always created a separate api/ subdirectory within my Django apps to hold all Django REST Framework related files. This is just one way of doing things but it's helped keep separation of concerns within our applications. The hierarchy looked like this... Django Project/ Django App/ views.py models.py urls.py api/ serializers.py viewsets.py

Categories : Python


Recently Add
Tkinter program not running while trying to run from console
Python pandas cumsum() reset after hitting max
Python: wget randomly prints "-1 / unknown"
Looping over items in a List to return Dictionary Values Python
How to send Google Maps API Marker from Python server?
Conditional Conjunction of two Iterables
Running part of python script
placement of widgets in kivy when useing a BoxLayout and no absolute coordinates
Couchbase, 4 nodes with replicas (not sharding), select from 127.0.0.1
Getting (in Python) the text output of executing a CMD command from Python
Enter interactive mode in piped python scripts
ROS Python msg, send list of ints
Matplotlib | Change the orientation to portrait
Django forms with clean_field(self) return empty element on raise
Cannot compile two .py files into stand alone executable using py2exe
DrawingArea inside scrolledwindow fails to draw
Mandrill API: Filter out scheduled emails list by metadata
When I read from a file, The last letter is printed twice
How to perform custom sort in python on dictionary with custom class keys?
Error "QObject::startTimer: QTimer can only be used with threads started with QThread" many times when closing application
Simple map function error
uWSGI env and PYTHON_EGG_CACHE configuration options
Python: Appending to lists as keys within a dictionary
Callbacks in Python Maya plugin
Python: how to locate a missing delimiter and append it to a text file
How to return .xlsx file?
Python Pyserial Serial Buffer
"error: command 'x86_64-linux-gnu-gcc' failed with exit status 1" in virtualenv
Dynamic number of loops
zeromq load balacing in "divide and conquer"
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.