def findNearestByTime (self, pose, tolerance=0): if (pose.timestamp < self.table[0].timestamp) : raise KeyError ("Timestamp less than table") if (pose.timestamp > self.table[self.c-1].timestamp) : raise KeyError ("Timestamp is outside table: " + str(pose.timestamp)) candidates = set() i = 0 for p in range(len(self.table)) : i = p cpose = self.table[i] if (cpose.timestamp > pose.timestamp) : candidates.add(cpose) i-=1 break while i!=0 : cpose = self.table[i] i -= 1 candidates.add (cpose) if (cpose.timestamp < pose.timestamp) : candidates.add (cpose) break if (tolerance>0) : tcandidates=[] for c in candidates: c.tdif = abs(c.timestamp-pose.timestamp) if c.tdif > tolerance: pass else: tcandidates.append(c) return sorted (tcandidates, key=lambda pose: pose.tdif) #return sorted (candidates, key=lambda pose: pose.timestamp) return min(candidates, key=lambda p: abs(p.timestamp-pose.timestamp))
def get_document(self): """ Uses the authentication token to fetch a google doc. """ # Handle basically all the things that can go wrong. if not self.auth: raise KeyError( "Error! You didn't get an auth token. Something very bad happened. File a bug?" ) elif not self.key: raise KeyError("Error! You forgot to pass a key to the class.") else: headers = {} headers['Authorization'] = "GoogleLogin auth=%s" % self.auth url_params = { 'key': self.key, 'format': self.file_format, 'gid': self.gid } url = self.new_spreadsheet_url % url_params r = requests.get(url, headers=headers) if r.status_code != 200: url = self.spreadsheet_url % url_params r = requests.get(url, headers=headers) if r.status_code != 200: raise KeyError("Error! Your Google Doc does not exist.") with open('data/%s.%s' % (self.file_name, self.file_format), 'wb') as writefile: writefile.write(r.content)
def get_document(key, file_path, template_type): """ Uses Authomatic to get the google doc """ credentials = get_credentials() if template_type == 'spreadsheet': TEMPLATE = SPREADSHEET_URL_TEMPLATE else: TEMPLATE = DOC_URL_TEMPLATE url = TEMPLATE % key response = app_config.authomatic.access(credentials, url) print url if response.status != 200: if response.status == 404: raise KeyError( "Error! Your Google Doc does not exist or you do not have permission to access it." ) else: raise KeyError("Error! Google returned a %s error" % response.status) with open(file_path, 'wb') as writefile: writefile.write(response.content)
def get_document(key, file_path, mimeType=None): """ Uses Authomatic to get the google doc """ # Default to spreadsheet if no mimeType is passed mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' if not mimeType: mimeType = mime credentials = get_credentials() url = DRIVE_API_EXPORT_TEMPLATE % (key, mimeType) response = app_config.authomatic.access(credentials, url) if response.status != 200: if response.status == 404: raise KeyError( "Error! Your Google Doc does not exist or you do not have permission to access it." ) else: raise KeyError("Error! Google returned a %s error" % response.status) with open(file_path, 'wb') as writefile: writefile.write(response.content)
def get_doc(key, file_path): """ Uses Authomatic to get the google doc """ credentials = get_credentials() url = DOC_URL_TEMPLATE % key response = app_config.authomatic.access(credentials, url) if response.status != 200: if response.status == 404: raise KeyError("Error! Your Google Doc (%s) does not exist or you do not have permission to access it." % key) else: raise KeyError("Error! Google returned a %s error" % response.status) with codecs.open(file_path, 'w', 'utf-8') as writefile: writefile.write(response.content)
def __getitem__(self, item): field = self.field(item) if field == None: raise KeyError('invalid field key "%s"' % item) return field.value()
def readByTime (self, second): rtm = rospy.Time.from_sec(second) if self.rTopicName is not None: for topic,msg,time in self.read_messages(topics=self.rTopicName, start_time=rtm): if msg is None: raise KeyError("Message not found in that time") return copy(msg)
def active_or_dead(result): if not result.has_key('cmd'): raise KeyError("Not a shell or command action result") if (('systemctl' not in result['cmd']) and ('status' not in result['cmd'])): raise ValueError("Not a systemctl status command") active_lines = [ l for l in result['stdout'].splitlines() if l.strip().startswith('Active: ') ] if len(active_lines) > 1: raise ValueError("Multiple 'Active:' lines detected") elif len(active_lines) < 1: raise ValueError("No 'Active:' lines detected") active_line = active_lines[0] if (((": active (exited)" in active_line) or (": active (running)" in active_line)) and (int(result['rc']) == 0)): return True if (": inactive (dead)" in active_line) and int(result['rc']) != 0: return True return False
def __setitem__(self, item, value): field = self.field(item) if field == None: raise KeyError('invalid field name') return field.setValue(value)
def get_bin_contents(self, bin_index): contents = self.values.get(bin_index, "DoesntExist") if contents is "DoesntExist": msg = "Cannot find bin for index, {0}, for binning called '{1}'" logger.error(msg.format(bin_index, self.label)) raise KeyError(bin_index) return contents
def subsetByTime (self, startTimestamp, duration): if startTimestamp < self.table[0].timestamp or startTimestamp > self.table[-1].timestamp: raise KeyError("Invalid timestamp: outside table") if startTimestamp+duration > self.table[-1].timestamp: raise KeyError("Duration reaches the future") subset = PoseTable() for i in range(len(self.table)): if self.table[i].timestamp >= startTimestamp: break while True: p = self.table[i] if startTimestamp + duration > p.timestamp: subset.append(p) else: break i += 1 return subset
def eval_condition(self, name): """ Evaluate a condition calling eval_condition from Condition instance @param name : The name of the condition instance @return {'name':name, 'result': evaluation result} or raise Exception """ if name not in self._conditions: raise KeyError('no key {0} in conditions table'.format(name)) else: res = self._conditions[name].eval_condition() return {'name': name, 'result': res}
def get_parsed_condition(self, name): """ Call cond.get_parsed_condition on the cond with name 'name' @param name : name of the Condition @return {'name':name, 'data': parsed_condition} or raise Exception """ if name not in self._conditions: raise KeyError('no key {0} in conditions table'.format(name)) else: parsed = self._conditions[name].get_parsed_condition() return {'name': name, 'data': parsed}
def get_customer_info(self, name): """ get customer info Args: name (str) : name of the customer """ if not self.customers[name]: raise KeyError('I am sorry! Customer does not exist') return self.customers[name]
def findNearPosesByTime (self, srcpose, tolerance=0.1): if (srcpose.timestamp < self.table[0].timestamp) : raise KeyError ("Timestamp less than table") if (srcpose.timestamp > self.table[-1].timestamp) : raise KeyError ("Timestamp is outside table: " + str(srcpose.timestamp)) nearMin = None nearMax = None for p in range(len(self)): i = p cpose = self.table[i] if (cpose.timestamp > srcpose.timestamp): nearMax = copy(cpose) break while i != 0 : cpose = self.table[i] i -= 1 if (cpose.timestamp < srcpose.timestamp): nearMin = copy (cpose) break return (nearMin, nearMax)
def trigger_actions(self, name): """ Trigger that will be called when a condition evaluates to True """ if name not in self._conditions_actions \ or name not in self._conditions: raise KeyError('no key %s in one of the _conditions tables table' % name) else: for action in self._conditions_actions[name]: self._actions_mapping[action].do_action( \ self._conditions[name], \ self._conditions[name].get_mapping() \ )
def get_document(key, file_path): print "GETTING DOCUMENT" """ Uses Authomatic to get the google doc """ credentials = get_credentials() # key = '1SAMHTa6dEfZQmkMlntCIKFhHWNpoL-2XhNKxR7txEDQ' url = SPREADSHEET_URL_TEMPLATE % key response = app_config.authomatic.access(credentials, url) if response.status != 200: if response.status == 404: raise KeyError( "Error! Your Google Doc does not exist or you do not have permission to access it." ) else: raise KeyError("Error! Google returned a %s error" % response.status) with open(file_path, 'wb') as writefile: writefile.write(response.content)
def __init__(self, **kwargs): self._storage_dict = {} self._handle = None self._handle_global = None self._parents = list(kwargs.pop("parents", [])) # Accumulate changes since last call to flush_deltas() self._delta_lock = threading.Lock() self._delta_attrs = {} self._delta_parents = [] self._calc_changes_delta = kwargs.pop("calc_changes_delta", lambda: True) for k, v in kwargs.items(): if not k in self._meta.storage_attributes: raise KeyError("Unknown attribute %s (not one of %s)" % (k, self._meta.storage_attributes.keys())) setattr(self, k, v) self.flush_deltas()
def get_auth(self): """ Gets an authorization token and adds it to the class. """ data = {} if not self.email or not self.password: raise KeyError("Error! You're missing some variables. You need to export APPS_GOOGLE_EMAIL and APPS_GOOGLE_PASS.") else: data['Email'] = self.email data['Passwd'] = self.password data['scope'] = self.scope data['service'] = self.service data['session'] = self.session r = requests.post("https://www.google.com/accounts/ClientLogin", data=data) self.auth = r.content.split('\n')[2].split('Auth=')[1]
def julian_day(year, month, day, hour, minute, sec): last_julian_day = 17520902.0 first_gregorian_day = 17520914.0 requested_date = 10000.0 * year + 100 * month + day if month <= 2: month += 12 year -= 1 if requested_date <= last_julian_day: b = -2 + ((year + 4716) / 4) - 1179 # Julian calendar elif requested_date >= first_gregorian_day: b = (year / 400) - (year / 100) + (year / 4) # Gregorian calendar else: raise KeyError("The requested date never happened") jd = 365.0 * year - 679004.0 + 2400000.5 + b + floor(30.6001 * (month + 1)) + day day_fraction = (fabs(hour) + fabs(minute) / 60.0 + fabs(sec) / 3600.0) / 24.0 return jd + day_fraction
def SelectQuery(self, *params, **kwds): if params and len(params) > 0: query = params[0] elif kwds: selectclause = "*" fromclause = "" whereclause = "" orderclause = "" limitclause = "" if kwds.has_key("select"): if isinstance(kwds["select"], basestring): selectclause = kwds["select"] elif type(kwds["select"]) == list: selectclause = ", ".join(kwds["select"]) if kwds.has_key("From"): fromclause = "%s" % (kwds["From"]) elif kwds.has_key("from"): fromclause = "%s" % (kwds["from"]) else: raise KeyError("Missing parameter from") if kwds.has_key("where"): if isinstance(kwds["where"], basestring): whereclause = kwds["where"] elif type(kwds["where"]) == list: whereclause = ", ".join(kwds["where"]) elif type(kwds["where"]) == dict: where = kwds["where"] for key in where: if type(where[key]) == list: _where = "" for value in where[key]: if isinstance(value, basestring): _where += "OR %s=\"%s\" " % ( key, self.db.escape_string(value)) else: _where += "OR %s=%s " % (key, str(value)) _where = _where[3:] whereclause += "(%s)" % (_where) else: value = where[key] if isinstance(value, basestring): whereclause += "AND %s=\"%s\" " % ( key, self.db.escape_string(value)) else: whereclause += "AND %s=%s " % (key, str(value)) whereclause = whereclause[4:] elif kwds.has_key("orwhere"): if isinstance(kwds["orwhere"], basestring): whereclause = kwds["orwhere"] elif type(kwds["orwhere"]) == list: whereclause = ", ".join(kwds["orwhere"]) elif type(kwds["orwhere"]) == dict: where = kwds["orwhere"] for key in where: if type(where[key]) == list: _where = "" for value in where[key]: if isinstance(value, basestring): _where += "OR %s=\"%s\" " % ( key, self.db.escape_string(value)) else: _where += "OR %s=%s " % (key, str(value)) _where = _where[3:] whereclause += "%s" % (_where) else: value = where[key] if isinstance(value, basestring): whereclause += "OR %s=\"%s\" " % ( key, self.db.escape_string(value)) else: whereclause += "OR %s=%s " % (key, str(value)) whereclause = whereclause[3:] if kwds.has_key("order"): if isinstance(kwds["order"], basestring): orderclause = kwds["order"] elif type(kwds["order"]) == list: orderclause = ", ".join(kwds["order"]) if kwds.has_key("limit"): limitclause = kwds["limit"] if kwds.has_key("limit1") and kwds.has_key("limit2"): if type(kwds["limit1"]) == int and type(kwds["limit2"]) == int: limitclause = "%u,%u" % (kwds["limit1"], kwds["limit2"]) else: limitclause = "%s,%s" % (int(kwds["limit1"], int(kwds["limit2"]))) if whereclause and whereclause != "" and not whereclause.upper( ).startswith("WHERE "): whereclause = "WHERE %s" % (whereclause) if orderclause and orderclause != "" and not orderclause.upper( ).startswith("ORDER BY "): orderclause = "ORDER BY %s" % (orderclause) if limitclause and limitclause != "" and not limitclause.upper( ).startswith("LIMIT "): limitclause = "LIMIT %s" % (limitclause) query = "SELECT %s FROM %s %s %s %s;" % (selectclause, fromclause, whereclause, orderclause, limitclause) return query
def test_key_error(self): from exceptions import KeyError assert str(KeyError('s')) == "'s'"
def getAttribute(self, name): if self.has_key(name): # ComLog.getLogger("Properties").debug("name: %s, value: %s" %(name, self.getProperty(name).getAttribute("value"))) return self.getProperty(name).getAttribute(Property.ATTRIBUTE_VALUE) else: raise KeyError(name)