code
stringlengths
1
18.2k
changed, then we want to use the original file/line # Also have to replace indentation of original line with indentation of new line # To take into account nested describes if text and not regexes['only_whitespace'].match(text): if regexes['whitespace'].sub('', text) == regexes['whitespace'].sub('', data): bad_indentat...
a file is of spec encoding and return special CodecInfo if it is""" if s != 'spec': return None return codecs.CodecInfo( name='spec' , encode=utf8.encode , decode=decode , streamreader=StreamReader , streamwriter=utf8.streamwriter , incrementalencoder=utf8.incrementalencoder , incrementaldecoder=incrementaldecoder ) # ...
def dealwith(self, readline, **kwargs): """ Replace the contents of spec file with the translated version readline should be a callable object , which provides the same interface as the readline() method of built-in file objects """ data = [] try: # We pass in the data variable as an argument so that we # get partial o...
add a new line and put out line numberes if len(lines) == 1: data = "{0}{1}".format(exception, lines[0]) else: lines.append(exception) first_line = lines.pop() lines[0] = "{0} {1}".format(first_line, lines[0]) data = '\n'.join(lines) else: # At this point, data is a list of tokens data = untokenize(data) if six.PY2 and...
def output_for_debugging(self, stream, data): """It will write the translated version of the file""" with open('%s.spec.out' % stream.name, 'w') as f: f.write(str(data))
def to_python(self, value): """ Validates that the value is in self.choices and can be coerced to the right type. """ value = '' if value in validators.EMPTY_VALUES else smart_text(value) if value == self.empty_value or value in validators.EMPTY_VALUES: return self.empty_value try: value = self.coerce(value) except (Va...
def validate(self, value): """ Validates that the input is in self.choices. """ super(ChoicesField, self).validate(value) if value and not self.valid_value(value): self._on_invalid_value(value)
def valid_value(self, value): """ Check if the provided value is a valid choice. """ if isinstance(value, Constant): value = value.name text_value = force_text(value) for option_value, option_label, option_title in self.choices: if value == option_value or text_value == force_text(option_value): return True return Fals...
def _unit_info(self) -> Tuple[str, int]: """ Returns both the best unit to measure the size, and its power. :return: A tuple containing the unit and its power. """ abs_bytes = abs(self.size) if abs_bytes < 1024: unit = 'B' unit_divider = 1 elif abs_bytes < (1024 ** 2): unit = 'KB' unit_divider = 1024 elif abs_bytes < (...
def pretty_print(self, printer: Optional[Printer] = None, min_width: int = 1, min_unit_width: int = 1): """ Prints the file size (and it's unit), reserving places for longer sizes and units. For example: min_unit_width = 1: 793 B 100 KB min_unit_width = 2: 793 B 100 KB min_unit_width = 3: 793 B 100 KB """ unit, unit_di...
* spaces_count) printer.write(f'{size_string} {unit_color}{unit}')
def execute_sql( host, username, password, sql, schema=None, param=None, kwargs=None ): """EXECUTE MANY LINES OF SQL (FROM SQLDUMP FILE, MAYBE?""" kwargs.schema = coalesce(kwargs.schema, kwargs.database) if param: with MySQL(kwargs) as temp: sql = expand_template(sql, quote_param(param)) # We have no way to execute an ...
def quote_value(value): """ convert values to mysql code for the same mostly delegate directly to the mysql lib, but some exceptions exist """ try: if value == None: return SQL_NULL elif isinstance(value, SQL): return quote_sql(value.template, value.param) elif is_text(value): return SQL("'" + "".join(ESCAPE_DCT.get(c,...
def quote_sql(value, param=None): """ USED TO EXPAND THE PARAMETERS TO THE SQL() OBJECT """ try: if isinstance(value, SQL): if not param: return value param = {k: quote_sql(v) for k, v in param.items()} return SQL(expand_template(value, param)) elif is_text(value): return SQL(value) elif is_data(value): return quote_va...
def int_list_packer(term, values): """ return singletons, ranges and exclusions """ DENSITY = 10 # a range can have holes, this is inverse of the hole density MIN_RANGE = 20 # min members before a range is allowed to be used singletons = set() ranges = [] exclude = set() sorted = jx.sort(values) last = sorted[0] curr_s...
|= set(range(curr_start, last + 1)) singletons -= curr_excl else: # big enough, and dense enough range ranges.append({"gte": curr_start, "lte": last}) exclude |= curr_excl curr_start = v curr_excl = set() else: if 1 + last - curr_start >= len(curr_excl) * DENSITY: # high density, keep track of excluded and continue add...
last - curr_start - len(curr_excl) < MIN_RANGE or ((last - curr_start) < len(curr_excl) * DENSITY): # small ranges are singletons, sparse ranges are singletons singletons |= set(range(curr_start, last + 1)) singletons -= curr_excl else: # big enough, and dense enough range ranges.append({"gte": curr_start, "lte": last}...
def _open(self): """ DO NOT USE THIS UNLESS YOU close() FIRST""" try: self.db = connect( host=self.settings.host, port=self.settings.port, user=coalesce(self.settings.username, self.settings.user), passwd=coalesce(self.settings.password, self.settings.passwd), db=coalesce(self.settings.schema, self.settings.db), read_t...
def query(self, sql, param=None, stream=False, row_tuples=False): """ RETURN LIST OF dicts """ if not self.cursor: # ALLOW NON-TRANSACTIONAL READS Log.error("must perform all queries inside a transaction") self._execute_backlog() try: if param: sql = expand_template(sql, quote_param(param)) sql = self.preamble + outden...
def column_query(self, sql, param=None): """ RETURN RESULTS IN [column][row_num] GRID """ self._execute_backlog() try: old_cursor = self.cursor if not old_cursor: # ALLOW NON-TRANSACTIONAL READS self.cursor = self.db.cursor() self.cursor.execute("SET TIME_ZONE='+00:00'") self.cursor.close() self.cursor = self.db.cursor...
def update(self, table_name, where_slice, new_values): """ where_slice - A Data WHICH WILL BE USED TO MATCH ALL IN table eg {"id": 42} new_values - A dict WITH COLUMN NAME, COLUMN VALUE PAIRS TO SET """ new_values = quote_param(new_values) where_clause = SQL_AND.join([ quote_column(k) + "=" + quote_value(v) if v != Non...
def tokenize_tags(tags_string): """ This function is responsible to extract usable tags from a text. :param tags_string: a string of text :return: a string of comma separated tags """ # text is parsed in two steps: # the first step extract every single world that is 3 > chars long # and that contains only alphanumeric ...
def build_depenses_homogenisees(temporary_store = None, year = None): """Build menage consumption by categorie fiscale dataframe """ assert temporary_store is not None assert year is not None bdf_survey_collection = SurveyCollection.load( collection = 'budget_des_familles', config_files_directory = config_files_directo...
'ident_men', 'ponderrd': 'pondmen', }, inplace = True ) poids.set_index('ident_men', inplace = True) conso = survey.get_values(table = "depnom") conso = conso[["valeur", "montant", "mena", "nomen5"]] conso = conso.groupby(["mena", "nomen5"]).sum() conso = conso.reset_index() conso.rename( columns = { 'mena': 'ident_men...
'c99999'] + \ ["c0{}".format(i) for i in range(1, 10)] + \ ["c{}".format(i) for i in range(10, 14)]: del conso[variable] if year == 2005: conso = survey.get_values(table = "c05d") if year == 2011: try: conso = survey.get_values(table = "C05") except: conso = survey.get_values(table = "c05") conso.rename( columns = { 'i...
trois autres années if year == 1995: coicop_labels = [ normalize_code_coicop(coicop_by_poste_bdf.get(poste_bdf)) for poste_bdf in conso.columns ] else: coicop_labels = [ normalize_code_coicop(coicop_by_poste_bdf.get(reformat_consumption_column_coicop(poste_bdf))) for poste_bdf in conso.columns ] tuples = zip(coicop_lab...
depenses.rename(columns = {u'0421': 'poste_coicop_421'}, inplace = True) produits = [column for column in depenses.columns if column.isdigit()] for code in produits: if code[-1:] == '0': depenses.rename(columns = {code: code[:-1]}, inplace = True) else: depenses.rename(columns = {code: code}, inplace = True) produits =...
def normalize_code_coicop(code): '''Normalize_coicop est function d'harmonisation de la colonne d'entiers posteCOICOP de la table matrice_passage_data_frame en la transformant en une chaine de 5 caractères afin de pouvoir par la suite agréger les postes COICOP selon les 12 postes agrégés de la nomenclature de la compta...
(021.0) elif code.startswith("0"): code_coicop = code + "0" elif code in ["1151", "1181", "4552", "4522", "4511", "9122", "9151", "9211", "9341", "1411"]: # 1151 = Margarines et autres graisses végétales # 1181 = Confiserie # 04522 = Achat de butane, propane # 04511 = Facture EDF GDF non dissociables code_coicop = "0" ...
def deactivate(): """ Deactivate a state in this thread. """ if hasattr(_mode, "current_state"): del _mode.current_state if hasattr(_mode, "schema"): del _mode.schema for k in connections: con = connections[k] if hasattr(con, 'reset_schema'): con.reset_schema()
def readScriptRanges(scripts=None): """ Read script ranges from http://unicode.org/Public/UNIDATA/Scripts.txt file. """ scripts = scripts or LATIN_LIKE_SCRIPTS ranges = [] f = open('Scripts.txt', 'r') for line in f: line = line.strip('\n') matchObj = re.match( '^([0123456789ABCDEF]{4}(\.\.[0123456789ABCDEF]{4})?)\s*;\s...
def collections(record, key, value): """Parse custom MARC tag 980.""" return { 'primary': value.get('a'), 'secondary': value.get('b'), 'deleted': value.get('c'), }
def reverse_collections(self, key, value): """Reverse colections field to custom MARC tag 980.""" return { 'a': value.get('primary'), 'b': value.get('secondary'), 'c': value.get('deleted'), }
def _select1(data, field, depth, output): """ SELECT A SINGLE FIELD """ for d in data: for i, f in enumerate(field[depth:]): d = d[f] if d == None: output.append(None) break elif is_list(d): _select1(d, field, i + 1, output) break else: output.append(d)
def request(self, url, post=None, method="GET"): """ Make the request""" dsid = self.get_dsid() baseurl = "https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s" % ( url, dsid) if self.pch is None: self.pch = build_opener(HTTPCookieProcessor(self.cj)) if post: post = bytearray(post, "utf-8") request = ...
def login(self, user, passwd, bank): """ Login """ logger.info("login...") if bank not in self.BANKS: logger.error("Can't find that bank.") return False self.useragent = self.BANKS[bank]["u-a"] self.bankid = self.BANKS[bank]["id"] login = json.dumps( {"userId": user, "password": passwd, "useEasyLogin": False, "generate...
def accounts(self): """ Accounts """ logger.info("Fetching data...") try: self.request("engagement/overview") except HTTPError as e: error = json.loads(e.read().decode("utf8")) logger.error(error["errorMessages"]["general"][0]["message"]) return overview = json.loads(self.getdata()) overviewl = reversed(list(overview))...
def history(self): """ History """ logger.info("Transactions:") try: logger.debug("Account: %s", self.account) self.request("engagement/transactions/%s" % self.account) except HTTPError as e: error = json.loads(e.read().decode("utf8")) logger.error(error["errorMessages"]["general"][0]["message"]) return transactions = ...
def search_form(*fields, **kwargs): """ Construct a search form filter form using the fields provided as arguments to this function. By default a field will be created for each field passed and hidden field will be created for search. If you pass the key work argument `search_only` then only a visible search field will...
def get_filter_fields(self, exclude=None): """ Get the fields that are normal filter fields """ exclude_set = set(self.exclude) if exclude: exclude_set = exclude_set.union(set(exclude)) return [name for name in self.fields if name not in exclude_set]
def get_search_fields(self, exclude=None): """ Get the fields for searching for an item. """ exclude = set(exclude) if self.search_fields and len(self.search_fields) > 1: exclude = exclude.union(self.search_fields) return self.get_filter_fields(exclude=exclude)
def get_filter_kwargs(self): """ Translates the cleaned data into a dictionary that can used to generate the filter removing blank values. """ if self.is_valid(): filter_kwargs = {} for field in self.get_filter_fields(): empty_values = EMPTY_VALUES if hasattr(self.fields[field], 'empty_values'): empty_values = self.fie...
def get_filter(self): """ Returns a list of Q objects that is created by passing for the keyword arguments from `self.get_filter_kwargs`. If search_fields are specified and we received a seach query all search_fields will be queried use using OR (|) for that term and any specific terms for those search_fields will be i...
def jx_expression_to_function(expr): """ RETURN FUNCTION THAT REQUIRES PARAMETERS (row, rownum=None, rows=None): """ if is_expression(expr): if is_op(expr, ScriptOp) and not is_text(expr.script): return expr.script else: return compile_expression(Python[expr].to_python()) if ( expr != None and not is_data(expr) and not...
def make_proc_name(self, subtitle): """ 获取进程名称 :param subtitle: :return: """ proc_name = '[%s:%s %s] %s' % ( constants.NAME, subtitle, self.name, ' '.join([sys.executable] + sys.argv) ) return proc_name
def _validate_cmds(self): """ 确保 cmd 没有重复 :return: """ cmd_list = list(self.rule_map.keys()) for bp in self.blueprints: cmd_list.extend(bp.rule_map.keys()) duplicate_cmds = (Counter(cmd_list) - Counter(set(cmd_list))).keys() assert not duplicate_cmds, 'duplicate cmds: %s' % duplicate_cmds
def _init_groups(self): """ 初始化group数据 :return: """ for group_id, conf in self.group_conf.items(): self.parent_input_dict[group_id] = Queue(conf.get('input_max_size', 0)) self.parent_output_dict[group_id] = Queue(conf.get('output_max_size', 0))
def _spawn_poll_worker_result_thread(self): """ 启动获取worker数据的线程 """ for group_id in self.group_conf: thread = Thread(target=self._poll_worker_result, args=(group_id,)) thread.daemon = True thread.start()
def _spawn_fork_workers(self): """ 通过线程启动多个worker """ thread = Thread(target=self._fork_workers, args=()) thread.daemon = True thread.start()
def _poll_worker_result(self, group_id): """ 从队列里面获取worker的返回 """ while 1: try: msg = self.parent_input_dict[group_id].get() except KeyboardInterrupt: break except: logger.error('exc occur.', exc_info=True) break # 参考 http://twistedsphinx.funsize.net/projects/core/howto/threading.html reactor.callFromThread(self._handl...
def get_ranked_english(): ''' wikitionary has a list of ~40k English words, ranked by frequency of occurance in TV and movie transcripts. more details at: http://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/TV/2006/explanation the list is separated into pages of 1000 or 2000 terms each. * the first 10k words are s...
frequency. for url in urls: html, is_cached = wiki_download(url) if not is_cached: time.sleep(SLEEP_TIME) new_terms = parse_wiki_terms(html) ranked_terms.extend(new_terms) return ranked_terms
def wiki_download(url): ''' scrape friendly: sleep 20 seconds between each request, cache each result. ''' DOWNLOAD_TMPL = '../data/tv_and_movie_freqlist%s.html' freq_range = url[url.rindex('/')+1:] tmp_path = DOWNLOAD_TMPL % freq_range if os.path.exists(tmp_path): print('cached.......', url) with codecs.open(tmp_path,...
def parse_wiki_terms(doc): '''who needs an html parser. fragile hax, but checks the result at the end''' results = [] last3 = ['', '', ''] header = True for line in doc.split('\n'): last3.pop(0) last3.append(line.strip()) if all(s.startswith('<td>') and not s == '<td></td>' for s in last3): if header: header = False co...
def get_ranked_census_names(): ''' takes name lists from the the 2000 us census, prepares as a json array in order of frequency (most common names first). more info: http://www.census.gov/genealogy/www/data/2000surnames/index.html files in data are downloaded copies of: http://www.census.gov/genealogy/names/dist.all.la...
def filter_short(terms): ''' only keep if brute-force possibilities are greater than this word's rank in the dictionary ''' return [term for i, term in enumerate(terms) if 26**(len(term)) > i]
def filter_dup(lst, lists): ''' filters lst to only include terms that don't have lower rank in another list ''' max_rank = len(lst) + 1 dct = to_ranked_dict(lst) dicts = [to_ranked_dict(l) for l in lists] return [word for word in lst if all(dct[word] < dct2.get(word, max_rank) for dct2 in dicts)]
def filter_ascii(lst): ''' removes words with accent chars etc. (most accented words in the english lookup exist in the same table unaccented.) ''' return [word for word in lst if all(ord(c) < 128 for c in word)]
def __get_type(self, expectation, options): """ Determining the type of Matcher Return: string """ if "is_custom_func" in options.keys(): setattr(self, "mtest", expectation) return "CUSTOMFUNC" elif "is_substring" in options.keys(): return "SUBSTRING" elif "is_regex" in options.keys(): return "REGEX" elif isinstance(ex...
def __value_compare(self, target): """ Comparing result based on expectation if arg_type is "VALUE" Args: Anything Return: Boolean """ if self.expectation == "__ANY__": return True elif self.expectation == "__DEFINED__": return True if target is not None else False elif self.expectation == "__TYPE__": return True if ty...
def __get_match_result(self, ret, ret2): """ Getting match result """ if self.another_compare == "__MATCH_AND__": return ret and ret2 elif self.another_compare == "__MATCH_OR__": return ret or ret2 return ret
def typeOf(cls, expected_type): #pylint: disable=no-self-argument,invalid-name,no-self-use """ (*Type does NOT consider inherited class) Matcher.mtest(...) will return True if type(...) == expected_type Return: Matcher Raise: matcher_type_error """ if isinstance(expected_type, type): options = {} options["target_type"]...
def instanceOf(cls, expected_instance): #pylint: disable=no-self-argument,invalid-name,no-self-use """ (*Instance consider inherited class) Matcher.mtest(...) will return True if instance(...) == expected_instance Return: Matcher Raise: matcher_instance_error """ if not inspect.isclass(expected_instance): options = {} ...
def _sort(self, short_list, sorts): """ TAKE SHORTLIST, RETURN IT SORTED :param short_list: :param sorts: LIST OF SORTS TO PERFORM :return: """ sort_values = self._index_columns(sorts) # RECURSIVE SORTING output = [] def _sort_more(short_list, i, sorts): if len(sorts) == 0: output.extend(short_list) sort = sorts[0] ind...
def gather_xml(self): """Attempt to read the XML, whether from a file on-disk or via host:port. TODO: handle when you cant gather stats, due to bad hostname """ if self.xml_filepath: with open(self.xml_filepath, "r") as xml_fh: self.raw_xml = xml_fh.read() self.bs_xml = BeautifulSoup(self.raw_xml, 'lxml') else: try: re...
def get_stats(self): """Given XML version, parse create XMLAbstract object and sets xml_stats attribute.""" self.gather_xml() self.xml_version = self.bs_xml.find('statistics')['version'] if self.xml_version is None: raise XmlError("Unable to determine XML version via 'statistics' tag.") if self.xml_version == '3.6': se...
def median(values, simple=True, mean_weight=0.0): """ RETURN MEDIAN VALUE IF simple=False THEN IN THE EVENT MULTIPLE INSTANCES OF THE MEDIAN VALUE, THE MEDIAN IS INTERPOLATED BASED ON ITS POSITION IN THE MEDIAN RANGE mean_weight IS TO PICK A MEDIAN VALUE IN THE ODD CASE THAT IS CLOSER TO THE MEAN (PICK A MEDIAN BETWEEN...
1 while start_index > 0 and _sorted[start_index] == _median: start_index -= 1 start_index += 1 stop_index = middle + 1 while stop_index < l and _sorted[stop_index] == _median: stop_index += 1 num_middle = stop_index - start_index if l % 2 == 0: if num_middle == 1: return (_sorted[middle - 1] + _median) / 2 else: return...
def percentile(values, percent): """ PERCENTILE WITH INTERPOLATION RETURN VALUE AT, OR ABOVE, percentile OF THE VALUES snagged from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/ """ N = sorted(values) if not N: return None k = (len(N) - 1) * percent f = int(math.floor(k)) c = int(math...
def map(self, method: str, *args, _threaded: bool = True, **kwargs ) -> "AttrIndexedDict": "For all stored items, run a method they possess." work = lambda item: getattr(item, method)(*args, **kwargs) if _threaded: pool = ThreadPool(int(config.CFG["GENERAL"]["parallel_requests"])) try: pool.map(work, self.data.values()...
def put(self, *items) -> "AttrIndexedDict": "Add items to the dict that will be indexed by self.attr." for item in items: self.data[getattr(item, self.attr)] = item return self
def main(host, password, username): """Console script for tplink.""" client = tplink.TpLinkClient(password) devices = client.get_connected_devices() click.echo(json.dumps(devices, indent=4)) return 0
def do_login(self, line): "login aws-acces-key aws-secret" if line: args = self.getargs(line) self.connect(args[0], args[1]) else: self.connect() self.do_tables('')
def do_tables(self, line): "List tables" self.tables = self.conn.list_tables().get('TableNames') print "\nAvailable tables:" self.pprint(self.tables)
def do_describe(self, line): "describe [-c] {tablename}..." args = self.getargs(line) if '-c' in args: create_info = True args.remove('-c') else: create_info = False if not args: if self.table: args = [ self.table.table_name ] else: args = self.tables for table in args: desc = self.conn.describe_table(table) if create_...
def do_use(self, line): "use {tablename}" self.table = boto.dynamodb2.table.Table(line, connection=self.conn) self.pprint(self.table.describe()) self.prompt = "%s> " % self.table.table_name
def do_create(self, line): "create {tablename} [-c rc,wc] {hkey}[:{type} {rkey}:{type}]" args = self.getargs(line) rc = wc = 5 name = args.pop(0) # tablename if args[0] == "-c": # capacity args.pop(0) # skyp -c capacity = args.pop(0).strip() rc, _, wc = capacity.partition(",") rc = int(rc) wc = int(wc) if wc != "" else...
def do_refresh(self, line): "refresh {table_name}" table = self.get_table(line) while True: desc = table.describe() status = desc['Table']['TableStatus'] if status == 'ACTIVE': break else: print status, "..." time.sleep(5) print "" self.pprint(desc)
def do_capacity(self, line): "capacity [tablename] {read_units} {write_units}" table, line = self.get_table_params(line) args = self.getargs(line) read_units = int(args[0]) write_units = int(args[1]) desc = table.describe() prov = desc['Table']['ProvisionedThroughput'] current_read, current_write = prov['ReadCapacityUn...
print "%s: updating capacity to %d read units, %d write units" % (table.table_name, current_read, current_write) if not table.update({'read': current_read, 'write': current_write}): print "" print "update failed" print "" break else: print "" self.do_refresh(table.table_name) print ""
def do_put(self, line): "put [:tablename] [!fieldname:expectedvalue] {json-body} [{json-body}, {json-body}...]" table, line = self.get_table_params(line) expected, line = self.get_expected(line) if expected: print "expected: not yet implemented" return if line.startswith('(') or line.startswith('['): print "batch: not ...
def do_import(self, line): "import [:tablename] filename|list" table, line = self.get_table_params(line) if line[0] == '[': list = self.get_list(line) else: with open(line) as f: list = self.get_list(f.read()) items = 0 consumed = 0 for item in list: table.put_item(item) #consumed += item.consumed_units items += 1 prin...
def _todo_do_update(self, line): "update [:tablename] {hashkey[,rangekey]} [!fieldname:expectedvalue] [-add|-delete] [+ALL_OLD|ALL_NEW|UPDATED_OLD|UPDATED_NEW] {attributes}" table, line = self.get_table_params(line) hkey, line = line.split(" ", 1) expected, attr = self.get_expected(line) if attr[0] == '-': op, attr = a...
def do_get(self, line): """ get [:tablename] {haskkey} [rangekey] or get [:tablename] ((hkey,rkey), (hkey,rkey)...) """ table, line = self.get_table_params(line) if line.startswith('(') or line.startswith('[') or "," in line: print "batch: not yet implemented" return # list of IDs list = self.get_list(line) from collec...
"consumed units:", item.consumed_units
def do_scan(self, line): """ scan [:tablename] [--batch=#] [-{max}] [+filter_attribute=filter_value] [attributes,...] filter_attribute is either the field name to filter on or a field name with a conditional, as specified in boto's documentation, in the form of {name}__{conditional} where conditional is: eq (equal valu...
None cond = None while args: if args[0].startswith('+'): arg = args.pop(0) filter_name, filter_value = arg[1:].split('=', 1) if "__" not in filter_name: filter_name += "__eq" if filter_name.endswith("__null"): scan_filter[filter_name] = filter_value == "true" else: scan_filter[filter_name] = self.get_typed_value(filter...
arg[1:].isdigit(): max_size = int(arg[1:]) elif arg == '--': break else: print "invalid argument: %s" % arg break else: break attr_keys = args[0].split(",") if args else None attrs = list(set(attr_keys)) if attr_keys else None result = table.scan(limit=max_size, max_page_size=batch_size, attributes=attrs, conditional_o...
def do_rmall(self, line): "remove [tablename...] yes" args = self.getargs(line) if args and args[-1] == "yes": args.pop() if not args: args = [self.table.table_name] while args: table = boto.dynamodb2.table.Table(args.pop(0), connection=self.conn) print "from table " + table.table_name for item in table.scan(attributes...
def simulate(simulated_variables, year): ''' Construction de la DataFrame à partir de laquelle sera faite l'analyse des données ''' input_data_frame = get_input_data_frame(year) TaxBenefitSystem = openfisca_france_indirect_taxation.init_country() tax_benefit_system = TaxBenefitSystem() survey_scenario = SurveyScenario(...
def wavg(groupe, var): ''' Fonction qui calcule la moyenne pondérée par groupe d'une variable ''' d = groupe[var] w = groupe['pondmen'] return (d * w).sum() / w.sum()
def collapse(dataframe, groupe, var): ''' Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe. ''' grouped = dataframe.groupby([groupe]) var_weighted_grouped = grouped.apply(lambda x: wavg(groupe = x, var = var)) return var_weighted_grouped
def df_weighted_average_grouped(dataframe, groupe, varlist): ''' Agrège les résultats de weighted_average_grouped() en une unique dataframe pour la liste de variable 'varlist'. ''' return DataFrame( dict([ (var, collapse(dataframe, groupe, var)) for var in varlist ]) )
def flatten(value): """value can be any nesting of tuples, arrays, dicts. returns 1D numpy array and an unflatten function.""" if isinstance(value, np.ndarray): def unflatten(vector): return np.reshape(vector, value.shape) return np.ravel(value), unflatten elif isinstance(value, float): return np.array([value]), lambda...
unflatteners.append(cur_unflatten) lengths.append(len(cur_flattened)) keys.append(k) def unflatten(vector): split_ixs = np.cumsum(lengths) pieces = np.split(vector, split_ixs) return {key: unflattener(piece) for piece, unflattener, key in zip(pieces, unflatteners, keys)} return np.concatenate(flattened), unflatten else...
def switch_state(request): """ Switch the default version state in the session. """ if request.session.get(SESSION_KEY): request.session[SESSION_KEY] = False else: request.session[SESSION_KEY] = True # Get redirect location # Don't go to non local paths url = request.GET.get('redirect_to', '/') if url.startswith('http'...
def get_db_prep_value(self, value, connection, prepared=False): """Convert JSON object to a string""" if isinstance(value, basestring): return value return json.dumps(value, **self.dump_kwargs)
def _CollectHistory_(lookupType, fromVal, toVal, using={}, pattern=''): """ Return a dictionary detailing what, if any, change was made to a record field :param string lookupType: what cleaning rule made the change; one of: genericLookup, genericRegex, fieldSpecificLookup, fieldSpecificRegex, normLookup, normRegex, nor...
histObj
def _CollectHistoryAgg_(contactHist, fieldHistObj, fieldName): """ Return updated history dictionary with new field change :param dict contactHist: Existing contact history dictionary :param dict fieldHistObj: Output of _CollectHistory_ :param string fieldName: field name """ if fieldHistObj!={}: if fieldName not in co...