signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def auth_edit(method):
def wrapper(self, *args, **kwargs):<EOL><INDENT>'''<STR_LIT>'''<EOL>if self.current_user:<EOL><INDENT>if is_prived(self.userinfo.role, ROLE_CFG['<STR_LIT>']):<EOL><INDENT>return method(self, *args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>kwd = {<EOL>'<STR_LIT:info>': '<STR_LIT>',<EOL>}<EOL>self.render('<STR_LIT>',<EOL>...
role for edit.
f10090:m3
def auth_delete(method):
def wrapper(self, *args, **kwargs):<EOL><INDENT>'''<STR_LIT>'''<EOL>if self.current_user:<EOL><INDENT>if is_prived(self.userinfo.role, ROLE_CFG['<STR_LIT>']):<EOL><INDENT>return method(self, *args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>kwd = {<EOL>'<STR_LIT:info>': '<STR_LIT>',<EOL>}<EOL>self.render('<STR_LIT>',<EOL>...
role for delete.
f10090:m4
def auth_admin(method):
def wrapper(self, *args, **kwargs):<EOL><INDENT>'''<STR_LIT>'''<EOL>if self.current_user:<EOL><INDENT>if is_prived(self.userinfo.role, ROLE_CFG['<STR_LIT>']):<EOL><INDENT>return method(self, *args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>kwd = {<EOL>'<STR_LIT:info>': '<STR_LIT>',<EOL>}<EOL>self.render('<STR_LIT>',<EOL>...
role for admin.
f10090:m5
def deprecated(deprecated_in=None, removed_in=None, current_version=None, details="<STR_LIT>"):
<EOL>if deprecated_in is None and removed_in is not None:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>is_deprecated = False<EOL>is_unsupported = False<EOL>if current_version:<EOL><INDENT>current_version = version.StrictVersion(current_version)<EOL>if removed_in and current_version >= version.St...
Decorate a function to signify its deprecation This function wraps a method that will soon be removed and does two things: * The docstring of the method will be modified to include a notice about deprecation, e.g., "Deprecated since 0.9.11. Use foo instead." * Raises a :class:`~deprecatio...
f10091:m0
def fail_if_not_removed(method):
def _inner(*args, **kwargs):<EOL><INDENT>with warnings.catch_warnings(record=True) as caught_warnings:<EOL><INDENT>warnings.simplefilter("<STR_LIT>")<EOL>rval = method(*args, **kwargs)<EOL><DEDENT>for warning in caught_warnings:<EOL><INDENT>if warning.category == UnsupportedWarning:<EOL><INDENT>raise AssertionError(<EO...
Decorate a test method to track removal of deprecated code This decorator catches :class:`~deprecation.UnsupportedWarning` warnings that occur during testing and causes unittests to fail, making it easier to keep track of when code should be removed. :raises: :class:`AssertionError` if an ...
f10091:m1
def send_mail(to_list, sub, content, cc=None):
sender = SMTP_CFG['<STR_LIT:name>'] + "<STR_LIT:<>" + SMTP_CFG['<STR_LIT:user>'] + "<STR_LIT:>>"<EOL>msg = MIMEText(content, _subtype='<STR_LIT:html>', _charset='<STR_LIT:utf-8>')<EOL>msg['<STR_LIT>'] = sub<EOL>msg['<STR_LIT>'] = sender<EOL>msg['<STR_LIT>'] = "<STR_LIT:;>".join(to_list)<EOL>if cc:<EOL><INDENT>msg['<STR...
Sending email via Python.
f10095:m0
def do_for_app(writer, rand=True, kind='<STR_LIT>', doc_type=None):
if doc_type is None:<EOL><INDENT>doc_type = {}<EOL><DEDENT>if rand:<EOL><INDENT>recs = MPost.query_random(num=<NUM_LIT:10>, kind=kind)<EOL><DEDENT>else:<EOL><INDENT>recs = MPost.query_recent(num=<NUM_LIT:2>, kind=kind)<EOL><DEDENT>for rec in recs:<EOL><INDENT>text2 = rec.title + '<STR_LIT:U+002C>' + html2text.html2text...
生成whoosh,根据配置文件中类别。
f10096:m0
def gen_whoosh_database(kind_arr, post_type):
SITE_CFG['<STR_LIT>'] = SITE_CFG.get('<STR_LIT>', '<STR_LIT>')<EOL>if SITE_CFG['<STR_LIT>'] == '<STR_LIT>' and ChineseAnalyzer:<EOL><INDENT>schema = Schema(title=TEXT(stored=True, analyzer=ChineseAnalyzer()),<EOL>catid=TEXT(stored=True),<EOL>type=TEXT(stored=True),<EOL>link=ID(unique=True, stored=True),<EOL>content=TEX...
kind_arr, define the `type` except Post, Page, Wiki post_type, define the templates for different kind.
f10096:m4
def run():
gen_whoosh_database(kind_arr=kind_arr, post_type=post_type)<EOL>
Run it.
f10096:m5
def render(self, *args, **kwargs):
uid_with_str = args[<NUM_LIT:0>]<EOL>slug = kwargs.get('<STR_LIT>', False)<EOL>with_title = kwargs.get('<STR_LIT>', False)<EOL>glyph = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>kwd = {<EOL>'<STR_LIT>': glyph<EOL>}<EOL>curinfo = MCategory.get_by_uid(uid_with_str)<EOL>sub_cats = MCategory.query_sub_cat(uid_with_str)<EOL>i...
fun(uid_with_str) fun(uid_with_str, slug = val1, glyph = val2)
f10098:c0:m0
def render(self, *args, **kwargs):
user_name = kwargs.get('<STR_LIT>', args[<NUM_LIT:0>])<EOL>kind = kwargs.get('<STR_LIT>', args[<NUM_LIT:1>])<EOL>num = kwargs.get('<STR_LIT>', args[<NUM_LIT:2>] if len(args) > <NUM_LIT:2> else <NUM_LIT:6>)<EOL>with_tag = kwargs.get('<STR_LIT>', False)<EOL>glyph = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>all_cats = MUsa...
fun(user_name, kind) fun(user_name, kind, num) fun(user_name, kind, num, with_tag = val1, glyph = val2) fun(user_name = vala, kind = valb, num = valc, with_tag = val1, glyph = val2)
f10098:c1:m0
def render_it(self, *args, **kwargs):
kind = kwargs.get('<STR_LIT>', args[<NUM_LIT:0>])<EOL>num = kwargs.get('<STR_LIT>', args[<NUM_LIT:1>] if len(args) > <NUM_LIT:1> else <NUM_LIT:6>)<EOL>with_tag = kwargs.get('<STR_LIT>', False)<EOL>glyph = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>all_cats = MPost.query_most(kind=kind, num=num).objects()<EOL>kwd = {<EOL>...
Render without userinfo. fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, glyph = val2)
f10098:c2:m1
def render_user(self, *args, **kwargs):
kind = kwargs.get('<STR_LIT>', args[<NUM_LIT:0>])<EOL>num = kwargs.get('<STR_LIT>', args[<NUM_LIT:1>] if len(args) > <NUM_LIT:1> else <NUM_LIT:6>)<EOL>with_tag = kwargs.get('<STR_LIT>', False)<EOL>user_id = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>glyph = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>all_cats = MUsage.query...
Render user. fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, user_id = val2) fun(kind, num, with_tag = val1, user_id = val2, glyph = val3)
f10098:c2:m2
def render_it(self, kind, num, with_tag=False, glyph='<STR_LIT>'):
all_cats = MPost.query_recent(num, kind=kind)<EOL>kwd = {<EOL>'<STR_LIT>': with_tag,<EOL>'<STR_LIT>': router_post[kind],<EOL>'<STR_LIT>': glyph<EOL>}<EOL>return self.render_string('<STR_LIT>',<EOL>recs=all_cats,<EOL>kwd=kwd)<EOL>
render, no user logged in
f10098:c3:m1
def render_user(self, *args, **kwargs):
kind = kwargs.get('<STR_LIT>', args[<NUM_LIT:0>])<EOL>num = kwargs.get('<STR_LIT>', args[<NUM_LIT:1>] if len(args) > <NUM_LIT:1> else <NUM_LIT:6>)<EOL>with_tag = kwargs.get('<STR_LIT>', False)<EOL>user_id = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>glyph = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>logger.info(<EOL>'<STR_...
render, with userinfo fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, user_id = val2) fun(kind, num, with_tag = val1, user_id = val2, glyph = val3)
f10098:c3:m2
def gen_xlsx_table():
XLSX_FILE = '<STR_LIT>'<EOL>if os.path.exists(XLSX_FILE):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>fields = []<EOL>for sheet_ranges in load_workbook(filename=XLSX_FILE):<EOL><INDENT>for xr in FILTER_COLUMNS:<EOL><INDENT>row1_val = sheet_ranges[xr + "<STR_LIT:1>"].value<EOL>row2_val = sheet_rang...
excel中的数据作为表中的字段,创建表
f10103:m0
def run_init(*args):
gen_xlsx_table()<EOL>gen_xlsx_table_info()<EOL>
running init.
f10104:m0
def entry(argv):
command_dic = {<EOL>'<STR_LIT>': run_init,<EOL>}<EOL>try:<EOL><INDENT>opts, args = getopt.getopt(argv, "<STR_LIT>")<EOL><DEDENT>except getopt.GetoptError:<EOL><INDENT>print('<STR_LIT>')<EOL>sys.exit(<NUM_LIT:2>)<EOL><DEDENT>for opt, arg in opts:<EOL><INDENT>if opt == "<STR_LIT>":<EOL><INDENT>print('<STR_LIT>')<EOL>prin...
Command entry
f10105:m0
def build_dir():
tag_arr = ['<STR_LIT>', '<STR_LIT:list>', '<STR_LIT>']<EOL>path_arr = [os.path.join(CRUD_PATH, x) for x in tag_arr]<EOL>for wpath in path_arr:<EOL><INDENT>if os.path.exists(wpath):<EOL><INDENT>continue<EOL><DEDENT>os.makedirs(wpath)<EOL><DEDENT>
Build the directory used for templates.
f10106:m0
def __write_filter_dic(wk_sheet, column):
row1_val = wk_sheet['<STR_LIT>'.format(column)].value<EOL>row2_val = wk_sheet['<STR_LIT>'.format(column)].value<EOL>row3_val = wk_sheet['<STR_LIT>'.format(column)].value<EOL>row4_val = wk_sheet['<STR_LIT>'.format(column)].value<EOL>if row1_val and row1_val.strip() != '<STR_LIT>':<EOL><INDENT>row2_val = row2_val.strip()...
return filter dic for certain column
f10107:m0
def gen_html_dic():
if WORK_BOOK:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>html_dics = {}<EOL>for wk_sheet in WORK_BOOK:<EOL><INDENT>for column in FILTER_COLUMNS:<EOL><INDENT>kkey, kval = __write_filter_dic(wk_sheet, column)<EOL>if kkey:<EOL><INDENT>html_dics[kkey] = kval<EOL><DEDENT><DEDENT><DEDENT>return h...
生成 Filter .
f10107:m1
def gen_input_view(sig_dic):
html_str = HTML_TPL_DICT['<STR_LIT>'].format(<EOL>sig_dic['<STR_LIT>'],<EOL>sig_dic['<STR_LIT>'],<EOL>sig_dic['<STR_LIT>'][<NUM_LIT:1>],<EOL>)<EOL>return html_str<EOL>
Viewing the HTML text.
f10108:m0
def gen_radio_view(sig_dic):
view_zuoxiang = '''<STR_LIT>'''.format(sig_dic['<STR_LIT>'])<EOL>dic_tmp = sig_dic['<STR_LIT>']<EOL>for key in dic_tmp.keys():<EOL><INDENT>tmp_str = '''<STR_LIT>'''.format(sig_dic['<STR_LIT>'], key, dic_tmp[key])<EOL>view_zuoxiang += tmp_str<EOL><DEDENT>view_zuoxiang += '''<STR_LIT>'''<EOL>return view_zuoxiang<EOL>
for checkbox
f10108:m1
def gen_checkbox_view(sig_dic):
view_zuoxiang = '''<STR_LIT>'''.format(sig_dic['<STR_LIT>'])<EOL>dic_tmp = sig_dic['<STR_LIT>']<EOL>for key in dic_tmp.keys():<EOL><INDENT>tmp_str = '''<STR_LIT>'''.format(key, sig_dic['<STR_LIT>'], dic_tmp[key])<EOL>view_zuoxiang += tmp_str<EOL><DEDENT>view_zuoxiang += '''<STR_LIT>'''<EOL>return view_zuoxiang<EOL>
for checkbox
f10108:m2
def gen_select_view(sig_dic):
option_str = '<STR_LIT>'<EOL>dic_tmp = sig_dic['<STR_LIT>']<EOL>for key, val in dic_tmp.items():<EOL><INDENT>tmp_str = '''<STR_LIT>'''.format(sig_en=sig_dic['<STR_LIT>'], sig_key=key, sig_dic=val)<EOL>option_str += tmp_str<EOL><DEDENT>return '''<STR_LIT>'''.format(sig_zh=sig_dic['<STR_LIT>'], option_str=option_str)<EOL...
HTML view, for selection.
f10108:m3
def gen_file_view(sig_dic):
_ = sig_dic<EOL>view_html = '<STR_LIT>'<EOL>return view_html<EOL>
for file viewing.
f10108:m4
def gen_input_list(sig_dic):
out_str = '''<STR_LIT>'''.format(sig_dic['<STR_LIT>'], sig_dic['<STR_LIT>'], sig_dic['<STR_LIT>'][<NUM_LIT:1>])<EOL>return out_str<EOL>
For generating List view HTML file for INPUT. for each item.
f10108:m5
def gen_radio_list(sig_dic):
view_zuoxiang = '''<STR_LIT>'''<EOL>dic_tmp = sig_dic['<STR_LIT>']<EOL>for key in dic_tmp.keys():<EOL><INDENT>tmp_str = '''<STR_LIT>'''.format(sig_dic['<STR_LIT>'], key, dic_tmp[key])<EOL>view_zuoxiang += tmp_str<EOL><DEDENT>view_zuoxiang += '''<STR_LIT>'''<EOL>return view_zuoxiang<EOL>
For generating List view HTML file for RADIO. for each item.
f10108:m6
def gen_checkbox_list(sig_dic):
view_zuoxiang = '''<STR_LIT>'''<EOL>dic_tmp = sig_dic['<STR_LIT>']<EOL>for key in dic_tmp.keys():<EOL><INDENT>tmp_str = '''<STR_LIT>'''.format(key, sig_dic['<STR_LIT>'], dic_tmp[key])<EOL>view_zuoxiang += tmp_str<EOL><DEDENT>view_zuoxiang += '''<STR_LIT>'''<EOL>return view_zuoxiang<EOL>
For generating List view HTML file for CHECKBOX. for each item.
f10108:m7
def gen_select_list(sig_dic):
view_jushi = '''<STR_LIT>'''<EOL>dic_tmp = sig_dic['<STR_LIT>']<EOL>for key in dic_tmp.keys():<EOL><INDENT>tmp_str = '''<STR_LIT>'''.format(sig_dic['<STR_LIT>'], key, dic_tmp[key])<EOL>view_jushi += tmp_str<EOL><DEDENT>view_jushi += '''<STR_LIT>'''<EOL>return view_jushi<EOL>
For generating List view HTML file for SELECT. for each item.
f10108:m8
def minify(the_str):
return the_str<EOL>
Redefine the function for it is htmlmin. For it not work fine for Tornado template.
f10109:m0
def __gen_select_filter(bl_str):
bianliang = HTML_DICS[bl_str]<EOL>html_out = '''<STR_LIT>'''.format(bianliang['<STR_LIT>'], '<STR_LIT:_>'.join(bl_str.split('<STR_LIT:_>')[<NUM_LIT:1>:]))<EOL>tmp_dic = bianliang['<STR_LIT>']<EOL>for key in tmp_dic.keys():<EOL><INDENT>tmp_str = '''<STR_LIT>'''.format('<STR_LIT:_>'.join(bl_str.split('<STR_LIT:_>')[<NUM_...
Convert to html. :return String.
f10109:m1
def generate_html_files(*args):
_ = args<EOL>for tag_key, tag_list in SWITCH_DICS.items():<EOL><INDENT>if tag_key.startswith('<STR_LIT>'):<EOL><INDENT>__write_view_tmpl(tag_list)<EOL><DEDENT><DEDENT>__write_filter_tmpl(TPL_LIST)<EOL>__write_list_tmpl(TPL_LISTINFO)<EOL>
Generate the templates for adding, editing, viewing. :return: None
f10109:m2
def __write_view_tmpl(tag_list):
view_file = os.path.join(OUT_DIR, '<STR_LIT>', '<STR_LIT>')<EOL>view_widget_arr = []<EOL>for sig in tag_list:<EOL><INDENT>html_sig = '<STR_LIT:_>'.join(['<STR_LIT:html>', sig])<EOL>var_html = HTML_DICS[html_sig]<EOL>if var_html['<STR_LIT:type>'] in INPUT_ARR:<EOL><INDENT>tmpl = func_gen_html.gen_input_view(var_html)<EO...
Generate the HTML file for viewing. :param tag_key: key of the tags. :param tag_list: list of the tags. :return: None
f10109:m3
def __write_filter_tmpl(html_tpl):
out_dir = os.path.join(os.getcwd(), CRUD_PATH, '<STR_LIT:list>')<EOL>if os.path.exists(out_dir):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>os.mkdir(out_dir)<EOL><DEDENT>for var_name, bl_val in SWITCH_DICS.items():<EOL><INDENT>if var_name.startswith('<STR_LIT>'):<EOL><INDENT>subdir = '<STR_LIT>'<EOL>outfile = os.pa...
doing for directory.
f10109:m4
def __write_list_tmpl(html_tpl):
out_dir = os.path.join(os.getcwd(), CRUD_PATH, '<STR_LIT>')<EOL>if os.path.exists(out_dir):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>os.mkdir(out_dir)<EOL><DEDENT>for var_name, bl_val in SWITCH_DICS.items():<EOL><INDENT>if var_name.startswith('<STR_LIT>'):<EOL><INDENT>outfile = os.path.join(out_dir, '<STR_LIT>')<...
doing for directory.
f10109:m5
def gen_xlsx_table_info():
XLSX_FILE = '<STR_LIT>'<EOL>if os.path.exists(XLSX_FILE):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>RAW_LIST = ['<STR_LIT:A>', '<STR_LIT:B>', '<STR_LIT:C>', '<STR_LIT:D>', '<STR_LIT:E>', '<STR_LIT:F>', '<STR_LIT>', '<STR_LIT:H>', '<STR_LIT:I>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:L>', '<STR_LIT:...
向表中插入数据
f10111:m0
def stable_hash(obj):
return _recursive_stable_hash(obj)<EOL>
Computes a cross-kernel stable hash value for the given object. The supported data structure are the built-in list, tuple and dict types. Any included tuple or list, whether outer or nested, may only contain values of the following built-in types: bool, int, float, complex, str, list, tuple and dict. ...
f10118:m2
def json_based_stable_hash(obj):
encoded_str = json.dumps(<EOL>obj=obj,<EOL>skipkeys=False,<EOL>ensure_ascii=False,<EOL>check_circular=True,<EOL>allow_nan=True,<EOL>cls=None,<EOL>indent=<NUM_LIT:0>,<EOL>separators=('<STR_LIT:U+002C>', '<STR_LIT::>'),<EOL>default=None,<EOL>sort_keys=True,<EOL>).encode('<STR_LIT:utf-8>')<EOL>return hashlib.sha256(encode...
Computes a cross-kernel stable hash value for the given object. The supported data structure are the built-in list, tuple and dict types. Any included tuple or list, whether outer or nested, may only contain values of the following built-in types: bool, int, float, complex, str, list, tuple and dict. ...
f10118:m3
def get_priority_elem_in_set(obj_set, priority_list):
for obj in priority_list:<EOL><INDENT>if obj in obj_set:<EOL><INDENT>return obj<EOL><DEDENT><DEDENT>return None<EOL>
Returns the highest priority element in a set. The set will be searched for objects in the order they appear in the priority list, and the first one to be found will be returned. None is returned if no such object is found. Parameters --------- obj_set : set, list A set or list of obje...
f10119:m0
def find_point_in_section_list(point, section_list):
if point < section_list[<NUM_LIT:0>] or point > section_list[-<NUM_LIT:1>]:<EOL><INDENT>return None<EOL><DEDENT>if point in section_list:<EOL><INDENT>if point == section_list[-<NUM_LIT:1>]:<EOL><INDENT>return section_list[-<NUM_LIT:2>]<EOL><DEDENT>ind = section_list.bisect(point)-<NUM_LIT:1><EOL>if ind == <NUM_LIT:0>:<...
Returns the start of the section the given point belongs to. The given list is assumed to contain start points of consecutive sections, except for the final point, assumed to be the end point of the last section. For example, the list [5, 8, 30, 31] is interpreted as the following list of sections: [5-...
f10122:m0
def find_range_ix_in_section_list(start, end, section_list):
if start > section_list[-<NUM_LIT:1>] or end < section_list[<NUM_LIT:0>]:<EOL><INDENT>return [<NUM_LIT:0>, <NUM_LIT:0>]<EOL><DEDENT>if start < section_list[<NUM_LIT:0>]:<EOL><INDENT>start_section = section_list[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>start_section = find_point_in_section_list(start, section_list)<EO...
Returns the index range all sections belonging to the given range. The given list is assumed to contain start points of consecutive sections, except for the final point, assumed to be the end point of the last section. For example, the list [5, 8, 30, 31] is interpreted as the following list of section...
f10122:m1
def find_range_in_section_list(start, end, section_list):
ind = find_range_ix_in_section_list(start, end, section_list)<EOL>return section_list[ind[<NUM_LIT:0>]: ind[<NUM_LIT:1>]]<EOL>
Returns all sections belonging to the given range. The given list is assumed to contain start points of consecutive sections, except for the final point, assumed to be the end point of the last section. For example, the list [5, 8, 30, 31] is interpreted as the following list of sections: [5-8), [8-30)...
f10122:m2
def find_range_ix_in_point_list(start, end, point_list):
return [point_list.bisect_left(start), point_list.bisect_right(end)]<EOL>
Returns the index range all points inside the given range. Parameters --------- start : float The start of the desired range. end : float The end of the desired range. point_list : sortedcontainers.SortedList A list of points. Returns ------- iterable Th...
f10122:m3
def get_keywords():
<EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>git_date = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full, "<STR_LIT:date>": git_date}<EOL>return keywords<EOL>
Get the keywords needed to look up the version information.
f10123:m0
def get_config():
<EOL>cfg = VersioneerConfig()<EOL>cfg.VCS = "<STR_LIT>"<EOL>cfg.style = "<STR_LIT>"<EOL>cfg.tag_prefix = "<STR_LIT:v>"<EOL>cfg.parentdir_prefix = "<STR_LIT>"<EOL>cfg.versionfile_source = "<STR_LIT>"<EOL>cfg.verbose = False<EOL>return cfg<EOL>
Create, populate and return the VersioneerConfig() object.
f10123:m1
def register_vcs_handler(vcs, method):
def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>
Decorator to mark a method as the handler for a particular VCS.
f10123:m2
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,<EOL>env=None):
assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, env=env,<EOL>stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><I...
Call the given command(s).
f10123:m3
def versions_from_parentdir(parentdir_prefix, root, verbose):
rootdirs = []<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>dirname = os.path.basename(root)<EOL>if dirname.startswith(parentdir_prefix):<EOL><INDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None, "<STR_LIT:date>": None}<EOL><DEDENT>e...
Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory
f10123:m4
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_get_keywords(versionfile_abs):
<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().sta...
Extract version information from the given file.
f10123:m5
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT...
Get version information from git keywords.
f10123:m6
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotTh...
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
f10123:m7
def plus_or_dot(pieces):
if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>
Return a + if we don't already have one, else return a .
f10123:m8
def render_pep440(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><...
Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
f10123:m9
def render_pep440_pre(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE
f10123:m10
def render_pep440_post(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces...
TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]
f10123:m11
def render_pep440_old(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<...
TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0]
f10123:m12
def render_git_describe(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL...
TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f10123:m13
def render_git_describe_long(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f10123:m14
def render(pieces, style):
if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>" <E...
Render the given version pieces into the requested style.
f10123:m15
def get_versions():
<EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>')...
Get version information or return default if unable to do so.
f10123:m16
def get_first_val(key_tuple, dict_obj):
for key in key_tuple:<EOL><INDENT>try:<EOL><INDENT>return dict_obj[key]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>raise KeyError('<STR_LIT>')<EOL>
Return the first value mapped by a key in the given tuple. Parameters ---------- key_tuple : tuple The keys to use for extraction, in order. dict_obj : dict The dict to extract from. Returns ------- value : object The extracted value, if exists. Otherwise, raises Ke...
f10125:m0
def any_in_dict(key_tuple, dict_obj):
return any([key in dict_obj for key in key_tuple])<EOL>
Return whether any of the given keys is in the given dict. Parameters ---------- key_tuple : tuple The keys for which to check inclusion. dict_obj : dict The dict to examine. Returns ------- bool True if any of the given keys is in the given dict. False otherwise. ...
f10125:m1
def get_nested_val(key_tuple, dict_obj):
if len(key_tuple) == <NUM_LIT:1>:<EOL><INDENT>return dict_obj[key_tuple[<NUM_LIT:0>]]<EOL><DEDENT>return get_nested_val(key_tuple[<NUM_LIT:1>:], dict_obj[key_tuple[<NUM_LIT:0>]])<EOL>
Return a value from nested dicts by the order of the given keys tuple. Parameters ---------- key_tuple : tuple The keys to use for extraction, in order. dict_obj : dict The outer-most dict to extract from. Returns ------- value : object The extracted value, if exist...
f10125:m2
def safe_nested_val(key_tuple, dict_obj, default_value=None):
try:<EOL><INDENT>return get_nested_val(key_tuple, dict_obj)<EOL><DEDENT>except (KeyError, IndexError, TypeError):<EOL><INDENT>return default_value<EOL><DEDENT>
Return a value from nested dicts by the order of the given keys tuple. Parameters ---------- key_tuple : tuple The keys to use for extraction, in order. dict_obj : dict The outer-most dict to extract from. default_value : object, default None The value to return when no matc...
f10125:m3
def put_nested_val(dict_obj, key_tuple, value):
current_dict = dict_obj<EOL>for key in key_tuple[:-<NUM_LIT:1>]:<EOL><INDENT>try:<EOL><INDENT>current_dict = current_dict[key]<EOL><DEDENT>except KeyError:<EOL><INDENT>current_dict[key] = {}<EOL>current_dict = current_dict[key]<EOL><DEDENT><DEDENT>current_dict[key_tuple[-<NUM_LIT:1>]] = value<EOL>
Put a value into nested dicts by the order of the given keys tuple. Any missing intermediate dicts are created. Parameters ---------- dict_obj : dict The outer-most dict to put in. key_tuple : tuple The keys to use for putting, in order. value : object The value to put....
f10125:m4
def in_nested_dicts(key_tuple, dict_obj):
return safe_nested_val(key_tuple, dict_obj) is not None<EOL>
Indicated whether a value is nested in nested dicts by a keys tuple. Parameters ----------- key_tuple : tuple The keys to use for examination, in order. dict_obj : dict The outer-most dict to examine from. Returns ------- True : object If some value if nested in the...
f10125:m5
def get_alternative_nested_val(key_tuple, dict_obj):
<EOL>top_keys = key_tuple[<NUM_LIT:0>] if isinstance(key_tuple[<NUM_LIT:0>], (list, tuple)) else [<EOL>key_tuple[<NUM_LIT:0>]]<EOL>for key in top_keys:<EOL><INDENT>try:<EOL><INDENT>if len(key_tuple) < <NUM_LIT:2>:<EOL><INDENT>return dict_obj[key]<EOL><DEDENT>return get_alternative_nested_val(key_tuple[<NUM_LIT:1>:], di...
Return a value from nested dicts by any path in the given keys tuple. Parameters --------- key_tuple : tuple Describe all possible paths for extraction. dict_obj : dict The outer-most dict to extract from. Returns ------- value : object The extracted value, if exist...
f10125:m6
def safe_alternative_nested_val(key_tuple, dict_obj, default_value=None):
try:<EOL><INDENT>return get_alternative_nested_val(key_tuple, dict_obj)<EOL><DEDENT>except KeyError:<EOL><INDENT>return default_value<EOL><DEDENT>
Return a value from nested dicts by any path in the given keys tuple. Parameters ---------- key_tuple : tuple Describe all possible paths for extraction. dict_obj : dict The outer-most dict to extract from. default_value : object, default None The value to return when no mat...
f10125:m7
def any_path_in_dict(key_tuple, dict_obj):
return safe_alternative_nested_val(key_tuple, dict_obj) is not None<EOL>
Indicated whether any path in the given keys tuple is in a dict. Parameters ---------- key_tuple : tuple Describe all possible paths for examination. dict_obj : dict The outer-most dict to examine from. Returns ------- bool True if any path in the given keys tuple i...
f10125:m8
def subdict_by_keys(dict_obj, keys):
return {k: dict_obj[k] for k in set(keys).intersection(dict_obj.keys())}<EOL>
Returns a sub-dict composed solely of the given keys. Parameters ---------- dict_obj : dict The dict to create a sub-dict from. keys : list of str The keys to keep in the sub-dict. Keys not present in the given dict will be ignored. Returns ------- dict A su...
f10125:m9
def increment_dict_val(dict_obj, key, value, zero_value=<NUM_LIT:0>):
dict_obj[key] = dict_obj.get(key, zero_value) + value<EOL>
Increments the value mapped by the given key by the given val. If the key is missing from the dict, the given mapping is added. Parameters ---------- dict_obj : dict The dict to increment a value in. key : object The key whose value is to be incremented. value : object T...
f10125:m10
def increment_nested_val(dict_obj, key_tuple, value, zero_value=<NUM_LIT:0>):
inc_val = value + safe_nested_val(<EOL>key_tuple=key_tuple,<EOL>dict_obj=dict_obj,<EOL>default_value=zero_value,<EOL>)<EOL>put_nested_val(<EOL>dict_obj=dict_obj,<EOL>key_tuple=key_tuple,<EOL>value=inc_val,<EOL>)<EOL>
Increments the value mapped by the given key by the given val. If the key is missing from the dict, the given mapping is added. Parameters ---------- dict_obj : dict The outer-most dict to increment a value in. key_tuple : tuple The keys mapping to the nested value to increment, in ...
f10125:m11
def add_to_dict_val_set(dict_obj, key, val):
try:<EOL><INDENT>dict_obj[key].add(val)<EOL><DEDENT>except KeyError:<EOL><INDENT>dict_obj[key] = set([val])<EOL><DEDENT>
Adds the given val to the set mapped by the given key. If the key is missing from the dict, the given mapping is added. Example ------- >>> dict_obj = {'a': set([1, 2])} >>> add_to_dict_val_set(dict_obj, 'a', 2) >>> print(dict_obj['a']) {1, 2} >>> add_to_dict_val_set(dict_obj, 'a', 3) ...
f10125:m12
def add_many_to_dict_val_set(dict_obj, key, val_list):
try:<EOL><INDENT>dict_obj[key].update(val_list)<EOL><DEDENT>except KeyError:<EOL><INDENT>dict_obj[key] = set(val_list)<EOL><DEDENT>
Adds the given value list to the set mapped by the given key. If the key is missing from the dict, the given mapping is added. Example ------- >>> dict_obj = {'a': set([1, 2])} >>> add_many_to_dict_val_set(dict_obj, 'a', [2, 3]) >>> print(dict_obj['a']) {1, 2, 3} >>> add_many_to_dict_va...
f10125:m13
def add_many_to_dict_val_list(dict_obj, key, val_list):
try:<EOL><INDENT>dict_obj[key].extend(val_list)<EOL><DEDENT>except KeyError:<EOL><INDENT>dict_obj[key] = list(val_list)<EOL><DEDENT>
Adds the given value list to the list mapped by the given key. If the key is missing from the dict, the given mapping is added. Example ------- >>> dict_obj = {'a': [1, 2]} >>> add_many_to_dict_val_list(dict_obj, 'a', [2, 3]) >>> print(dict_obj['a']) [1, 2, 2, 3] >>> add_many_to_dict_va...
f10125:m14
def get_key_of_max(dict_obj):
return max(<EOL>dict_obj, key=lambda key: dict_obj[key])<EOL>
Returns the key that maps to the maximal value in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1} >>> print(get_key_of_max(dict_obj)) a
f10125:m15
def get_keys_of_max_n(dict_obj, n):
return sorted([<EOL>item[<NUM_LIT:0>]<EOL>for item in sorted(<EOL>dict_obj.items(), key=lambda item: item[<NUM_LIT:1>], reverse=True<EOL>)[:n]<EOL>])<EOL>
Returns the keys that maps to the top n max values in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1, 'c':5} >>> get_keys_of_max_n(dict_obj, 2) ['a', 'c']
f10125:m16
def get_key_of_min(dict_obj):
return min(<EOL>dict_obj, key=lambda key: dict_obj[key])<EOL>
Returns the key that maps to the minimal value in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1} >>> print(get_key_of_min(dict_obj)) b
f10125:m17
def get_key_val_of_max(dict_obj):
return max(dict_obj.items(), key=lambda item: item[<NUM_LIT:1>])<EOL>
Returns the key-value pair with maximal value in the given dict. Example: -------- >>> dict_obj = {'a':2, 'b':1} >>> print(get_key_val_of_max(dict_obj)) ('a', 2)
f10125:m18
def get_key_val_of_max_key(dict_obj):
return max(dict_obj.items(), key=lambda item: item[<NUM_LIT:0>])<EOL>
Returns the key-value pair with the largest key in the given dict. Example: -------- >>> dict_obj = {5: 'g', 3: 'z'} >>> print(get_key_val_of_max_key(dict_obj)) (5, 'g')
f10125:m19
def unite_dicts(*args):
return dict(i for dct in args for i in dct.items())<EOL>
Unites the given dicts into a single dict mapping each key to the latest value it was mapped to in the order the dicts were given. Parameters --------- *args : positional arguments, each of type dict The dicts to unite. Returns ------- dict A dict where each key is mapped t...
f10125:m20
def deep_merge_dict(base, priority):
if not isinstance(base, dict) or not isinstance(priority, dict):<EOL><INDENT>return priority<EOL><DEDENT>result = copy.deepcopy(base)<EOL>for key in priority.keys():<EOL><INDENT>if key in base:<EOL><INDENT>result[key] = deep_merge_dict(base[key], priority[key])<EOL><DEDENT>else:<EOL><INDENT>result[key] = priority[key]<...
Recursively merges the two given dicts into a single dict. Treating base as the the initial point of the resulting merged dict, and considering the nested dictionaries as trees, they are merged os: 1. Every path to every leaf in priority would be represented in the result. 2. Subtrees of base are overw...
f10125:m21
def norm_int_dict(int_dict):
norm_dict = int_dict.copy()<EOL>val_sum = sum(norm_dict.values())<EOL>for key in norm_dict:<EOL><INDENT>norm_dict[key] = norm_dict[key] / val_sum<EOL><DEDENT>return norm_dict<EOL>
Normalizes values in the given dict with int values. Parameters ---------- int_dict : list A dict object mapping each key to an int value. Returns ------- dict A dict where each key is mapped to its relative part in the sum of all dict values. Example ------- ...
f10125:m22
def sum_num_dicts(dicts, normalize=False):
sum_dict = {}<EOL>for dicti in dicts:<EOL><INDENT>for key in dicti:<EOL><INDENT>sum_dict[key] = sum_dict.get(key, <NUM_LIT:0>) + dicti[key]<EOL><DEDENT><DEDENT>if normalize:<EOL><INDENT>return norm_int_dict(sum_dict)<EOL><DEDENT>return sum_dict<EOL>
Sums the given dicts into a single dict mapping each key to the sum of its mappings in all given dicts. Parameters ---------- dicts : list A list of dict objects mapping each key to an numeric value. normalize : bool, default False Indicated whether to normalize all values by value ...
f10125:m23
def sum_dicts(dicts, normalize=False):
sum_dict = {}<EOL>for dicti in dicts:<EOL><INDENT>for key in dicti:<EOL><INDENT>val = dicti[key]<EOL>if isinstance(val, numbers.Number):<EOL><INDENT>sum_dict[key] = sum_dict.get(key, <NUM_LIT:0>) + val<EOL><DEDENT>else:<EOL><INDENT>sum_dict[key] = val<EOL><DEDENT><DEDENT><DEDENT>if normalize:<EOL><INDENT>return norm_in...
Sums the given dicts into a single dict mapping each numberic-valued key to the sum of its mappings in all given dicts. Keys mapping to non-numeric values retain the last value (by the given order). Parameters ---------- dicts : list A list of dict objects mapping each key to an numeric val...
f10125:m24
def reverse_dict(dict_obj):
new_dict = {}<EOL>for key in dict_obj:<EOL><INDENT>add_to_dict_val_set(dict_obj=new_dict, key=dict_obj[key], val=key)<EOL><DEDENT>for key in new_dict:<EOL><INDENT>new_dict[key] = sorted(new_dict[key], reverse=False)<EOL><DEDENT>return new_dict<EOL>
Reverse a dict, so each value in it maps to a sorted list of its keys. Parameters ---------- dict_obj : dict A key-value dict. Returns ------- dict A dict where each value maps to a sorted list of all the unique keys that mapped to it. Example ------- >>> d...
f10125:m25
def reverse_dict_partial(dict_obj):
new_dict = {}<EOL>for key in dict_obj:<EOL><INDENT>new_dict[dict_obj[key]] = key<EOL><DEDENT>return new_dict<EOL>
Reverse a dict, so each value in it maps to one of its keys. Parameters ---------- dict_obj : dict A key-value dict. Returns ------- dict A dict where each value maps to the key that mapped to it. Example ------- >>> dicti = {'a': 1, 'b': 3} >>> reverse_dict_pa...
f10125:m26
def reverse_list_valued_dict(dict_obj):
new_dict = {}<EOL>for key in dict_obj:<EOL><INDENT>for element in dict_obj[key]:<EOL><INDENT>new_dict[element] = key<EOL><DEDENT><DEDENT>return new_dict<EOL>
Reverse a list-valued dict, so each element in a list maps to its key. Parameters ---------- dict_obj : dict A dict where each key maps to a list of unique values. Values are assumed to be unique across the entire dict, on not just per-list. Returns ------- dict A dict ...
f10125:m27
def flatten_dict(dict_obj, separator='<STR_LIT:.>', flatten_lists=False):
reducer = _get_key_reducer(separator)<EOL>flat = {}<EOL>def _flatten_key_val(key, val, parent):<EOL><INDENT>flat_key = reducer(parent, key)<EOL>try:<EOL><INDENT>_flatten(val, flat_key)<EOL><DEDENT>except TypeError:<EOL><INDENT>flat[flat_key] = val<EOL><DEDENT><DEDENT>def _flatten(d, parent=None):<EOL><INDENT>try:<EOL><...
Flattens the given dict into a single-level dict with flattend keys. Parameters ---------- dict_obj : dict A possibly nested dict. separator : str, optional The character to use as a separator between keys. Defaults to '.'. flatten_lists : bool, optional If True, list values...
f10125:m29
def pprint_int_dict(int_dict, indent=<NUM_LIT:4>, descending=False):
sorted_tup = sorted(int_dict.items(), key=lambda x: x[<NUM_LIT:1>])<EOL>if descending:<EOL><INDENT>sorted_tup.reverse()<EOL><DEDENT>print('<STR_LIT:{>')<EOL>for tup in sorted_tup:<EOL><INDENT>print('<STR_LIT>'.format('<STR_LIT:U+0020>'*indent, tup[<NUM_LIT:0>], tup[<NUM_LIT:1>]))<EOL><DEDENT>print('<STR_LIT:}>')<EOL>
Prints the given dict with int values in a nice way. Parameters ---------- int_dict : list A dict object mapping each key to an int value.
f10125:m30
def pprint_dist_dict(int_dict, indent=<NUM_LIT:4>, descending=False):
sorted_tup = sorted(int_dict.items(), key=lambda x: x[<NUM_LIT:1>])<EOL>if descending:<EOL><INDENT>sorted_tup.reverse()<EOL><DEDENT>print('<STR_LIT:{>')<EOL>for tup in sorted_tup:<EOL><INDENT>print('<STR_LIT>'.format('<STR_LIT:U+0020>'*indent, tup[<NUM_LIT:0>], tup[<NUM_LIT:1>]*<NUM_LIT:100>))<EOL><DEDENT>print('<STR_L...
Prints the given dict, representing a normalized distribution, nicely. Parameters ---------- int_dict : list A dict object mapping each key to an int value between 0 and 1, and all values sum to 1.
f10125:m31
def key_value_nested_generator(dict_obj):
for key, value in dict_obj.items():<EOL><INDENT>if isinstance(value, dict):<EOL><INDENT>for key, value in key_value_nested_generator(value):<EOL><INDENT>yield key, value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield key, value<EOL><DEDENT><DEDENT>
Recursively iterate over key-value pairs of nested dictionaries. Parameters ---------- dict_obj : dict The outer-most dict to iterate on. Returns ------- generator A generator over key-value pairs in all nested dictionaries. Example ------- >>> dicti = {'a': 1, 'b'...
f10125:m32
def key_tuple_value_nested_generator(dict_obj):
for key, value in dict_obj.items():<EOL><INDENT>if isinstance(value, dict):<EOL><INDENT>for nested_key, value in key_tuple_value_nested_generator(value):<EOL><INDENT>yield tuple([key]) + nested_key, value<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield tuple([key]), value<EOL><DEDENT><DEDENT>
Recursively iterate over key-tuple-value pairs of nested dictionaries. Parameters ---------- dict_obj : dict The outer-most dict to iterate on. Returns ------- generator A generator over key-tuple-value pairs in all nested dictionaries. Example ------- >>> dicti = ...
f10125:m33
def all_but(list_obj, idx):
return list_obj[<NUM_LIT:0>:idx] + list_obj[idx+<NUM_LIT:1>:]<EOL>
Returns the given list will all but a single item. Parameters ---------- list_obj : list The list from which to take out an element. idx : int The index of the element to take out. Returns ------- list The list with the element taken out. Example ------- ...
f10128:m0
def order_preserving_single_index_shift(arr, index, new_index):
if new_index == <NUM_LIT:0>:<EOL><INDENT>return [arr[index]] + arr[<NUM_LIT:0>:index] + arr[index+<NUM_LIT:1>:]<EOL><DEDENT>if new_index == len(arr) - <NUM_LIT:1>:<EOL><INDENT>return arr[<NUM_LIT:0>:index] + arr[index+<NUM_LIT:1>:] + [arr[index]]<EOL><DEDENT>if index < new_index:<EOL><INDENT>return arr[<NUM_LIT:0>:inde...
Moves a list element to a new index while preserving order. Parameters --------- arr : list The list in which to shift an element. index : int The index of the element to shift. new_index : int The index to which to shift the element. Returns ------- list ...
f10128:m1
def order_preserving_single_element_shift(arr, value, new_index):
return order_preserving_single_index_shift(<EOL>arr=arr, index=arr.index(value), new_index=new_index)<EOL>
Moves a list element to a new index while preserving order. Parameters --------- arr : list The list in which to shift an element. value : object The value of the element to shift. new_index : int The index to which to shift the element. Returns ------- list ...
f10128:m2
def read_text_file(filename, encoding="<STR_LIT:utf-8>"):
try:<EOL><INDENT>with open(filename, '<STR_LIT:r>', encoding) as f:<EOL><INDENT>r = f.read()<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>with open(filename, '<STR_LIT:r>') as f:<EOL><INDENT>r = f.read()<EOL><DEDENT><DEDENT>return r<EOL>
Reads a file under python3 with encoding (default UTF-8). Also works under python2, without encoding. Uses the EAFP (https://docs.python.org/2/glossary.html#term-eafp) principle.
f10130:m0
def read_text_file(filename, encoding="<STR_LIT:utf-8>"):
try:<EOL><INDENT>with open(filename, '<STR_LIT:r>', encoding) as f:<EOL><INDENT>r = f.read()<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>with open(filename, '<STR_LIT:r>') as f:<EOL><INDENT>r = f.read()<EOL><DEDENT><DEDENT>return r<EOL>
Reads a file under python3 with encoding (default UTF-8). Also works under python2, without encoding. Uses the EAFP (https://docs.python.org/2/glossary.html#term-eafp) principle.
f10137:m0
def write_text_file(filename, contents, encoding="<STR_LIT:utf-8>"):
try:<EOL><INDENT>with open(filename, '<STR_LIT:w>', encoding) as f:<EOL><INDENT>f.write(contents)<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>with open(filename, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(contents)<EOL><DEDENT><DEDENT>
Writes a file under python3 with encoding (default UTF-8). Also works under python2, without encoding. Uses the EAFP (https://docs.python.org/2/glossary.html#term-eafp) principle.
f10137:m1