code stringlengths 1 18.2k |
|---|
def _DataClean_(fieldVal): """ Return 'cleaned' value to standardize lookups (convert to uppercase, remove leading/trailing whitespace, carriage returns, line breaks, and unprintable characters) :param string fieldVal: field value """ fieldValNew = fieldVal fieldValNew = fieldValNew.upper() fieldValNew = fieldValNew.st... |
def _RunUserDefinedFunctions_(config, data, histObj, position, namespace=__name__): """ Return a single updated data record and history object after running user-defined functions :param dict config: DWM configuration (see DataDictionary) :param dict data: single record (dictionary) to which user-defined functions shou... |
def feed(self): "Feed a line from the contents of the GPS log to the daemon." line = self.testload.sentences[self.index % len(self.testload.sentences)] if "%Delay:" in line: # Delay specified number of seconds delay = line.split()[1] time.sleep(int(delay)) # self.write has to be set by the derived class self.write(line... |
def spawn(self, options, port, background=False, prefix=""): "Spawn a daemon instance." self.spawncmd = None # Look for gpsd in GPSD_HOME env variable if os.environ.get('GPSD_HOME'): for path in os.environ['GPSD_HOME'].split(':'): _spawncmd = "%s/gpsd" % path if os.path.isfile(_spawncmd) and os.access(_spawncmd, os.X_O... |
to implement the FakeGPS.read() method self.spawncmd += " -b -N -S %s -F %s -P %s %s" % (port, self.control_socket, self.pidfile, options) if prefix: self.spawncmd = prefix + " " + self.spawncmd.strip() if background: self.spawncmd += " &" status = os.system(self.spawncmd) if os.WIFSIGNALED(status) or os.WEXITSTATUS(st... |
def wait_pid(self): "Wait for the daemon, get its PID and a control-socket connection." while True: try: fp = open(self.pidfile) except IOError: time.sleep(0.1) continue try: fp.seek(0) pidstr = fp.read() self.pid = int(pidstr) except ValueError: time.sleep(0.5) continue # Avoid race condition -- PID not yet written fp... |
def add_device(self, path): "Add a device to the daemon's internal search list." if self.__get_control_socket(): self.sock.sendall("+%s\r\n\x00" % path) self.sock.recv(12) self.sock.close() |
def remove_device(self, path): "Remove a device from the daemon's internal search list." if self.__get_control_socket(): self.sock.sendall("-%s\r\n\x00" % path) self.sock.recv(12) self.sock.close() |
def kill(self): "Kill the daemon instance." if self.pid: try: os.kill(self.pid, signal.SIGTERM) # Raises an OSError for ESRCH when we've killed it. while True: os.kill(self.pid, signal.SIGTERM) time.sleep(0.01) except OSError: pass self.pid = None |
def addParts(parentPart, childPath, count, index): """ BUILD A hierarchy BY REPEATEDLY CALLING self METHOD WITH VARIOUS childPaths count IS THE NUMBER FOUND FOR self PATH """ if index == None: index = 0 if index == len(childPath): return c = childPath[index] parentPart.count = coalesce(parentPart.count, 0) + count if p... |
def encrypt(text, _key, salt=None): """ RETURN {"salt":s, "length":l, "data":d} -> JSON -> UTF8 """ if is_text(text): encoding = 'utf8' data = bytearray(text.encode("utf8")) elif is_binary(text): encoding = None if PY2: data = bytearray(text) else: data = text if _key is None: Log.error("Expecting a key") if is_binary(... |
def decrypt(data, _key): """ ACCEPT BYTES -> UTF8 -> JSON -> {"salt":s, "length":l, "data":d} """ # Key and iv have not been generated or provided, bail out if _key is None: Log.error("Expecting a key") _input = get_module("mo_json").json2value(data.decode('utf8'), leaves=False, flexible=False) # Initialize encryption ... |
def get_qs(self): """ Returns a mapping that will be used to generate the query string for the api url. Any values in the the `limit_choices_to` specified on the foreign key field and any arguments specified on self.extra_query_kwargs are converted to a format that can be used in a query string and returned as a dictio... |
def get_api_link(self): """ Adds a query string to the api url. At minimum adds the type=choices argument so that the return format is json. Any other filtering arguments calculated by the `get_qs` method are then added to the url. It is up to the destination url to respect them as filters. """ url = self._api_link if ... |
def label_for_value(self, value, key=None): """ Looks up the current value of the field and returns a unicode representation. Default implementation does a lookup on the target model and if a match is found calls force_unicode on that object. Otherwise a blank string is returned. """ if not key: key = self.rel.get_rela... |
def update_links(self, request, admin_site=None): """ Called to update the widget's urls. Tries to find the bundle for the model that this foreign key points to and then asks it for the urls for adding and listing and sets them on this widget instance. The urls are only set if request.user has permissions on that url. ... |
def schema_class(self, object_schema, model_name, classes=False): """ Create a object-class based on the object_schema. Use this class to create specific instances, and validate the data values. See the "python-jsonschema-objects" package for details on further usage. Parameters ---------- object_schema : dict The JSON... |
for further details. When `False` (default), return only the object-class Returns ------- - new class for given object_schema (default) - dict of all classes when :param:`classes` is True """ # if not model_name: # model_name = SchemaObjectFactory.schema_model_name(object_schema) cls_bldr = ClassBuilder(self.resolver) ... |
def __model_class(self, model_name): """ this method is used by the lru_cache, do not call directly """ build_schema = deepcopy(self.definitions[model_name]) return self.schema_class(build_schema, model_name) |
def binom(n, k): """ Returns binomial coefficient (n choose k). """ # http://blog.plover.com/math/choose.html if k > n: return 0 if k == 0: return 1 result = 1 for denom in range(1, k + 1): result *= n result /= denom n -= 1 return result |
def minimum_entropy_match_sequence(password, matches): """ Returns minimum entropy Takes a list of overlapping matches, returns the non-overlapping sublist with minimum entropy. O(nm) dp alg for length-n password with m candidate matches. """ bruteforce_cardinality = calc_bruteforce_cardinality(password) # e.g. 26 for ... |
entropy up to i-1 + entropy of this match is less than the current minimum at j. up_to = get(up_to_k, i-1) candidate_entropy = up_to + calc_entropy(match) if candidate_entropy < up_to_k[j]: #print "New minimum: using " + str(match) #print "Entropy: " + str(candidate_entropy) up_to_k[j] = candidate_entropy backpointers[... |
'entropy': lg(math.pow(bruteforce_cardinality, j - i + 1)), 'cardinality': bruteforce_cardinality, } k = 0 match_sequence_copy = [] for match in match_sequence: i, j = match['i'], match['j'] if i - k > 0: match_sequence_copy.append(make_bruteforce_match(k, i - 1)) k = j + 1 match_sequence_copy.append(match) if k < len(... |
def round_to_x_digits(number, digits): """ Returns 'number' rounded to 'digits' digits. """ return round(number * math.pow(10, digits)) / math.pow(10, digits) |
def values(self): """ TRY NOT TO USE THIS, IT IS SLOW """ matrix = self.data.values()[0] # CANONICAL REPRESENTATIVE if matrix.num == 0: return e_names = self.edges.name s_names = self.select.name parts = [e.domain.partitions.value if e.domain.primitive else e.domain.partitions for e in self.edges] for c in matrix._all_... |
def forall(self, method): """ TODO: I AM NOT HAPPY THAT THIS WILL NOT WORK WELL WITH WINDOW FUNCTIONS THE parts GIVE NO INDICATION OF NEXT ITEM OR PREVIOUS ITEM LIKE rownum DOES. MAYBE ALGEBRAIC EDGES SHOULD BE LOOPED DIFFERENTLY? ON THE OTHER HAND, MAYBE WINDOW FUNCTIONS ARE RESPONSIBLE FOR THIS COMPLICATION MAR 2015:... |
self) |
def _groupby(self, edges): """ RETURNS LIST OF (coord, values) TUPLES, WHERE coord IS THE INDEX INTO self CUBE (-1 INDEX FOR COORDINATES NOT GROUPED BY) values ALL VALUES THAT BELONG TO THE SLICE """ edges = FlatList([n for e in edges for n in _normalize_edge(e)]) stacked = [e for e in self.edges if e.name in edges.nam... |
= listwrap(self.select) index, v = transpose(*self.data[selects[0].name].groupby(selector)) coord = wrap([coord2term(c) for c in index]) values = [v] for s in selects[1::]: i, v = transpose(*self.data[s.name].group_by(selector)) values.append(v) output = transpose(coord, [Cube(self.select, remainder, {s.name: v[i] for ... |
def save_swagger_spec(self, filepath=None): """ Saves a copy of the origin_spec to a local file in JSON format """ if filepath is True or filepath is None: filepath = self.file_spec.format(server=self.server) json.dump(self.origin_spec, open(filepath, 'w+'), indent=3) |
def load_swagger_spec(self, filepath=None): """ Loads the origin_spec from a local JSON file. If `filepath` is not provided, then the class `file_spec` format will be used to create the file-path value. """ if filepath is True or filepath is None: filepath = self.file_spec.format(server=self.server) return json.load(op... |
def preprocess_legislation(legislation_json): ''' Preprocess the legislation parameters to add prices and amounts from national accounts ''' import os import pkg_resources import pandas as pd # Add fuel prices to the tree default_config_files_directory = os.path.join( pkg_resources.get_distribution('openfisca_france_in... |
values1['stop'] = u'{}-12-31'.format(year) values1['value'] = prix_annuel.loc[year] * 100 all_values['super_95_e10_ttc'].append(values1) prix_annuel = prix_annuel_carburants['super_95_ttc'] for year in range(2009, 2013): values2 = dict() values2['start'] = u'{}-01-01'.format(year) values2['stop'] = u'{}-12-31'.format(y... |
= prix_carburants # Add the number of vehicle in circulation to the tree default_config_files_directory = os.path.join( pkg_resources.get_distribution('openfisca_france_indirect_taxation').location) parc_annuel_moyen_vp = pd.read_csv( os.path.join( default_config_files_directory, 'openfisca_france_indirect_taxation', '... |
os.path.join( pkg_resources.get_distribution('openfisca_france_indirect_taxation').location) quantite_carbu_vp_france = pd.read_csv( os.path.join( default_config_files_directory, 'openfisca_france_indirect_taxation', 'assets', 'quantites', 'quantite_carbu_vp_france.csv' ), sep =';' ) quantite_carbu_vp_france = quantite... |
> 0].copy() part_des_types_de_supercarburants['annee'] = part_des_types_de_supercarburants['annee'].astype(int) part_des_types_de_supercarburants = part_des_types_de_supercarburants.set_index('annee') # delete share of e_85 because we have no data for its price # When the sum of all shares is not one, need to multiply ... |
values['start'] = u'{}-01-01'.format(year) values['stop'] = u'{}-12-31'.format(year) values['value'] = part_par_carburant.loc[year] values_part_supercarburants[element].append(values) part_type_supercaburant['children'][element] = { "@type": "Parameter", "description": "part de " + element + " dans la consommation tota... |
127}, {'start': u'2001-01-01', 'stop': u'2001-12-31', 'value': 127}, {'start': u'2002-01-01', 'stop': u'2002-12-31', 'value': 127}, {'start': u'2003-01-01', 'stop': u'2003-12-31', 'value': 127}, {'start': u'2004-01-01', 'stop': u'2004-12-31', 'value': 125}, {'start': u'2005-01-01', 'stop': u'2005-12-31', 'value': 117},... |
'stop': u'1998-12-31', 'value': 8025}, {'start': u'1999-01-01', 'stop': u'1999-12-31', 'value': 8451}, {'start': u'2000-01-01', 'stop': u'2000-12-31', 'value': 8854}, {'start': u'2001-01-01', 'stop': u'2001-12-31', 'value': 9168}, {'start': u'2002-01-01', 'stop': u'2002-12-31', 'value': 9476}, {'start': u'2003-01-01', ... |
"Masse droit biere selon comptabilité nationale", "format": "float", "values": [ {'start': u'1995-01-01', 'stop': u'1995-12-31', 'value': 361}, {'start': u'1996-01-01', 'stop': u'1996-12-31', 'value': 366}, {'start': u'1997-01-01', 'stop': u'1997-12-31', 'value': 364}, {'start': u'1998-01-01', 'stop': u'1998-12-31', 'v... |
u'2014-12-31', 'value': }, ], }, "masse_conso_cn_biere": { "@type": "Parameter", "description": u"Masse consommation biere selon comptabilité nationale", "format": "float", "values": [ {'start': u'1995-01-01', 'stop': u'1995-12-31', 'value': 2111}, {'start': u'1996-01-01', 'stop': u'1996-12-31', 'value': 2144}, {'start... |
{'start': u'2013-01-01', 'stop': u'2013-12-31', 'value': 3321}, # {'start': u'2014-01-01', 'stop': u'2014-12-31', 'value': }, ], }, }, } alcool_conso_et_vin['children']['alcools_forts'] = { "@type": "Node", "description": "Pour calculer le taux de taxation implicite sur alcools forts", "children": { "droit_cn_alcools":... |
u'2011-01-01', 'stop': u'2011-12-31', 'value': 2150}, {'start': u'2012-01-01', 'stop': u'2012-12-31', 'value': 2225}, # TODO: Problème pour les alcools forts chiffres différents entre les deux bases excel ! ], }, "droit_cn_alcools_total": { "@type": "Parameter", "description": u"Masse droit alcool selon comptabilité na... |
u'2008-12-31', 'value': 2528}, {'start': u'2009-01-01', 'stop': u'2009-12-31', 'value': 2629}, {'start': u'2010-01-01', 'stop': u'2010-12-31', 'value': 2734}, {'start': u'2011-01-01', 'stop': u'2011-12-31', 'value': 3078}, {'start': u'2012-01-01', 'stop': u'2012-12-31', 'value': 2718}, {'start': u'2013-01-01', 'stop': ... |
6106}, {'start': u'2007-01-01', 'stop': u'2007-12-31', 'value': 6142}, {'start': u'2008-01-01', 'stop': u'2008-12-31', 'value': 6147}, {'start': u'2009-01-01', 'stop': u'2009-12-31', 'value': 6342}, {'start': u'2010-01-01', 'stop': u'2010-12-31', 'value': 6618}, {'start': u'2011-01-01', 'stop': u'2011-12-31', 'value': ... |
def set_more_headers(self, req, extra_headers=None): """Set content-type, content-md5, date to the request Returns a new `PreparedRequest` :param req: the origin unsigned request :param extra_headers: extra headers you want to set, pass as dict """ oss_url = url.URL(req.url) req.headers.update(extra_headers or {}) # se... |
def get_signature(self, req): """calculate the signature of the oss request Returns the signatue """ oss_url = url.URL(req.url) oss_headers = [ "{0}:{1}\n".format(key, val) for key, val in req.headers.lower_items() if key.startswith(self.X_OSS_PREFIX) ] canonicalized_headers = "".join(sorted(oss_headers)) logger.debug(... |
def convert(self, expr): """ EXPAND INSTANCES OF name TO value """ if expr is True or expr == None or expr is False: return expr elif is_number(expr): return expr elif expr == ".": return "." elif is_variable_name(expr): return coalesce(self.dimensions[expr], expr) elif is_text(expr): Log.error("{{name|quote}} is not a... |
def _convert_clause(self, clause): """ JSON QUERY EXPRESSIONS HAVE MANY CLAUSES WITH SIMILAR COLUMN DELCARATIONS """ clause = wrap(clause) if clause == None: return None elif is_data(clause): return set_default({"value": self.convert(clause.value)}, clause) else: return [set_default({"value": self.convert(c.value)}, c)... |
def get_obstory_ids(self): """ Retrieve the IDs of all obstorys. :return: A list of obstory IDs for all obstorys """ self.con.execute('SELECT publicId FROM archive_observatories;') return map(lambda row: row['publicId'], self.con.fetchall()) |
def has_obstory_metadata(self, status_id): """ Check for the presence of the given metadata item :param string status_id: The metadata item ID :return: True if we have a metadata item with this ID, False otherwise """ self.con.execute('SELECT 1 FROM archive_metadata WHERE publicId=%s;', (status_id,)) return len(self.co... |
def has_file_id(self, repository_fname): """ Check for the presence of the given file_id :param string repository_fname: The file ID :return: True if we have a :class:`meteorpi_model.FileRecord` with this ID, False otherwise """ self.con.execute('SELECT 1 FROM archive_files WHERE repositoryFname = %s', (repository_fnam... |
def get_file(self, repository_fname): """ Retrieve an existing :class:`meteorpi_model.FileRecord` by its ID :param string repository_fname: The file ID :return: A :class:`meteorpi_model.FileRecord` instance, or None if not found """ search = mp.FileRecordSearch(repository_fname=repository_fname) b = search_files_sql_bu... |
def search_files(self, search): """ Search for :class:`meteorpi_model.FileRecord` entities :param search: an instance of :class:`meteorpi_model.FileRecordSearch` used to constrain the observations returned from the DB :return: a structure of {count:int total rows of an unrestricted search, observations:list of :class:`... |
def register_file(self, observation_id, user_id, file_path, file_time, mime_type, semantic_type, file_md5=None, file_meta=None): """ Register a file in the database, also moving the file into the file store. Returns the corresponding FileRecord object. :param observation_id: The publicId of the observation this file be... |
:class:`meteorpi_model.FileRecord` as stored in the database """ if file_meta is None: file_meta = [] # Check that file exists if not os.path.exists(file_path): raise ValueError('No file exists at {0}'.format(file_path)) # Get checksum for file, and size file_size_bytes = os.stat(file_path).st_size file_name = os.path.... |
archive_observations WHERE publicId=%s), %s, %s, %s, %s, %s, %s, %s); """, (observation_id, mime_type, file_name, semantic_type_id, file_time, file_size_bytes, repository_fname, file_md5)) # Move the original file from its path target_file_path = os.path.join(self.file_store_path, repository_fname) try: shutil.move(fil... |
def has_observation_id(self, observation_id): """ Check for the presence of the given observation_id :param string observation_id: The observation ID :return: True if we have a :class:`meteorpi_model.Observation` with this Id, False otherwise """ self.con.execute('SELECT 1 FROM archive_observations WHERE publicId = %s'... |
def get_observation(self, observation_id): """ Retrieve an existing :class:`meteorpi_model.Observation` by its ID :param string observation_id: UUID of the observation :return: A :class:`meteorpi_model.Observation` instance, or None if not found """ search = mp.ObservationSearch(observation_id=observation_id) b = searc... |
def search_observations(self, search): """ Search for :class:`meteorpi_model.Observation` entities :param search: an instance of :class:`meteorpi_model.ObservationSearch` used to constrain the observations returned from the DB :return: a structure of {count:int total rows of an unrestricted search, observations:list of... |
def register_observation(self, obstory_name, user_id, obs_time, obs_type, obs_meta=None): """ Register a new observation, updating the database and returning the corresponding Observation object :param string obstory_name: The ID of the obstory which produced this observation :param string user_id: The ID of the user w... |
# Insert into database self.con.execute(""" INSERT INTO archive_observations (publicId, observatory, userId, obsTime, obsType) VALUES (%s, %s, %s, %s, %s); """, (observation_id, obstory['uid'], user_id, obs_time, obs_type_id)) # Store the observation metadata for meta in obs_meta: self.set_observation_metadata(user_id,... |
def has_obsgroup_id(self, group_id): """ Check for the presence of the given group_id :param string group_id: The group ID :return: True if we have a :class:`meteorpi_model.ObservationGroup` with this Id, False otherwise """ self.con.execute('SELECT 1 FROM archive_obs_groups WHERE publicId = %s', (group_id,)) return le... |
def get_obsgroup(self, group_id): """ Retrieve an existing :class:`meteorpi_model.ObservationGroup` by its ID :param string group_id: UUID of the observation :return: A :class:`meteorpi_model.Observation` instance, or None if not found """ search = mp.ObservationGroupSearch(group_id=group_id) b = search_obsgroups_sql_b... |
def search_obsgroups(self, search): """ Search for :class:`meteorpi_model.ObservationGroup` entities :param search: an instance of :class:`meteorpi_model.ObservationGroupSearch` used to constrain the observations returned from the DB :return: a structure of {count:int total rows of an unrestricted search, observations:... |
def register_obsgroup(self, title, user_id, semantic_type, obs_time, set_time, obs=None, grp_meta=None): """ Register a new observation, updating the database and returning the corresponding Observation object :param string title: The title of this observation group :param string user_id: The ID of the user who created... |
for semantic_type semantic_type_id = self.get_obs_type_id(semantic_type) # Insert into database self.con.execute(""" INSERT INTO archive_obs_groups (publicId, title, time, setByUser, setAtTime, semanticType) VALUES (%s, %s, %s, %s, %s, %s); """, (group_id, title, obs_time, user_id, set_time, semantic_type_id)) # Store ... |
def get_user(self, user_id, password): """ Retrieve a user record :param user_id: the user ID :param password: password :return: A :class:`meteorpi_model.User` if everything is correct :raises: ValueError if the user is found but password is incorrect or if the user is not found. """ self.con.execute('SELECT uid, pwHas... |
def get_users(self): """ Retrieve all users in the system :return: A list of :class:`meteorpi_model.User` """ output = [] self.con.execute('SELECT userId, uid FROM archive_users;') results = self.con.fetchall() for result in results: # Fetch list of roles self.con.execute('SELECT name FROM archive_roles r INNER JOIN ar... |
def create_or_update_user(self, user_id, password, roles): """ Create a new user record, or update an existing one :param user_id: user ID to update or create :param password: new password, or None to leave unchanged :param roles: new roles, or None to leave unchanged :return: the action taken, one of "none", "update",... |
None: self.con.execute('UPDATE archive_users SET pwHash = %s WHERE userId = %s', (passlib.hash.bcrypt.encrypt(password), user_id)) if roles is not None: # Clear out existing roles, and delete any unused roles self.con.execute("DELETE r FROM archive_user_roles AS r WHERE " "(SELECT u.userId FROM archive_users AS u WHERE... |
def get_export_configuration(self, config_id): """ Retrieve the ExportConfiguration with the given ID :param string config_id: ID for which to search :return: a :class:`meteorpi_model.ExportConfiguration` or None, or no match was found. """ sql = ( 'SELECT uid, exportConfigId, exportType, searchString, targetURL, ' 'ta... |
def get_export_configurations(self): """ Retrieve all ExportConfigurations held in this db :return: a list of all :class:`meteorpi_model.ExportConfiguration` on this server """ sql = ( 'SELECT uid, exportConfigId, exportType, searchString, targetURL, ' 'targetUser, targetPassword, exportName, description, active ' 'FRO... |
def create_or_update_export_configuration(self, export_config): """ Create a new file export configuration or update an existing one :param ExportConfiguration export_config: a :class:`meteorpi_model.ExportConfiguration` containing the specification for the export. If this doesn't include a 'config_id' field it will be... |
archive_exportConfig c ' 'SET c.searchString = %s, c.targetUrl = %s, c.targetUser = %s, c.targetPassword = %s, ' 'c.exportName = %s, c.description = %s, c.active = %s, c.exportType = %s ' 'WHERE c.exportConfigId = %s', (search_string, target_url, user_id, password, name, description, enabled, export_type, export_config... |
def mark_entities_to_export(self, export_config): """ Apply the specified :class:`meteorpi_model.ExportConfiguration` to the database, running its contained query and creating rows in t_observationExport or t_fileExport for matching entities. :param ExportConfiguration export_config: An instance of :class:`meteorpi_mod... |
of the search and set the properties required when creating exports search = mp.ObservationSearch.from_dict(export_config.search.as_dict()) search.exclude_export_to = export_config.config_id b = search_observations_sql_builder(search) self.con.execute(b.get_select_sql(columns='o.uid, o.obsTime'), b.sql_args) for result... |
export_config.config_id b = search_metadata_sql_builder(search) self.con.execute(b.get_select_sql(columns='m.uid, m.setAtTime'), b.sql_args) for result in self.con.fetchall(): self.con.execute('INSERT INTO archive_metadataExport ' '(metadataId, setAtTime, exportConfig, exportState) ' 'VALUES (%s,%s,%s,%s)', (result['ui... |
def get_next_entity_to_export(self): """ Examines the archive_observationExport and archive_metadataExport tables, and builds either a :class:`meteorpi_db.ObservationExportTask` or a :class:`meteorpi_db.MetadataExportTask` as appropriate. These task objects can be used to retrieve the underlying entity and export confi... |
for items if (not self.export_queue_metadata) and (not self.export_queue_observations) and (not self.export_queue_files): self.export_queue_valid_until = time.time() + 60 # Try to retrieve the earliest record in archive_metadataExport self.con.execute('SELECT c.exportConfigId, o.publicId, x.exportState, ' 'c.targetURL,... |
self.export_queue_observations = list(self.con.fetchall()) if not self.export_queue_observations: # Try to retrieve the earliest record in archive_fileExport self.con.execute('SELECT c.exportConfigId, o.repositoryFname, x.exportState, ' 'c.targetURL, c.targetUser, c.targetPassword ' 'FROM archive_fileExport x ' 'INNER ... |
self.export_queue_files.pop(0) config_id = row['exportConfigId'] entity_id = row['repositoryFname'] status = row['exportState'] target_url = row['targetURL'] target_user = row['targetUser'] target_password = row['targetPassword'] return FileExportTask(db=self, config_id=config_id, file_id=entity_id, status=status, targ... |
def get_high_water_mark(self, mark_type, obstory_name=None): """ Retrieves the high water mark for a given obstory, defaulting to the current installation ID :param string mark_type: The type of high water mark to set :param string obstory_name: The obstory ID to check for, or the default installation ID if not specifi... |
def get(self, key): """ simple `select` """ if not Log: _late_import() return FlatList(vals=[unwrap(coalesce(_datawrap(v), Null)[key]) for v in _get_list(self)]) |
def right(self, num=None): """ WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE RIGHT [-num:] """ if num == None: return FlatList([_get_list(self)[-1]]) if num <= 0: return Null return FlatList(_get_list(self)[-num:]) |
def left(self, num=None): """ NOT REQUIRED, BUT EXISTS AS OPPOSITE OF right() """ if num == None: return FlatList([_get_list(self)[0]]) if num <= 0: return Null return FlatList(_get_list(self)[:num]) |
def not_right(self, num): """ WITH SLICES BEING FLAT, WE NEED A SIMPLE WAY TO SLICE FROM THE LEFT [:-num:] """ if num == None: return FlatList([_get_list(self)[:-1:]]) if num <= 0: return FlatList.EMPTY return FlatList(_get_list(self)[:-num:]) |
def not_left(self, num): """ NOT REQUIRED, EXISTS AS OPPOSITE OF not_right() """ if num == None: return FlatList([_get_list(self)[-1]]) if num <= 0: return self return FlatList(_get_list(self)[num::]) |
def baseglob(pat, base): """Given a pattern and a base, return files that match the glob pattern and also contain the base.""" return [f for f in glob(pat) if f.startswith(base)] |
def cibaseglob(pat, base): """Case insensitive baseglob. Note that it's not *actually* case insensitive, since glob is insensitive or not based on local semantics. Instead, it tries the original version, an upper() version, a lower() version, and a swapcase() version of the glob.""" results = [] for func in (str, str.u... |
def dircolorize(path, name_only=True): """Use user dircolors settings to colorize a string which is a path. If name_only is True, it does this by the name rules (*.x) only; it will not check the filesystem to colorize things like pipes, block devs, doors, etc.""" if not name_only: raise NotImplemented("Filesystem check... |
def get_revision(): """ GET THE CURRENT GIT REVISION """ proc = Process("git log", ["git", "log", "-1"]) try: while True: line = proc.stdout.pop().strip().decode('utf8') if not line: continue if line.startswith("commit "): return line[7:] finally: with suppress_exception: proc.join() |
def get_remote_revision(url, branch): """ GET REVISION OF A REMOTE BRANCH """ proc = Process("git remote revision", ["git", "ls-remote", url, "refs/heads/" + branch]) try: while True: raw_line = proc.stdout.pop() line = raw_line.strip().decode('utf8') if not line: continue return line.split("\t")[0] finally: try: proc.... |
def get_branch(): """ GET THE CURRENT GIT BRANCH """ proc = Process("git status", ["git", "status"]) try: while True: raw_line = proc.stdout.pop() line = raw_line.decode('utf8').strip() if line.startswith("On branch "): return line[10:] finally: try: proc.join() except Exception: pass |
def _normalize(esfilter): """ TODO: DO NOT USE Data, WE ARE SPENDING TOO MUCH TIME WRAPPING/UNWRAPPING REALLY, WE JUST COLLAPSE CASCADING `and` AND `or` FILTERS """ if esfilter == MATCH_ALL or esfilter == MATCH_NONE or esfilter.isNormal: return esfilter # Log.note("from: " + convert.value2json(esfilter)) isDiff = True ... |
tt0 = t0.range.items()[0] f1, tt1 = t1.range.items()[0] if f0 == f1: set_default(terms[i0].range[literal_field(f1)], tt1) terms[i1] = MATCH_ALL output = [] for a in terms: if is_container(a): from mo_logs import Log Log.error("and clause is not allowed a list inside a list") a_ = _normalize(a) if a_ is not a: isDiff = ... |
a.bool.should: a.isNormal = None isDiff = True output.extend(a.bool.should) else: a.isNormal = None output.append(a) if not output: return MATCH_NONE elif len(output) == 1: esfilter = output[0] break elif isDiff: esfilter = wrap(es_or(output)) continue if esfilter.term != None: if esfilter.term.keys(): esfilter.isNorma... |
sub.isNormal = None return wrap({"bool": {"must_not": sub, "isNormal": True}}) else: sub.isNormal = None esfilter.isNormal = True return esfilter |
def split_expression_by_depth(where, schema, output=None, var_to_depth=None): """ :param where: EXPRESSION TO INSPECT :param schema: THE SCHEMA :param output: :param var_to_depth: MAP FROM EACH VARIABLE NAME TO THE DEPTH :return: """ """ It is unfortunate that ES can not handle expressions that span nested indexes. Thi... |
is_op(where, AndOp_): for a in where.terms: split_expression_by_depth(a, schema, output, var_to_depth) else: Log.error("Can not handle complex where clause") return output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.