code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
query = \ 'select * from yahoo.finance.historicaldata where symbol = "%s" and startDate = "%s" and endDate = "%s"' \ % (symbol, start_date, end_date) return query
def prepare_query(self, symbol, start_date, end_date)
Method returns prepared request query for Yahoo YQL API.
2.369317
1.924705
1.231002
query = self.prepare_query(symbol, start_date, end_date) self.parameters['q'] = query response = requests.get(self.api, params=self.parameters).json() results = response['query']['results']['quote'] return results
def send(self, symbol, start_date, end_date)
Method sends request to Yahoo YQL API.
3.4189
2.947108
1.160087
if not self.connection: self._connect() try: self.connection.close() except: pass self.connection.connect() headers = {} if self.auth_header: headers["Authorization"] = self.auth_header self.connection.reque...
def _make_request(self, method, url, post_data=None, body=None)
Make a request on this connection
2.47617
2.425702
1.020806
obj_node = doc.getElementsByTagName('object')[0] if not cls: class_name = obj_node.getAttribute('class') cls = find_class(class_name) if not id: id = obj_node.getAttribute('id') props = {} for prop_node in obj_node.getElementsByTagName...
def get_props_from_doc(self, cls, id, doc)
Pull out the properties from this document Returns the class, the properties in a hash, and the id if provided as a tuple :return: (cls, props, id)
2.551754
2.520445
1.012422
doc = self.marshal_object(obj) if obj.id: url = "/%s/%s" % (self.db_name, obj.id) else: url = "/%s" % (self.db_name) resp = self._make_request("PUT", url, body=doc.toxml()) new_obj = self.get_object_from_doc(obj.__class__, None, parse(resp)) ...
def save_object(self, obj, expected_value=None)
Marshal the object and do a PUT
2.825565
2.671292
1.057752
if isinstance(fp, str) or isinstance(fp, unicode): doc = parseString(fp) else: doc = parse(fp) return self.get_props_from_doc(cls, id, doc)
def unmarshal_props(self, fp, cls=None, id=None)
Same as unmarshalling an object, except it returns from "get_props_from_doc"
3.449091
2.892742
1.192326
rs = self.connection.get_all_dbinstances(self.id) if len(rs) > 0: for i in rs: if i.id == self.id: self.__dict__.update(i.__dict__) elif validate: raise ValueError('%s is not a valid Instance ID' % self.id) return self....
def update(self, validate=False)
Update the DB instance's status information by making a call to fetch the current instance attributes from the service. :type validate: bool :param validate: By default, if EC2 returns no data about the instance the update method returns quietly. If ...
3.923594
3.080044
1.273876
return self.connection.delete_dbinstance(self.id, skip_final_snapshot, final_snapshot_id)
def stop(self, skip_final_snapshot=False, final_snapshot_id='')
Delete this DBInstance. :type skip_final_snapshot: bool :param skip_final_snapshot: This parameter determines whether a final db snapshot is created before the instance is deleted. If True, no snapshot is created. ...
4.700218
4.645908
1.01169
return self.connection.modify_dbinstance(self.id, param_group, security_groups, preferred_maintenance_window, ...
def modify(self, param_group=None, security_groups=None, preferred_maintenance_window=None, master_password=None, allocated_storage=None, instance_class=None, backup_retention_period=None, preferred_backup_window=None, multi_az=Fa...
Modify this DBInstance. :type security_groups: list of str or list of DBSecurityGroup objects :param security_groups: List of names of DBSecurityGroup to authorize on this DBInstance. :type preferred_maintenance_window: str :param preferred_maintenance_w...
1.667603
1.943173
0.858186
self.limit = limit self.offset = offset return self
def fetch(self, limit, offset=0)
Not currently fully supported, but we can use this to allow them to set a limit in a chainable method
5.023676
3.632061
1.383147
''' set symbols ''' for symbol in self.symbols: self.__trakers[symbol]=OneTraker(symbol, self, self.buyingRatio)
def __setUpTrakers(self)
set symbols
13.93752
10.313347
1.351406
''' call back for executed order ''' for orderId, order in orderDict.items(): if order.symbol in self.__trakers.keys(): self.__trakers[order.symbol].orderExecuted(orderId)
def orderExecuted(self, orderDict)
call back for executed order
5.08555
5.156726
0.986197
''' consume ticks ''' if not self.__trakers: self.__setUpTrakers() for symbol, tick in tickDict.items(): if symbol in self.__trakers: self.__trakers[symbol].tickUpdate(tick)
def tickUpdate(self, tickDict)
consume ticks
5.274508
5.048476
1.044772
''' calculate the amount of money to buy stock ''' account=self.__strategy.getAccountCopy() if (account.buyingPower >= account.getTotalValue() / self.__buyingRatio): return account.getTotalValue() / self.__buyingRatio else: return 0
def __getCashToBuyStock(self)
calculate the amount of money to buy stock
7.298193
6.819283
1.070229
''' consume ticks ''' LOG.debug("tickUpdate %s with tick %s, price %s" % (self.__symbol, tick.time, tick.close)) self.__priceZscore(tick.close) self.__volumeZscore(tick.volume) # if haven't started, don't do any trading if tick.time <= self.__startDate: retur...
def tickUpdate(self, tick)
consume ticks
3.717885
3.6316
1.02376
d = json.loads(json_doc) token = cls() token.__dict__.update(d) return token
def from_json(cls, json_doc)
Create and return a new Session Token based on the contents of a JSON document. :type json_doc: str :param json_doc: A string containing a JSON document with a previously saved Credentials object.
4.298315
4.858167
0.884761
fp = open(file_path) json_doc = fp.read() fp.close() return cls.from_json(json_doc)
def load(cls, file_path)
Create and return a new Session Token based on the contents of a previously saved JSON-format file. :type file_path: str :param file_path: The fully qualified path to the JSON-format file containing the previously saved Session Token information.
3.214962
3.661798
0.877974
return {'access_key': self.access_key, 'secret_key': self.secret_key, 'session_token': self.session_token, 'expiration': self.expiration, 'request_id': self.request_id}
def to_dict(self)
Return a Python dict containing the important information about this Session Token.
2.255549
2.001799
1.126761
fp = open(file_path, 'wb') json.dump(self.to_dict(), fp) fp.close() os.chmod(file_path, 0600)
def save(self, file_path)
Persist a Session Token to a file in JSON format. :type path: str :param path: The fully qualified path to the file where the the Session Token data should be written. Any previous data in the file will be overwritten. To help protect the credentials contained in t...
2.716162
3.056077
0.888774
now = datetime.datetime.utcnow() if time_offset_seconds: now = now + datetime.timedelta(seconds=time_offset_seconds) ts = boto.utils.parse_ts(self.expiration) delta = ts - now return delta.total_seconds() <= 0
def is_expired(self, time_offset_seconds=0)
Checks to see if the Session Token is expired or not. By default it will check to see if the Session Token is expired as of the moment the method is called. However, you can supply an optional parameter which is the number of seconds of offset into the future for the check. For exampl...
2.825596
3.318059
0.851581
raise NotImplementedError
def add_cron(self, name, minute, hour, mday, month, wday, who, command, env=None)
Add an entry to the system crontab.
521.35321
486.549377
1.071532
urls = super(AccountAdmin, self).get_urls() from django.conf.urls import url def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = self.opts.app...
def get_urls(self)
Add the export view to urls.
1.985475
1.943361
1.02167
seek = self._get_pos(ip) if seek > 0: return self._parse_location(seek, detailed=detailed) return False
def get_location(self, ip, detailed=False)
Returns a dictionary with location data or False on failure. Amount of information about IP contained in the dictionary depends upon `detailed` flag state.
7.423608
7.542807
0.984197
if isinstance(ip, str): ip = [ip] seek = map(self._get_pos, ip) return [self._parse_location(elem, detailed=detailed) if elem > 0 else False for elem in seek]
def get_locations(self, ip, detailed=False)
Returns a list of dictionaries with location data or False on failure. Argument `ip` must be an iterable object. Amount of information about IP contained in the dictionary depends upon `detailed` flag state.
7.290078
6.679212
1.091458
ready_handlers = [] auth_handlers = boto.plugin.get_plugin(AuthHandler, requested_capability) total_handlers = len(auth_handlers) for handler in auth_handlers: try: ready_handlers.append(handler(host, config, provider)) except boto.auth_handler.NotReadyToAuthenticate: ...
def get_auth_handler(host, config, provider, requested_capability=None)
Finds an AuthHandler that is ready to authenticate. Lists through all the registered AuthHandlers to find one that is willing to handle for the requested capabilities, config and provider. :type host: string :param host: The name of the host :type config: :param config: :type provider: ...
6.065691
5.487225
1.105421
headers_to_sign = {} headers_to_sign = {'Host' : self.host} for name, value in http_request.headers.items(): lname = name.lower() if lname.startswith('x-amz'): headers_to_sign[name] = value return headers_to_sign
def headers_to_sign(self, http_request)
Select the headers from the request that need to be included in the StringToSign.
2.396993
2.339471
1.024588
l = ['%s:%s'%(n.lower().strip(), headers_to_sign[n].strip()) for n in headers_to_sign] l.sort() return '\n'.join(l)
def canonical_headers(self, headers_to_sign)
Return the headers that need to be included in the StringToSign in their canonical form by converting all header keys to lower case, sorting them in alphabetical order and then joining them into a string, separated by newlines.
3.120662
2.874052
1.085806
headers_to_sign = self.headers_to_sign(http_request) canonical_headers = self.canonical_headers(headers_to_sign) string_to_sign = '\n'.join([http_request.method, http_request.path, '', ...
def string_to_sign(self, http_request)
Return the canonical StringToSign as well as a dict containing the original version of all headers that were included in the StringToSign.
2.087373
1.908216
1.093887
# This could be a retry. Make sure the previous # authorization header is removed first. if 'X-Amzn-Authorization' in req.headers: del req.headers['X-Amzn-Authorization'] req.headers['X-Amz-Date'] = formatdate(usegmt=True) req.headers['X-Amz-Security-Token']...
def add_auth(self, req, **kwargs)
Add AWS3 authentication to a request. :type req: :class`boto.connection.HTTPRequest` :param req: The HTTPRequest object.
2.770113
2.756956
1.004772
for c in requested_capability: if not c in cls.capability: return False return True
def is_capable(cls, requested_capability)
Returns true if the requested capability is supported by this plugin
4.876473
4.573435
1.06626
# Discard ready connections that are too old. self.clean() # Return the first connection that is ready, and remove it # from the queue. Connections that aren't ready are returned # to the end of the queue with an updated time, on the # assumption that somebody ...
def get(self)
Returns the next connection in this pool that is ready to be reused. Returns None of there aren't any.
6.352774
5.641891
1.126001
if ON_APP_ENGINE: # Google App Engine implementation of HTTPConnection doesn't contain # _HTTPConnection__response attribute. Moreover, it's not possible # to determine if given connection is ready. Reusing connections # simply doesn't make sense with App...
def _conn_ready(self, conn)
There is a nice state diagram at the top of httplib.py. It indicates that once the response headers have been read (which _mexe does before adding the connection to the pool), a response is attached to the connection, and it stays there until it's done reading. This isn't entirely true...
9.158292
8.847851
1.035087
# Note that we do not close the connection here -- somebody # may still be reading from it. while len(self.queue) > 0 and self._pair_stale(self.queue[0]): self.queue.pop(0)
def clean(self)
Get rid of stale connections.
8.115849
6.156518
1.318253
(_conn, return_time) = pair now = time.time() return return_time + ConnectionPool.STALE_DURATION < now
def _pair_stale(self, pair)
Returns true of the (connection,time) pair is too old to be used.
15.84963
8.259454
1.918968
self.clean() with self.mutex: key = (host, is_secure) if key not in self.host_to_pool: return None return self.host_to_pool[key].get()
def get_http_connection(self, host, is_secure)
Gets a connection from the pool for the named host. Returns None if there is no connection that can be reused. It's the caller's responsibility to call close() on the connection when it's no longer needed.
4.188238
3.410883
1.227904
with self.mutex: key = (host, is_secure) if key not in self.host_to_pool: self.host_to_pool[key] = HostConnectionPool() self.host_to_pool[key].put(conn)
def put_http_connection(self, host, is_secure, conn)
Adds a connection to the pool of connections that can be reused for the named host.
2.631302
2.53272
1.038923
with self.mutex: now = time.time() if self.last_clean_time + self.CLEAN_INTERVAL < now: to_remove = [] for (host, pool) in self.host_to_pool.items(): pool.clean() if pool.size() == 0: ...
def clean(self)
Clean up the stale connections in all of the pools, and then get rid of empty pools. Pools clean themselves every time a connection is fetched; this cleaning takes care of pools that aren't being used any more, so nothing is being gotten from them.
2.458555
2.241894
1.096642
boto.log.debug('Method: %s' % request.method) boto.log.debug('Path: %s' % request.path) boto.log.debug('Data: %s' % request.body) boto.log.debug('Headers: %s' % request.headers) boto.log.debug('Host: %s' % request.host) response = None body = None ...
def _mexe(self, request, sender=None, override_num_retries=None, retry_handler=None)
mexe - Multi-execute inside a loop, retrying multiple times to handle transient Internet errors by simply trying again. Also handles redirects. This code was inspired by the S3Utils classes posted to the boto-users Google group by Larry Bates. Thanks!
3.035356
3.057385
0.992795
http_request = self.build_base_http_request(method, path, auth_path, {}, headers, data, host) return self._mexe(http_request, sender, override_num_retries)
def make_request(self, method, path, headers=None, data='', host=None, auth_path=None, sender=None, override_num_retries=None)
Makes a request to the server, with stock multiple-retry logic.
4.248132
4.396533
0.966246
root = tkinter.Tk() root.withdraw() filepath = filedialog.askopenfilenames( filetypes=fileTypes, parent=root) if isinstance(filepath, str): fileList = filepath.split(" ") elif isinstance(filepath, tuple): fileList = list(filepath) elif isinstance(filepath, list): ...
def GetFilePathsWithDialog(fileTypes=[])
Multipul File Select with dialog fileTypes: you can choise file extension ex) fileTypes=[('Excel Files', '.xlsx')]
2.577176
2.668953
0.965613
root = tkinter.Tk() root.title(title) val = tkinter.IntVar() val.set(0) if msg != "": tkinter.Label(root, text=msg).pack() index = 0 for item in selectList: tkinter.Radiobutton(root, text=item, variable=val, value=index).pack(anchor=tkinter....
def GetRadioButtonSelect(selectList, title="Select", msg="")
Create radio button window for option selection title: Window name mag: Label of the radio button return (seldctedItem, selectedindex)
2.094703
2.060775
1.016464
root = tkinter.Tk() root.title(title) label = tkinter.Label(root, text=msg) label.pack() listbox = tkinter.Listbox(root) for i in selectList: listbox.insert(tkinter.END, i) listbox.pack() tkinter.Button(root, text="OK", fg="black", command=root.quit).pack() root.mainl...
def GetListSelect(selectList, title="Select", msg="")
Create list with selectList, and then return seleced string and index title: Window name mag: Label of the list return (seldctedItem, selectedindex)
2.085082
2.056157
1.014068
root = tkinter.Tk() root.title(title) label = tkinter.Label(root, text=msg) label.pack() optList = [] for item in selectList: opt = tkinter.BooleanVar() opt.set(False) tkinter.Checkbutton(root, text=item, variable=opt).pack() optList.append(opt) tkinte...
def GetCheckButtonSelect(selectList, title="Select", msg="")
Get selected check button options title: Window name mag: Label of the check button return selected dictionary {'sample b': False, 'sample c': False, 'sample a': False}
1.978626
1.997767
0.990419
root = tkinter.Tk() root.title(title) label = tkinter.Label(root, text=msg) label.pack() entries = [] for item in dataList: tkinter.Label(root, text=item).pack() entry = tkinter.Entry(root) entry.pack() entries.append(entry) # print entries tkinter...
def GetEntries(dataList, title="Select", msg="")
Get entries of the list title: Window name mag: Label of the check button return data dictionary like: {'y': '5.0', 'x': '100', 'z': 'save'}
2.065252
2.211797
0.933744
rule = IPPermissions(self) rule.ip_protocol = ip_protocol rule.from_port = from_port rule.to_port = to_port self.rules.append(rule) rule.add_grant(src_group_name, src_group_owner_id, cidr_ip)
def add_rule(self, ip_protocol, from_port, to_port, src_group_name, src_group_owner_id, cidr_ip)
Add a rule to the SecurityGroup object. Note that this method only changes the local version of the object. No information is sent to EC2.
2.200451
2.227216
0.987983
target_rule = None for rule in self.rules: if rule.ip_protocol == ip_protocol: if rule.from_port == from_port: if rule.to_port == to_port: target_rule = rule target_grant = None ...
def remove_rule(self, ip_protocol, from_port, to_port, src_group_name, src_group_owner_id, cidr_ip)
Remove a rule to the SecurityGroup object. Note that this method only changes the local version of the object. No information is sent to EC2.
1.797121
1.826741
0.983785
if src_group: cidr_ip = None src_group_name = src_group.name src_group_owner_id = src_group.owner_id else: src_group_name = None src_group_owner_id = None status = self.connection.authorize_security_group(self.name, ...
def authorize(self, ip_protocol=None, from_port=None, to_port=None, cidr_ip=None, src_group=None)
Add a new rule to this security group. You need to pass in either src_group_name OR ip_protocol, from_port, to_port, and cidr_ip. In other words, either you are authorizing another group or you are authorizing some ip-based rule. :type ip_protocol: string :param...
1.817422
1.906085
0.953485
if region.name == self.region: raise BotoClientError('Unable to copy to the same Region') conn_params = self.connection.get_params() rconn = region.connect(**conn_params) sg = rconn.create_security_group(name or self.name, self.description) source_groups = []...
def copy_to_region(self, region, name=None)
Create a copy of this security group in another region. Note that the new security group will be a separate entity and will not stay in sync automatically after the copy operation. :type region: :class:`boto.ec2.regioninfo.RegionInfo` :param region: The region to which this secu...
3.074222
3.163002
0.971932
# It would be more efficient to do this with filters now # but not all services that implement EC2 API support filters. instances = [] rs = self.connection.get_all_instances() for reservation in rs: uses_group = [g.name for g in reservation.groups if g.name =...
def instances(self)
Find all of the current instances that are running within this security group. :rtype: list of :class:`boto.ec2.instance.Instance` :return: A list of Instance objects
5.931217
5.599506
1.059239
assert type(expiration_time) == time.struct_time, \ 'Policy document must include a valid expiration Time object' # Convert conditions object mappings to condition statements return '{"expiration": "%s",\n"conditions": [%s]}' % \ (time.strftime(boto.utils.ISO86...
def build_post_policy(self, expiration_time, conditions)
Taken from the AWS book Python examples and modified for use with boto
7.47588
6.982772
1.070618
if fields == None: fields = [] if conditions == None: conditions = [] expiration = time.gmtime(int(time.time() + expires_in)) # Generate policy document conditions.append('{"bucket": "%s"}' % bucket_name) if key.endswith("${filename}"): ...
def build_post_form_args(self, bucket_name, key, expires_in = 6000, acl = None, success_action_redirect = None, max_content_length = None, http_method = "http", fields=None, conditions=None)
Taken from the AWS book Python examples and modified for use with boto This only returns the arguments required for the post form, not the actual form. This does not return the file input field which also needs to be added :type bucket_name: string :param bucket_name: ...
2.399306
2.316539
1.035729
rs = self.get_all_buckets(headers=headers) return rs.ID
def get_canonical_user_id(self, headers=None)
Convenience method that returns the "CanonicalUserID" of the user who's credentials are associated with the connection. The only way to get this value is to do a GET request on the service which returns all buckets associated with the account. As part of that response, the canonical user...
17.001993
11.958105
1.421797
check_lowercase_bucketname(bucket_name) if policy: if headers: headers[self.provider.acl_header] = policy else: headers = {self.provider.acl_header : policy} if location == Location.DEFAULT: data = '' else: ...
def create_bucket(self, bucket_name, headers=None, location=Location.DEFAULT, policy=None)
Creates a new located bucket. By default it's in the USA. You can pass Location.EU to create an European bucket. :type bucket_name: string :param bucket_name: The name of the new bucket :type headers: dict :param headers: Additional headers to pass along with the reques...
2.460559
2.661604
0.924465
"A generator for de-unsynchronizing a byte iterable." sync = False for b in iterable: if sync and b & 0xE0: warn("Invalid unsynched data", Warning) if not (sync and b == 0x00): yield b sync = (b == 0xFF)
def gen_decode(iterable)
A generator for de-unsynchronizing a byte iterable.
11.254326
6.696145
1.680717
"A generator for unsynchronizing a byte iterable." sync = False for b in data: if sync and (b == 0x00 or b & 0xE0): yield 0x00 # Insert sync char yield b sync = (b == 0xFF) if sync: yield 0x00
def gen_encode(data)
A generator for unsynchronizing a byte iterable.
7.215206
4.516982
1.597351
"Decodes a syncsafe integer" value = 0 for b in data: if b > 127: # iTunes bug raise ValueError("Invalid syncsafe integer") value <<= 7 value += b return value
def decode(data)
Decodes a syncsafe integer
7.771031
5.916888
1.313365
if i < 0: raise ValueError("value is negative") assert width != 0 data = bytearray() while i: data.append(i & 127) i >>= 7 if width > 0 and len(data) > width: raise ValueError("Integer too large") if len(data) < abs...
def encode(i, *, width=-1)
Encodes a nonnegative integer into syncsafe format When width > 0, then len(result) == width When width < 0, then len(result) >= abs(width)
2.626214
2.545078
1.031879
retval = self.set_attribute('VisibilityTimeout', visibility_timeout) if retval: self.visibility_timeout = visibility_timeout return retval
def set_timeout(self, visibility_timeout)
Set the visibility timeout for the queue. :type visibility_timeout: int :param visibility_timeout: The desired timeout in seconds
3.294314
4.966127
0.663357
rs = self.get_messages(1, visibility_timeout) if len(rs) == 1: return rs[0] else: return None
def read(self, visibility_timeout=None)
Read a single message from the queue. :type visibility_timeout: int :param visibility_timeout: The timeout for this message in seconds :rtype: :class:`boto.sqs.message.Message` :return: A single message or None if queue is empty
3.645701
3.692348
0.987367
new_msg = self.connection.send_message(self, message.get_body_encoded(), delay_seconds) message.id = new_msg.id message.md5 = new_msg.md5 return message
def write(self, message, delay_seconds=None)
Add a single message to the queue. :type message: Message :param message: The message to be written to the queue :rtype: :class:`boto.sqs.message.Message` :return: The :class:`boto.sqs.message.Message` object that was written.
5.193118
3.798156
1.367273
m = self.message_class(self, body) m.queue = self return m
def new_message(self, body='')
Create new message of appropriate class. :type body: message body :param body: The body of the newly created message (optional). :rtype: :class:`boto.sqs.message.Message` :return: A new Message object
6.734568
8.756606
0.769084
n = 0 l = self.get_messages(page_size, vtimeout) while l: for m in l: self.delete_message(m) n += 1 l = self.get_messages(page_size, vtimeout) return n
def clear(self, page_size=10, vtimeout=10)
Utility function to remove all messages from a queue
2.314931
2.059737
1.123896
n = 0 l = self.get_messages(page_size, vtimeout) while l: for m in l: n += 1 l = self.get_messages(page_size, vtimeout) return n
def count_slow(self, page_size=10, vtimeout=10)
Deprecated. This is the old 'count' method that actually counts the messages by reading them all. This gives an accurate count but is very slow for queues with non-trivial number of messasges. Instead, use get_attribute('ApproximateNumberOfMessages') to take advantage of the new SQS ca...
2.451459
1.962538
1.249127
fp = open(file_name, 'wb') n = 0 l = self.get_messages(page_size, vtimeout) while l: for m in l: fp.write(m.get_body()) if sep: fp.write(sep) n += 1 l = self.get_messages(page_size, vtime...
def dump(self, file_name, page_size=10, vtimeout=10, sep='\n')
Utility function to dump the messages in a queue to a file NOTE: Page size must be < 10 else SQS errors
2.175249
2.03118
1.070929
n = 0 m = self.read() while m: n += 1 fp.write(m.get_body()) if sep: fp.write(sep) self.delete_message(m) m = self.read() return n
def save_to_file(self, fp, sep='\n')
Read all messages from the queue and persist them to file-like object. Messages are written to the file and the 'sep' string is written in between messages. Messages are deleted from the queue after being written to the file. Returns the number of messages saved.
3.590759
2.429627
1.477905
fp = open(file_name, 'wb') n = self.save_to_file(fp, sep) fp.close() return n
def save_to_filename(self, file_name, sep='\n')
Read all messages from the queue and persist them to local file. Messages are written to the file and the 'sep' string is written in between messages. Messages are deleted from the queue after being written to the file. Returns the number of messages saved.
3.206655
2.849686
1.125266
n = 0 m = self.read() while m: n += 1 key = bucket.new_key('%s/%s' % (self.id, m.id)) key.set_contents_from_string(m.get_body()) self.delete_message(m) m = self.read() return n
def save_to_s3(self, bucket)
Read all messages from the queue and persist them to S3. Messages are stored in the S3 bucket using a naming scheme of:: <queue_id>/<message_id> Messages are deleted from the queue after being saved to S3. Returns the number of messages saved.
3.186357
2.251304
1.415338
n = 0 if prefix: prefix = '%s/' % prefix else: prefix = '%s/' % self.id[1:] rs = bucket.list(prefix=prefix) for key in rs: n += 1 m = self.new_message(key.get_contents_as_string()) self.write(m) return n
def load_from_s3(self, bucket, prefix=None)
Load messages previously saved to S3.
3.700649
3.464979
1.068015
n = 0 body = '' l = fp.readline() while l: if l == sep: m = Message(self, body) self.write(m) n += 1 print 'writing message %d' % n body = '' else: body = body...
def load_from_file(self, fp, sep='\n')
Utility function to load messages from a file-like object to a queue
3.777779
3.145937
1.200844
fp = open(file_name, 'rb') n = self.load_from_file(fp, sep) fp.close() return n
def load_from_filename(self, file_name, sep='\n')
Utility function to load messages from a local filename to a queue
3.299679
3.210623
1.027738
return click.echo(json.dumps(data, sort_keys=True, indent=2))
def echo_event(data)
Echo a json dump of an object using click
3.91884
3.178026
1.233105
if transport_type == 'udp': if timeout is not None: ctx.fail('--timeout cannot be used with the UDP transport') transport = riemann_client.transport.UDPTransport(host, port) elif transport_type == 'tcp': transport = riemann_client.transport.TCPTransport(host, port, timeo...
def main(ctx, host, port, transport_type, timeout, ca_certs)
Connects to a Riemann server to send events or query the index By default, will attempt to contact Riemann on localhost:5555 over TCP. The RIEMANN_HOST and RIEMANN_PORT environment variables can be used to configure the host and port used. Command line parameters will override the environment variables...
2.166984
2.158008
1.004159
client = CommandLineClient(transport) event = client.create_event({ 'time': time, 'state': state, 'host': host, 'description': description, 'service': service, 'tags': tag, 'attributes': dict(attribute), 'ttl': ttl, 'metric_f': metric_...
def send(transport, time, state, host, description, service, tag, attribute, ttl, metric_f, echo)
Send a single event to Riemann
2.884942
2.787834
1.034832
with CommandLineClient(transport) as client: echo_event(client.query(query))
def query(transport, query)
Query the Riemann server
13.226368
15.006894
0.881353
assert(isinstance(attrs, dict)), "Argument must be a dict of key->values to save" for prop_name in attrs: value = attrs[prop_name] prop = self.find_property(prop_name) assert(prop), "Property not found: %s" % prop_name self._manager.set_property(p...
def put_attributes(self, attrs)
Save just these few attributes, not the whole object :param attrs: Attributes to save, key->value dict :type attrs: dict :return: self :rtype: :class:`boto.sdb.db.model.Model`
4.201833
3.865148
1.087108
assert(isinstance(attrs, list)), "Argument must be a list of names of keys to delete." self._manager.domain.delete_attributes(self.id, attrs) self.reload() return self
def delete_attributes(self, attrs)
Delete just these attributes, not the whole object. :param attrs: Attributes to save, as a list of string names :type attrs: list :return: self :rtype: :class:`boto.sdb.db.model.Model`
5.895133
6.851429
0.860424
if name == cls.__name__: return cls for sc in cls.__sub_classes__: r = sc.find_subclass(name) if r != None: return r
def find_subclass(cls, name)
Find a subclass with a given name
3.033041
3.05478
0.992884
if not self.access_point: return new_hc = self.connection.configure_health_check(self.access_point, self) self.interval = new_hc.interval self.target = new_hc.target self.healthy_threshold = new_hc.healthy_threshold self.unhealthy_threshold = new_hc....
def update(self)
In the case where you have accessed an existing health check on a load balancer, this method applies this instance's health check values to the load balancer it is attached to. .. note:: This method will not do anything if the :py:attr:`access_point` attribute isn't set, as is the c...
3.236745
2.221237
1.457181
params['Service'] = "AWSECommerceService" params['Operation'] = action if page: params['ItemPage'] = page response = self.make_request(None, params, "/onca/xml") body = response.read() boto.log.debug(body) if response.status != 200: ...
def get_response(self, action, params, page=0, itemSet=None)
Utility method to handle calls to ECS and parsing of responses.
2.792603
2.717345
1.027696
def _replace(match): upload, options = parse_match(match) return render_upload(upload, template_path, **options) return oembed_replace(substitute_uploads(content, _replace))
def render_uploads(content, template_path="adminfiles/render/")
Replace all uploaded file references in a content string with the results of rendering a template found under ``template_path`` with the ``FileUpload`` instance and the key=value options found in the file reference. So if "<<<my-uploaded-file:key=val:key2=val2>>>" is found in the content string, it...
8.834006
9.348796
0.944935
if upload is None: return settings.ADMINFILES_STRING_IF_NOT_FOUND template_name = options.pop('as', None) if template_name: templates = [template_name, "%s/default" % template_name.split('/')[0], "default"] else: templates = [join(up...
def render_upload(upload, template_path="adminfiles/render/", **options)
Render a single ``FileUpload`` model instance using the appropriate rendering template and the given keyword options, and return the rendered HTML. The template used to render each upload is selected based on the mime-type of the upload. For an upload with mime-type "image/jpeg", assuming the d...
3.689523
3.957183
0.932361
resources = {} for name in meta: if name.startswith("$"): continue resources[name] = resource = {} for action in meta[name]: if action.startswith("$"): continue url, httpmethod = res_to_url(name, action) resource[action...
def parse_meta(meta)
Parse metadata of API Args: meta: metadata of API Returns: tuple(url_prefix, auth_header, resources)
4.276121
3.412127
1.253213
code = '' code += "function(root, init) {\n" code += " var q = init('%(auth_header)s', '%(url_prefix)s');\n" %\ {'url_prefix': url_prefix, 'auth_header': auth_header} code += " var r = null;\n" for key in resources: code += " r = root.%(key)s = {};\n" % {'key': key} f...
def render_core(url_prefix, auth_header, resources)
Generate res.core.js
2.572683
2.411388
1.066889
if isinstance(meta, dict): url_prefix, auth_header, resources = parse_meta(meta) else: url_prefix, auth_header, resources = meta if prefix is not None: url_prefix = prefix core = render_core(url_prefix, auth_header, resources) if min: filename = 'res.web.min.js' ...
def generate_code(meta, prefix=None, node=False, min=False)
Generate res.js Args: meta: tuple(url_prefix, auth_header, resources) or metadata of API Returns: res.js source code
3.578383
2.827903
1.265384
meta = requests.get(url, headers={'Accept': 'application/json'}).json() code = generate_code(meta, prefix, node, min) save_file(dest, code)
def resjs(url, dest='./res.js', prefix=None, node=False, min=False)
Generate res.js and save it
3.589015
3.89633
0.921127
assert size > 0 def main(upstream, downstream, size): queue = collections.deque() while True: if downstream.halted: # no one is downstream, so shutdown upstream.close() return watch = [] if queue: ...
def Queue(hub, size)
:: +----------+ send --> | Queue | | (buffer) | --> recv +----------+ A Queue may also only have exactly one sender and recver. A Queue however has a fifo buffer of a custom size. Sends to the Queue won't block until the buffer becomes full:: ...
4.587478
5.109827
0.897776
return self.sender.send(item, timeout=timeout)
def send(self, item, timeout=-1)
Send an *item* on this pair. This will block unless our Rever is ready, either forever or until *timeout* milliseconds.
6.161438
6.208926
0.992352
return self._replace(recver=self.recver.pipe(target))
def pipe(self, target)
Pipes are Recver to the target; see :meth:`vanilla.core.Recver.pipe` Returns a new Pair of our current Sender and the target's Recver.
16.471567
6.766607
2.434243
return self._replace(recver=self.recver.map(f))
def map(self, f)
Maps this Pair with *f*'; see :meth:`vanilla.core.Recver.map` Returns a new Pair of our current Sender and the mapped target's Recver.
17.247826
6.544749
2.635369
if not self.ready: self.pause(timeout=timeout) if isinstance(item, Exception): return self.hub.throw_to(self.other.peak, item) return self.hub.switch_to(self.other.peak, self.other, item)
def send(self, item, timeout=-1)
Send an *item* on this pair. This will block unless our Rever is ready, either forever or until *timeout* milliseconds.
7.274787
6.206394
1.172144
r1 = recver m1 = r1.middle s2 = self m2 = self.middle r2 = self.other r2.middle = m1 del m2.sender del m2.recver del m1.recver m1.recver = weakref.ref(r2, m1.on_abandoned) m1.recver_current = m2.recver_current de...
def connect(self, recver)
Rewire: s1 -> m1 <- r1 --> s2 -> m2 <- r2 To: s1 -> m1 <- r2
5.437186
5.211473
1.043311
if self.ready: return self.other.handover(self) return self.pause(timeout=timeout)
def recv(self, timeout=-1)
Receive and item from our Sender. This will block unless our Sender is ready, either forever or unless *timeout* milliseconds.
17.667023
13.347579
1.323613
if callable(target): sender, recver = self.hub.pipe() # link the two ends in the closure with a strong reference to # prevent them from being garbage collected if this piped section # is used in a chain self.downstream = sender se...
def pipe(self, target)
Pipes this Recver to *target*. *target* can either be `Sender`_ (or `Pair`_) or a callable. If *target* is a Sender, the two pairs are rewired so that sending on this Recver's Sender will now be directed to the target's Recver:: sender1, recver1 = h.pipe() sender2, recv...
10.368484
10.481894
0.98918
@self.pipe def recver(recver, sender): for item in recver: try: sender.send(f(item)) except Exception, e: sender.send(e) return recver
def map(self, f)
*f* is a callable that takes a single argument. All values sent on this Recver's Sender will be passed to *f* to be transformed:: def double(i): return i * 2 sender, recver = h.pipe() recver.map(double) h.spawn(sender.send, 2) recver...
5.255705
4.214046
1.247187
@self.hub.spawn def _(): for item in self: # TODO: think through whether trapping for HALT here is a good # idea try: f(item) except vanilla.exception.Halt: self.close() ...
def consume(self, f)
Creates a sink which consumes all values for this Recver. *f* is a callable which takes a single argument. All values sent on this Recver's Sender will be passed to *f* for processing. Unlike *map* however consume terminates this chain:: sender, recver = h.pipe @recver....
14.692595
15.28359
0.961331
images_to_load = set() with timedsection('iterimages0'): for image in binary_images: if get_image_cpu_name(image) is not None: images_to_load.add(image['uuid'].lower()) images = {} # Step one: load images that are named by their UUID with timedsection('loa...
def find_debug_images(dsym_paths, binary_images)
Given a list of paths and a list of binary images this returns a dictionary of image addresses to the locations on the file system for all found images.
3.257825
3.282131
0.992594
idx = bisect.bisect_left(self._image_addresses, parse_addr(addr)) if idx > 0: return self.images[self._image_addresses[idx - 1]]
def find_image(self, addr)
Given an instruction address this locates the image this address is contained in.
3.44294
3.275719
1.051049
'''Calculate and returns an MD5 checksum for the specified file. Any file errors (non-existent file, read error, etc.) are not handled here but should be caught where this method is called. :param filename: full path to the file for which a checksum should be calculated :returns: hex-digest format...
def file_md5sum(filename)
Calculate and returns an MD5 checksum for the specified file. Any file errors (non-existent file, read error, etc.) are not handled here but should be caught where this method is called. :param filename: full path to the file for which a checksum should be calculated :returns: hex-digest formatted MD5...
5.165959
2.406392
2.146765
'''Calculate and returns an MD5 checksum for the specified content. :param content: text content :returns: hex-digest formatted MD5 checksum as a string ''' md5 = hashlib.md5() md5.update(force_bytes(content)) return md5.hexdigest()
def md5sum(content)
Calculate and returns an MD5 checksum for the specified content. :param content: text content :returns: hex-digest formatted MD5 checksum as a string
4.237568
2.177804
1.945799
if isinstance(items, basestring): items = [items] for i in range(1, len(items) + 1): params['%s.%d' % (label, i)] = items[i - 1]
def _build_list_params(self, params, items, label)
Add an AWS API-compatible parameter list to a dictionary. :type params: dict :param params: The parameter dictionary :type items: list :param items: Items to be included in the list :type label: string :param label: The parameter list's name
2.414718
3.278552
0.73652