repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.t_NAME
def t_NAME(self,t): '[A-Za-z]\w*|\"char\"' # warning: this allows stuff like SeLeCt with mixed case. who cares. t.type = KEYWORDS[t.value.lower()] if t.value.lower() in KEYWORDS else 'BOOL' if t.value.lower() in ('is','not') else 'NAME' return t
python
def t_NAME(self,t): '[A-Za-z]\w*|\"char\"' # warning: this allows stuff like SeLeCt with mixed case. who cares. t.type = KEYWORDS[t.value.lower()] if t.value.lower() in KEYWORDS else 'BOOL' if t.value.lower() in ('is','not') else 'NAME' return t
[ "def", "t_NAME", "(", "self", ",", "t", ")", ":", "# warning: this allows stuff like SeLeCt with mixed case. who cares.", "t", ".", "type", "=", "KEYWORDS", "[", "t", ".", "value", ".", "lower", "(", ")", "]", "if", "t", ".", "value", ".", "lower", "(", ")...
[A-Za-z]\w*|\"char\"
[ "[", "A", "-", "Za", "-", "z", "]", "\\", "w", "*", "|", "\\", "char", "\\" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L137-L141
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_typename
def p_typename(self,t): "typename : NAME \n | NAME '(' INTLIT ')'" t[0] = TypeX(t[1],None) if len(t) == 2 else TypeX(t[1],int(t[3]))
python
def p_typename(self,t): "typename : NAME \n | NAME '(' INTLIT ')'" t[0] = TypeX(t[1],None) if len(t) == 2 else TypeX(t[1],int(t[3]))
[ "def", "p_typename", "(", "self", ",", "t", ")", ":", "t", "[", "0", "]", "=", "TypeX", "(", "t", "[", "1", "]", ",", "None", ")", "if", "len", "(", "t", ")", "==", "2", "else", "TypeX", "(", "t", "[", "1", "]", ",", "int", "(", "t", "[...
typename : NAME \n | NAME '(' INTLIT ')
[ "typename", ":", "NAME", "\\", "n", "|", "NAME", "(", "INTLIT", ")" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L164-L166
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_x_boolx
def p_x_boolx(self,t): """expression : unop expression | expression binop expression """ # todo: ply exposes precedence with %prec, use it. if len(t)==4: t[0] = bin_priority(t[2],t[1],t[3]) elif len(t)==3: t[0] = un_priority(t[1],t[2]) else: raise NotImplementedError('unk_len',...
python
def p_x_boolx(self,t): """expression : unop expression | expression binop expression """ # todo: ply exposes precedence with %prec, use it. if len(t)==4: t[0] = bin_priority(t[2],t[1],t[3]) elif len(t)==3: t[0] = un_priority(t[1],t[2]) else: raise NotImplementedError('unk_len',...
[ "def", "p_x_boolx", "(", "self", ",", "t", ")", ":", "# todo: ply exposes precedence with %prec, use it.", "if", "len", "(", "t", ")", "==", "4", ":", "t", "[", "0", "]", "=", "bin_priority", "(", "t", "[", "2", "]", ",", "t", "[", "1", "]", ",", "...
expression : unop expression | expression binop expression
[ "expression", ":", "unop", "expression", "|", "expression", "binop", "expression" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L175-L182
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_x_commalist
def p_x_commalist(self,t): """commalist : commalist ',' expression | expression """ if len(t) == 2: t[0] = CommaX([t[1]]) elif len(t) == 4: t[0] = CommaX(t[1].children+[t[3]]) else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover
python
def p_x_commalist(self,t): """commalist : commalist ',' expression | expression """ if len(t) == 2: t[0] = CommaX([t[1]]) elif len(t) == 4: t[0] = CommaX(t[1].children+[t[3]]) else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover
[ "def", "p_x_commalist", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", "==", "2", ":", "t", "[", "0", "]", "=", "CommaX", "(", "[", "t", "[", "1", "]", "]", ")", "elif", "len", "(", "t", ")", "==", "4", ":", "t", "[", "0",...
commalist : commalist ',' expression | expression
[ "commalist", ":", "commalist", "expression", "|", "expression" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L183-L189
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_array
def p_array(self,t): """expression : '{' commalist '}' | kw_array '[' commalist ']' """ if len(t)==4: t[0] = ArrayLit(t[2].children) elif len(t)==5: t[0] = ArrayLit(t[3].children) else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover
python
def p_array(self,t): """expression : '{' commalist '}' | kw_array '[' commalist ']' """ if len(t)==4: t[0] = ArrayLit(t[2].children) elif len(t)==5: t[0] = ArrayLit(t[3].children) else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover
[ "def", "p_array", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", "==", "4", ":", "t", "[", "0", "]", "=", "ArrayLit", "(", "t", "[", "2", "]", ".", "children", ")", "elif", "len", "(", "t", ")", "==", "5", ":", "t", "[", "...
expression : '{' commalist '}' | kw_array '[' commalist ']'
[ "expression", ":", "{", "commalist", "}", "|", "kw_array", "[", "commalist", "]" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L190-L196
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_whenlist
def p_whenlist(self,t): """whenlist : whenlist kw_when expression kw_then expression | kw_when expression kw_then expression """ if len(t)==5: t[0] = [WhenX(t[2],t[4])] elif len(t)==6: t[0] = t[1] + [WhenX(t[3],t[5])] else: raise NotImplementedError('unk_len',len(t)) # pragma: no cov...
python
def p_whenlist(self,t): """whenlist : whenlist kw_when expression kw_then expression | kw_when expression kw_then expression """ if len(t)==5: t[0] = [WhenX(t[2],t[4])] elif len(t)==6: t[0] = t[1] + [WhenX(t[3],t[5])] else: raise NotImplementedError('unk_len',len(t)) # pragma: no cov...
[ "def", "p_whenlist", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", "==", "5", ":", "t", "[", "0", "]", "=", "[", "WhenX", "(", "t", "[", "2", "]", ",", "t", "[", "4", "]", ")", "]", "elif", "len", "(", "t", ")", "==", "...
whenlist : whenlist kw_when expression kw_then expression | kw_when expression kw_then expression
[ "whenlist", ":", "whenlist", "kw_when", "expression", "kw_then", "expression", "|", "kw_when", "expression", "kw_then", "expression" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L197-L203
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_case
def p_case(self,t): """expression : kw_case whenlist kw_else expression kw_end | kw_case whenlist kw_end """ if len(t)==4: t[0] = CaseX(t[2],None) elif len(t)==6: t[0] = CaseX(t[2],t[4]) else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover
python
def p_case(self,t): """expression : kw_case whenlist kw_else expression kw_end | kw_case whenlist kw_end """ if len(t)==4: t[0] = CaseX(t[2],None) elif len(t)==6: t[0] = CaseX(t[2],t[4]) else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover
[ "def", "p_case", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", "==", "4", ":", "t", "[", "0", "]", "=", "CaseX", "(", "t", "[", "2", "]", ",", "None", ")", "elif", "len", "(", "t", ")", "==", "6", ":", "t", "[", "0", "]...
expression : kw_case whenlist kw_else expression kw_end | kw_case whenlist kw_end
[ "expression", ":", "kw_case", "whenlist", "kw_else", "expression", "kw_end", "|", "kw_case", "whenlist", "kw_end" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L204-L210
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_attr
def p_attr(self,t): """attr : NAME '.' NAME | NAME '.' '*' """ # careful: sqex.infer_columns relies on AttrX not containing anything but a name t[0] = AttrX(NameX(t[1]), AsterX() if t[3]=='*' else NameX(t[3]))
python
def p_attr(self,t): """attr : NAME '.' NAME | NAME '.' '*' """ # careful: sqex.infer_columns relies on AttrX not containing anything but a name t[0] = AttrX(NameX(t[1]), AsterX() if t[3]=='*' else NameX(t[3]))
[ "def", "p_attr", "(", "self", ",", "t", ")", ":", "# careful: sqex.infer_columns relies on AttrX not containing anything but a name", "t", "[", "0", "]", "=", "AttrX", "(", "NameX", "(", "t", "[", "1", "]", ")", ",", "AsterX", "(", ")", "if", "t", "[", "3"...
attr : NAME '.' NAME | NAME '.' '*'
[ "attr", ":", "NAME", ".", "NAME", "|", "NAME", ".", "*" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L214-L219
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_fromtable
def p_fromtable(self,t): """fromtable : NAME | aliasx | '(' selectx ')' kw_as NAME """ if len(t)==6: t[0]=AliasX(t[2],t[5]) elif len(t)==2: t[0]=t[1] else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover
python
def p_fromtable(self,t): """fromtable : NAME | aliasx | '(' selectx ')' kw_as NAME """ if len(t)==6: t[0]=AliasX(t[2],t[5]) elif len(t)==2: t[0]=t[1] else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover
[ "def", "p_fromtable", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", "==", "6", ":", "t", "[", "0", "]", "=", "AliasX", "(", "t", "[", "2", "]", ",", "t", "[", "5", "]", ")", "elif", "len", "(", "t", ")", "==", "2", ":", ...
fromtable : NAME | aliasx | '(' selectx ')' kw_as NAME
[ "fromtable", ":", "NAME", "|", "aliasx", "|", "(", "selectx", ")", "kw_as", "NAME" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L225-L232
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_jointype
def p_jointype(self,t): """jointype : kw_join | kw_inner kw_join | outerjoin kw_outer kw_join | outerjoin kw_join """ if len(t) <= 2 or t[1] == 'inner': t[0] = JoinTypeX(None, False, None) else: t[0] = JoinTypeX(t[1], True, None)
python
def p_jointype(self,t): """jointype : kw_join | kw_inner kw_join | outerjoin kw_outer kw_join | outerjoin kw_join """ if len(t) <= 2 or t[1] == 'inner': t[0] = JoinTypeX(None, False, None) else: t[0] = JoinTypeX(t[1], True, None)
[ "def", "p_jointype", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", "<=", "2", "or", "t", "[", "1", "]", "==", "'inner'", ":", "t", "[", "0", "]", "=", "JoinTypeX", "(", "None", ",", "False", ",", "None", ")", "else", ":", "t"...
jointype : kw_join | kw_inner kw_join | outerjoin kw_outer kw_join | outerjoin kw_join
[ "jointype", ":", "kw_join", "|", "kw_inner", "kw_join", "|", "outerjoin", "kw_outer", "kw_join", "|", "outerjoin", "kw_join" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L234-L241
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_joinx
def p_joinx(self,t): # todo: support join types http://www.postgresql.org/docs/9.4/static/queries-table-expressions.html#QUERIES-JOIN """joinx : fromtable jointype fromtable | fromtable jointype fromtable kw_on expression | fromtable jointype fromtable kw_using '(' namelist ')' """...
python
def p_joinx(self,t): # todo: support join types http://www.postgresql.org/docs/9.4/static/queries-table-expressions.html#QUERIES-JOIN """joinx : fromtable jointype fromtable | fromtable jointype fromtable kw_on expression | fromtable jointype fromtable kw_using '(' namelist ')' """...
[ "def", "p_joinx", "(", "self", ",", "t", ")", ":", "# todo: support join types http://www.postgresql.org/docs/9.4/static/queries-table-expressions.html#QUERIES-JOIN", "if", "len", "(", "t", ")", "==", "4", ":", "t", "[", "0", "]", "=", "JoinX", "(", "t", "[", "1",...
joinx : fromtable jointype fromtable | fromtable jointype fromtable kw_on expression | fromtable jointype fromtable kw_using '(' namelist ')'
[ "joinx", ":", "fromtable", "jointype", "fromtable", "|", "fromtable", "jointype", "fromtable", "kw_on", "expression", "|", "fromtable", "jointype", "fromtable", "kw_using", "(", "namelist", ")" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L242-L250
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_fromitem_list
def p_fromitem_list(self,t): """fromitem_list : fromitem_list ',' fromitem | fromitem """ if len(t)==2: t[0] = [t[1]] elif len(t)==4: t[0] = t[1] + [t[3]] else: raise NotImplementedError('unk_len', len(t)) # pragma: no cover
python
def p_fromitem_list(self,t): """fromitem_list : fromitem_list ',' fromitem | fromitem """ if len(t)==2: t[0] = [t[1]] elif len(t)==4: t[0] = t[1] + [t[3]] else: raise NotImplementedError('unk_len', len(t)) # pragma: no cover
[ "def", "p_fromitem_list", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", "==", "2", ":", "t", "[", "0", "]", "=", "[", "t", "[", "1", "]", "]", "elif", "len", "(", "t", ")", "==", "4", ":", "t", "[", "0", "]", "=", "t", ...
fromitem_list : fromitem_list ',' fromitem | fromitem
[ "fromitem_list", ":", "fromitem_list", "fromitem", "|", "fromitem" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L252-L258
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_namelist
def p_namelist(self,t): "namelist : namelist ',' NAME \n | NAME" if len(t)==2: t[0] = [t[1]] elif len(t)==4: t[0] = t[1] + [t[3]] else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover
python
def p_namelist(self,t): "namelist : namelist ',' NAME \n | NAME" if len(t)==2: t[0] = [t[1]] elif len(t)==4: t[0] = t[1] + [t[3]] else: raise NotImplementedError('unk_len',len(t)) # pragma: no cover
[ "def", "p_namelist", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", "==", "2", ":", "t", "[", "0", "]", "=", "[", "t", "[", "1", "]", "]", "elif", "len", "(", "t", ")", "==", "4", ":", "t", "[", "0", "]", "=", "t", "[", ...
namelist : namelist ',' NAME \n | NAME
[ "namelist", ":", "namelist", "NAME", "\\", "n", "|", "NAME" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L277-L281
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_createx
def p_createx(self,t): """expression : kw_create kw_table nexists NAME '(' tablespecs ')' opt_inheritx | kw_create kw_table nexists NAME inheritx """ if len(t)==6: t[0] = CreateX(t[3], t[4], [], None, [], t[5]) else: all_constraints = {k:list(group) for k, group in itertool...
python
def p_createx(self,t): """expression : kw_create kw_table nexists NAME '(' tablespecs ')' opt_inheritx | kw_create kw_table nexists NAME inheritx """ if len(t)==6: t[0] = CreateX(t[3], t[4], [], None, [], t[5]) else: all_constraints = {k:list(group) for k, group in itertool...
[ "def", "p_createx", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", "==", "6", ":", "t", "[", "0", "]", "=", "CreateX", "(", "t", "[", "3", "]", ",", "t", "[", "4", "]", ",", "[", "]", ",", "None", ",", "[", "]", ",", "t"...
expression : kw_create kw_table nexists NAME '(' tablespecs ')' opt_inheritx | kw_create kw_table nexists NAME inheritx
[ "expression", ":", "kw_create", "kw_table", "nexists", "NAME", "(", "tablespecs", ")", "opt_inheritx", "|", "kw_create", "kw_table", "nexists", "NAME", "inheritx" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L302-L315
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_returnx
def p_returnx(self,t): "opt_returnx : kw_returning commalist \n | " # note: this gets weird because '(' commalist ')' is an expression but we need bare commalist to support non-paren returns t[0] = None if len(t)==1 else ReturnX(t[2].children[0] if len(t[2].children)==1 else t[2])
python
def p_returnx(self,t): "opt_returnx : kw_returning commalist \n | " # note: this gets weird because '(' commalist ')' is an expression but we need bare commalist to support non-paren returns t[0] = None if len(t)==1 else ReturnX(t[2].children[0] if len(t[2].children)==1 else t[2])
[ "def", "p_returnx", "(", "self", ",", "t", ")", ":", "# note: this gets weird because '(' commalist ')' is an expression but we need bare commalist to support non-paren returns", "t", "[", "0", "]", "=", "None", "if", "len", "(", "t", ")", "==", "1", "else", "ReturnX", ...
opt_returnx : kw_returning commalist \n |
[ "opt_returnx", ":", "kw_returning", "commalist", "\\", "n", "|" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L321-L324
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_insertx
def p_insertx(self,t): "expression : kw_insert kw_into NAME opt_paren_namelist kw_values '(' commalist ')' opt_returnx" t[0] = InsertX(t[3],t[4],t[7].children,t[9])
python
def p_insertx(self,t): "expression : kw_insert kw_into NAME opt_paren_namelist kw_values '(' commalist ')' opt_returnx" t[0] = InsertX(t[3],t[4],t[7].children,t[9])
[ "def", "p_insertx", "(", "self", ",", "t", ")", ":", "t", "[", "0", "]", "=", "InsertX", "(", "t", "[", "3", "]", ",", "t", "[", "4", "]", ",", "t", "[", "7", "]", ".", "children", ",", "t", "[", "9", "]", ")" ]
expression : kw_insert kw_into NAME opt_paren_namelist kw_values '(' commalist ')' opt_returnx
[ "expression", ":", "kw_insert", "kw_into", "NAME", "opt_paren_namelist", "kw_values", "(", "commalist", ")", "opt_returnx" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L326-L328
abe-winter/pg13-py
pg13/sqparse2.py
SqlGrammar.p_assignlist
def p_assignlist(self,t): "assignlist : assignlist ',' assign \n | assign" if len(t)==4: t[0] = t[1] + [t[3]] elif len(t)==2: t[0] = [t[1]] else: raise NotImplementedError('unk_len', len(t)) # pragma: no cover
python
def p_assignlist(self,t): "assignlist : assignlist ',' assign \n | assign" if len(t)==4: t[0] = t[1] + [t[3]] elif len(t)==2: t[0] = [t[1]] else: raise NotImplementedError('unk_len', len(t)) # pragma: no cover
[ "def", "p_assignlist", "(", "self", ",", "t", ")", ":", "if", "len", "(", "t", ")", "==", "4", ":", "t", "[", "0", "]", "=", "t", "[", "1", "]", "+", "[", "t", "[", "3", "]", "]", "elif", "len", "(", "t", ")", "==", "2", ":", "t", "["...
assignlist : assignlist ',' assign \n | assign
[ "assignlist", ":", "assignlist", "assign", "\\", "n", "|", "assign" ]
train
https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/sqparse2.py#L332-L336
veltzer/pypitools
pypitools/scripts/register.py
main
def main(): """ register a function on pypi or gemfury :return: """ setup_main() config = ConfigData(clean=True) try: config.register() finally: config.clean_after_if_needed()
python
def main(): """ register a function on pypi or gemfury :return: """ setup_main() config = ConfigData(clean=True) try: config.register() finally: config.clean_after_if_needed()
[ "def", "main", "(", ")", ":", "setup_main", "(", ")", "config", "=", "ConfigData", "(", "clean", "=", "True", ")", "try", ":", "config", ".", "register", "(", ")", "finally", ":", "config", ".", "clean_after_if_needed", "(", ")" ]
register a function on pypi or gemfury :return:
[ "register", "a", "function", "on", "pypi", "or", "gemfury", ":", "return", ":" ]
train
https://github.com/veltzer/pypitools/blob/5f097be21e9bc65578eed5b6b7855c1945540701/pypitools/scripts/register.py#L31-L41
PSU-OIT-ARC/elasticmodels
elasticmodels/indexes.py
suspended_updates
def suspended_updates(): """ This allows you to postpone updates to all the search indexes inside of a with: with suspended_updates(): model1.save() model2.save() model3.save() model4.delete() """ if getattr(local_storage, "bulk_queue", None) is N...
python
def suspended_updates(): """ This allows you to postpone updates to all the search indexes inside of a with: with suspended_updates(): model1.save() model2.save() model3.save() model4.delete() """ if getattr(local_storage, "bulk_queue", None) is N...
[ "def", "suspended_updates", "(", ")", ":", "if", "getattr", "(", "local_storage", ",", "\"bulk_queue\"", ",", "None", ")", "is", "None", ":", "local_storage", ".", "bulk_queue", "=", "defaultdict", "(", "list", ")", "try", ":", "yield", "finally", ":", "fo...
This allows you to postpone updates to all the search indexes inside of a with: with suspended_updates(): model1.save() model2.save() model3.save() model4.delete()
[ "This", "allows", "you", "to", "postpone", "updates", "to", "all", "the", "search", "indexes", "inside", "of", "a", "with", ":" ]
train
https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/indexes.py#L88-L106
PSU-OIT-ARC/elasticmodels
elasticmodels/indexes.py
IndexRegistry.register
def register(self, model, index): """Register the model with the registry""" self.model_to_indexes[model].add(index) if not self.connected: connections.index_name = {} from django.conf import settings kwargs = {} for name, params in settings.ELASTI...
python
def register(self, model, index): """Register the model with the registry""" self.model_to_indexes[model].add(index) if not self.connected: connections.index_name = {} from django.conf import settings kwargs = {} for name, params in settings.ELASTI...
[ "def", "register", "(", "self", ",", "model", ",", "index", ")", ":", "self", ".", "model_to_indexes", "[", "model", "]", ".", "add", "(", "index", ")", "if", "not", "self", ".", "connected", ":", "connections", ".", "index_name", "=", "{", "}", "fro...
Register the model with the registry
[ "Register", "the", "model", "with", "the", "registry" ]
train
https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/indexes.py#L42-L54
PSU-OIT-ARC/elasticmodels
elasticmodels/indexes.py
IndexRegistry.update
def update(self, instance, **kwargs): """ Update all the Index instances attached to this model (if their ignore_signals flag allows it) """ for index in self.model_to_indexes[instance.__class__]: if not index._doc_type.ignore_signals: index.update(ins...
python
def update(self, instance, **kwargs): """ Update all the Index instances attached to this model (if their ignore_signals flag allows it) """ for index in self.model_to_indexes[instance.__class__]: if not index._doc_type.ignore_signals: index.update(ins...
[ "def", "update", "(", "self", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "for", "index", "in", "self", ".", "model_to_indexes", "[", "instance", ".", "__class__", "]", ":", "if", "not", "index", ".", "_doc_type", ".", "ignore_signals", ":", "i...
Update all the Index instances attached to this model (if their ignore_signals flag allows it)
[ "Update", "all", "the", "Index", "instances", "attached", "to", "this", "model", "(", "if", "their", "ignore_signals", "flag", "allows", "it", ")" ]
train
https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/indexes.py#L56-L63
jmgilman/Neolib
neolib/shop/UserShopFront.py
UserShopFront.load
def load(self): """ Loads the shop details and current inventory Raises parseException """ pg = self.usr.getPage("http://www.neopets.com/browseshop.phtml?owner=" + self.owner) # Checks for valid shop if "doesn't have a shop" in pg.content: ...
python
def load(self): """ Loads the shop details and current inventory Raises parseException """ pg = self.usr.getPage("http://www.neopets.com/browseshop.phtml?owner=" + self.owner) # Checks for valid shop if "doesn't have a shop" in pg.content: ...
[ "def", "load", "(", "self", ")", ":", "pg", "=", "self", ".", "usr", ".", "getPage", "(", "\"http://www.neopets.com/browseshop.phtml?owner=\"", "+", "self", ".", "owner", ")", "# Checks for valid shop", "if", "\"doesn't have a shop\"", "in", "pg", ".", "content", ...
Loads the shop details and current inventory Raises parseException
[ "Loads", "the", "shop", "details", "and", "current", "inventory", "Raises", "parseException" ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/shop/UserShopFront.py#L59-L85
ardydedase/pycouchbase
pycouchbase/connection.py
Connection.bucket
def bucket(cls, bucket_name, connection=None): """Gives the bucket from couchbase server. :param bucket_name: Bucket name to fetch. :type bucket_name: str :returns: couchbase driver's Bucket object. :rtype: :class:`couchbase.client.Bucket` :raises: :exc:`RuntimeError` If...
python
def bucket(cls, bucket_name, connection=None): """Gives the bucket from couchbase server. :param bucket_name: Bucket name to fetch. :type bucket_name: str :returns: couchbase driver's Bucket object. :rtype: :class:`couchbase.client.Bucket` :raises: :exc:`RuntimeError` If...
[ "def", "bucket", "(", "cls", ",", "bucket_name", ",", "connection", "=", "None", ")", ":", "connection", "=", "cls", ".", "connection", "if", "connection", "==", "None", "else", "connection", "if", "bucket_name", "not", "in", "cls", ".", "_buckets", ":", ...
Gives the bucket from couchbase server. :param bucket_name: Bucket name to fetch. :type bucket_name: str :returns: couchbase driver's Bucket object. :rtype: :class:`couchbase.client.Bucket` :raises: :exc:`RuntimeError` If the credentials wasn't set.
[ "Gives", "the", "bucket", "from", "couchbase", "server", "." ]
train
https://github.com/ardydedase/pycouchbase/blob/6f010b4d2ef41aead2366878d0cf0b1284c0db0e/pycouchbase/connection.py#L23-L43
ulf1/oxyba
oxyba/linreg_ols_qr.py
linreg_ols_qr
def linreg_ols_qr(y, X): """Linear Regression, OLS, inverse by QR Factoring""" import numpy as np try: # multiply with inverse to compute coefficients q, r = np.linalg.qr(np.dot(X.T, X)) return np.dot(np.dot(np.linalg.inv(r), q.T), np.dot(X.T, y)) except np.linalg.LinAlgError: p...
python
def linreg_ols_qr(y, X): """Linear Regression, OLS, inverse by QR Factoring""" import numpy as np try: # multiply with inverse to compute coefficients q, r = np.linalg.qr(np.dot(X.T, X)) return np.dot(np.dot(np.linalg.inv(r), q.T), np.dot(X.T, y)) except np.linalg.LinAlgError: p...
[ "def", "linreg_ols_qr", "(", "y", ",", "X", ")", ":", "import", "numpy", "as", "np", "try", ":", "# multiply with inverse to compute coefficients", "q", ",", "r", "=", "np", ".", "linalg", ".", "qr", "(", "np", ".", "dot", "(", "X", ".", "T", ",", "X...
Linear Regression, OLS, inverse by QR Factoring
[ "Linear", "Regression", "OLS", "inverse", "by", "QR", "Factoring" ]
train
https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/linreg_ols_qr.py#L2-L10
inspirehep/plotextractor
plotextractor/output_utils.py
find_open_and_close_braces
def find_open_and_close_braces(line_index, start, brace, lines): """ Take the line where we want to start and the index where we want to start and find the first instance of matched open and close braces of the same type as brace in file file. :param: line (int): the index of the line we want to st...
python
def find_open_and_close_braces(line_index, start, brace, lines): """ Take the line where we want to start and the index where we want to start and find the first instance of matched open and close braces of the same type as brace in file file. :param: line (int): the index of the line we want to st...
[ "def", "find_open_and_close_braces", "(", "line_index", ",", "start", ",", "brace", ",", "lines", ")", ":", "if", "brace", "in", "[", "'['", ",", "']'", "]", ":", "open_brace", "=", "'['", "close_brace", "=", "']'", "elif", "brace", "in", "[", "'{'", "...
Take the line where we want to start and the index where we want to start and find the first instance of matched open and close braces of the same type as brace in file file. :param: line (int): the index of the line we want to start searching at :param: start (int): the index in the line we want to st...
[ "Take", "the", "line", "where", "we", "want", "to", "start", "and", "the", "index", "where", "we", "want", "to", "start", "and", "find", "the", "first", "instance", "of", "matched", "open", "and", "close", "braces", "of", "the", "same", "type", "as", "...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L31-L116
inspirehep/plotextractor
plotextractor/output_utils.py
assemble_caption
def assemble_caption(begin_line, begin_index, end_line, end_index, lines): """ Take the caption of a picture and put it all together in a nice way. If it spans multiple lines, put it on one line. If it contains controlled characters, strip them out. If it has tags we don't want to worry about, ge...
python
def assemble_caption(begin_line, begin_index, end_line, end_index, lines): """ Take the caption of a picture and put it all together in a nice way. If it spans multiple lines, put it on one line. If it contains controlled characters, strip them out. If it has tags we don't want to worry about, ge...
[ "def", "assemble_caption", "(", "begin_line", ",", "begin_index", ",", "end_line", ",", "end_index", ",", "lines", ")", ":", "# stuff we don't like", "label_head", "=", "'\\\\label{'", "# reassemble that sucker", "if", "end_line", ">", "begin_line", ":", "# our captio...
Take the caption of a picture and put it all together in a nice way. If it spans multiple lines, put it on one line. If it contains controlled characters, strip them out. If it has tags we don't want to worry about, get rid of them, etc. :param: begin_line (int): the index of the line where the capt...
[ "Take", "the", "caption", "of", "a", "picture", "and", "put", "it", "all", "together", "in", "a", "nice", "way", ".", "If", "it", "spans", "multiple", "lines", "put", "it", "on", "one", "line", ".", "If", "it", "contains", "controlled", "characters", "...
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L119-L168
inspirehep/plotextractor
plotextractor/output_utils.py
prepare_image_data
def prepare_image_data(extracted_image_data, output_directory, image_mapping): """Prepare and clean image-data from duplicates and other garbage. :param: extracted_image_data ([(string, string, list, list) ...], ...])): the images and their captions + contexts, ordered :param...
python
def prepare_image_data(extracted_image_data, output_directory, image_mapping): """Prepare and clean image-data from duplicates and other garbage. :param: extracted_image_data ([(string, string, list, list) ...], ...])): the images and their captions + contexts, ordered :param...
[ "def", "prepare_image_data", "(", "extracted_image_data", ",", "output_directory", ",", "image_mapping", ")", ":", "img_list", "=", "{", "}", "for", "image", ",", "caption", ",", "label", "in", "extracted_image_data", ":", "if", "not", "image", "or", "image", ...
Prepare and clean image-data from duplicates and other garbage. :param: extracted_image_data ([(string, string, list, list) ...], ...])): the images and their captions + contexts, ordered :param: tex_file (string): the location of the TeX (used for finding the associated images; the TeX is assu...
[ "Prepare", "and", "clean", "image", "-", "data", "from", "duplicates", "and", "other", "garbage", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L171-L211
inspirehep/plotextractor
plotextractor/output_utils.py
get_image_location
def get_image_location(image, sdir, image_list, recurred=False): """Take a raw image name + directory and return the location of image. :param: image (string): the name of the raw image from the TeX :param: sdir (string): the directory where everything was unzipped to :param: image_list ([string, strin...
python
def get_image_location(image, sdir, image_list, recurred=False): """Take a raw image name + directory and return the location of image. :param: image (string): the name of the raw image from the TeX :param: sdir (string): the directory where everything was unzipped to :param: image_list ([string, strin...
[ "def", "get_image_location", "(", "image", ",", "sdir", ",", "image_list", ",", "recurred", "=", "False", ")", ":", "if", "isinstance", "(", "image", ",", "list", ")", ":", "# image is a list, not good", "return", "None", "image", "=", "image", ".", "encode"...
Take a raw image name + directory and return the location of image. :param: image (string): the name of the raw image from the TeX :param: sdir (string): the directory where everything was unzipped to :param: image_list ([string, string, ...]): the list of images that were extracted from the tarbal...
[ "Take", "a", "raw", "image", "name", "+", "directory", "and", "return", "the", "location", "of", "image", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L214-L315
inspirehep/plotextractor
plotextractor/output_utils.py
get_converted_image_name
def get_converted_image_name(image): """Return the name of the image after it has been converted to png format. Strips off the old extension. :param: image (string): The fullpath of the image before conversion :return: converted_image (string): the fullpath of the image after convert """ png_...
python
def get_converted_image_name(image): """Return the name of the image after it has been converted to png format. Strips off the old extension. :param: image (string): The fullpath of the image before conversion :return: converted_image (string): the fullpath of the image after convert """ png_...
[ "def", "get_converted_image_name", "(", "image", ")", ":", "png_extension", "=", "'.png'", "if", "image", "[", "(", "0", "-", "len", "(", "png_extension", ")", ")", ":", "]", "==", "png_extension", ":", "# it already ends in png! we're golden", "return", "image...
Return the name of the image after it has been converted to png format. Strips off the old extension. :param: image (string): The fullpath of the image before conversion :return: converted_image (string): the fullpath of the image after convert
[ "Return", "the", "name", "of", "the", "image", "after", "it", "has", "been", "converted", "to", "png", "format", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L318-L344
inspirehep/plotextractor
plotextractor/output_utils.py
get_tex_location
def get_tex_location(new_tex_name, current_tex_name, recurred=False): """ Takes the name of a TeX file and attempts to match it to an actual file in the tarball. :param: new_tex_name (string): the name of the TeX file to find :param: current_tex_name (string): the location of the TeX file where we ...
python
def get_tex_location(new_tex_name, current_tex_name, recurred=False): """ Takes the name of a TeX file and attempts to match it to an actual file in the tarball. :param: new_tex_name (string): the name of the TeX file to find :param: current_tex_name (string): the location of the TeX file where we ...
[ "def", "get_tex_location", "(", "new_tex_name", ",", "current_tex_name", ",", "recurred", "=", "False", ")", ":", "tex_location", "=", "None", "current_dir", "=", "os", ".", "path", ".", "split", "(", "current_tex_name", ")", "[", "0", "]", "some_kind_of_tag",...
Takes the name of a TeX file and attempts to match it to an actual file in the tarball. :param: new_tex_name (string): the name of the TeX file to find :param: current_tex_name (string): the location of the TeX file where we found the reference :return: tex_location (string): the location of t...
[ "Takes", "the", "name", "of", "a", "TeX", "file", "and", "attempts", "to", "match", "it", "to", "an", "actual", "file", "in", "the", "tarball", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L347-L412
inspirehep/plotextractor
plotextractor/output_utils.py
get_name_from_path
def get_name_from_path(full_path, root_path): """Create a filename by merging path after root directory.""" relative_image_path = os.path.relpath(full_path, root_path) return "_".join(relative_image_path.split('.')[:-1]).replace('/', '_')\ .replace(';', '').replace(':', '')
python
def get_name_from_path(full_path, root_path): """Create a filename by merging path after root directory.""" relative_image_path = os.path.relpath(full_path, root_path) return "_".join(relative_image_path.split('.')[:-1]).replace('/', '_')\ .replace(';', '').replace(':', '')
[ "def", "get_name_from_path", "(", "full_path", ",", "root_path", ")", ":", "relative_image_path", "=", "os", ".", "path", ".", "relpath", "(", "full_path", ",", "root_path", ")", "return", "\"_\"", ".", "join", "(", "relative_image_path", ".", "split", "(", ...
Create a filename by merging path after root directory.
[ "Create", "a", "filename", "by", "merging", "path", "after", "root", "directory", "." ]
train
https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/output_utils.py#L415-L419
awsroadhouse/roadhouse
roadhouse/group.py
SecurityGroupsConfig.apply
def apply(self, vpc): """ returns a list of new security groups that will be added """ assert vpc is not None # make sure we're up to date self.reload_remote_groups() vpc_groups = self.vpc_groups(vpc) self._apply_groups(vpc) # reloads groups from...
python
def apply(self, vpc): """ returns a list of new security groups that will be added """ assert vpc is not None # make sure we're up to date self.reload_remote_groups() vpc_groups = self.vpc_groups(vpc) self._apply_groups(vpc) # reloads groups from...
[ "def", "apply", "(", "self", ",", "vpc", ")", ":", "assert", "vpc", "is", "not", "None", "# make sure we're up to date", "self", ".", "reload_remote_groups", "(", ")", "vpc_groups", "=", "self", ".", "vpc_groups", "(", "vpc", ")", "self", ".", "_apply_groups...
returns a list of new security groups that will be added
[ "returns", "a", "list", "of", "new", "security", "groups", "that", "will", "be", "added" ]
train
https://github.com/awsroadhouse/roadhouse/blob/d7c2c316fc20a04b8cae3357996c0ce4f51d44ea/roadhouse/group.py#L53-L103
awsroadhouse/roadhouse
roadhouse/group.py
SecurityGroupsConfig.filter_existing_rules
def filter_existing_rules(self, rules, group): """returns list of rules with the existing ones filtered out :param group security group we need to check the rules against :type group boto.ec2.securitygroup.SecurityGroup :rtype list of Rule """ tmp = [] for rule in...
python
def filter_existing_rules(self, rules, group): """returns list of rules with the existing ones filtered out :param group security group we need to check the rules against :type group boto.ec2.securitygroup.SecurityGroup :rtype list of Rule """ tmp = [] for rule in...
[ "def", "filter_existing_rules", "(", "self", ",", "rules", ",", "group", ")", ":", "tmp", "=", "[", "]", "for", "rule", "in", "rules", ":", "def", "eq", "(", "x", ")", ":", "# returns True if this existing AWS rule matches the one we want to create", "assert", "...
returns list of rules with the existing ones filtered out :param group security group we need to check the rules against :type group boto.ec2.securitygroup.SecurityGroup :rtype list of Rule
[ "returns", "list", "of", "rules", "with", "the", "existing", "ones", "filtered", "out", ":", "param", "group", "security", "group", "we", "need", "to", "check", "the", "rules", "against", ":", "type", "group", "boto", ".", "ec2", ".", "securitygroup", ".",...
train
https://github.com/awsroadhouse/roadhouse/blob/d7c2c316fc20a04b8cae3357996c0ce4f51d44ea/roadhouse/group.py#L105-L159
fedora-infra/fmn.rules
fmn/rules/anitya.py
anitya_unmapped_new_update
def anitya_unmapped_new_update(config, message): """ New releases of upstream projects that have no mapping to Fedora Adding this rule will let through events when new upstream releases are detected, but only on upstream projects that have no mapping to Fedora Packages. This could be useful to you if ...
python
def anitya_unmapped_new_update(config, message): """ New releases of upstream projects that have no mapping to Fedora Adding this rule will let through events when new upstream releases are detected, but only on upstream projects that have no mapping to Fedora Packages. This could be useful to you if ...
[ "def", "anitya_unmapped_new_update", "(", "config", ",", "message", ")", ":", "if", "not", "anitya_new_update", "(", "config", ",", "message", ")", ":", "return", "False", "for", "package", "in", "message", "[", "'msg'", "]", "[", "'message'", "]", "[", "'...
New releases of upstream projects that have no mapping to Fedora Adding this rule will let through events when new upstream releases are detected, but only on upstream projects that have no mapping to Fedora Packages. This could be useful to you if you want to monitor release-monitoring.org itself and...
[ "New", "releases", "of", "upstream", "projects", "that", "have", "no", "mapping", "to", "Fedora" ]
train
https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/anitya.py#L8-L25
fedora-infra/fmn.rules
fmn/rules/anitya.py
anitya_specific_distro
def anitya_specific_distro(config, message, distro=None, *args, **kw): """ Distro-specific release-monitoring.org events This rule will match all anitya events *only for a particular distro*. """ if not distro: return False if not anitya_catchall(config, message): return False ...
python
def anitya_specific_distro(config, message, distro=None, *args, **kw): """ Distro-specific release-monitoring.org events This rule will match all anitya events *only for a particular distro*. """ if not distro: return False if not anitya_catchall(config, message): return False ...
[ "def", "anitya_specific_distro", "(", "config", ",", "message", ",", "distro", "=", "None", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "if", "not", "distro", ":", "return", "False", "if", "not", "anitya_catchall", "(", "config", ",", "message", "...
Distro-specific release-monitoring.org events This rule will match all anitya events *only for a particular distro*.
[ "Distro", "-", "specific", "release", "-", "monitoring", ".", "org", "events" ]
train
https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/anitya.py#L41-L70
fedora-infra/fmn.rules
fmn/rules/anitya.py
anitya_by_upstream_project
def anitya_by_upstream_project(config, message, projects=None, *args, **kw): """ Anything regarding a particular "upstream project" Adding this rule will let through *any* anitya notification that pertains to a particular "upstream project". Note that the "project" name is often different from the dis...
python
def anitya_by_upstream_project(config, message, projects=None, *args, **kw): """ Anything regarding a particular "upstream project" Adding this rule will let through *any* anitya notification that pertains to a particular "upstream project". Note that the "project" name is often different from the dis...
[ "def", "anitya_by_upstream_project", "(", "config", ",", "message", ",", "projects", "=", "None", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "# We only deal in anitya messages, first off.", "if", "not", "anitya_catchall", "(", "config", ",", "message", ")"...
Anything regarding a particular "upstream project" Adding this rule will let through *any* anitya notification that pertains to a particular "upstream project". Note that the "project" name is often different from the distro "package" name. For instance, the package python-requests in Fedora will hav...
[ "Anything", "regarding", "a", "particular", "upstream", "project" ]
train
https://github.com/fedora-infra/fmn.rules/blob/f9ec790619fcc8b41803077c4dec094e5127fc24/fmn/rules/anitya.py#L187-L212
radjkarl/appBase
appbase/Launcher.py
_FileSystemModel.data
def data(self, index, role): """use zipped icon.png as icon""" if index.column() == 0 and role == QtCore.Qt.DecorationRole: if self.isPyz(index): with ZipFile(str(self.filePath(index)), 'r') as myzip: # print myzip.namelist() t...
python
def data(self, index, role): """use zipped icon.png as icon""" if index.column() == 0 and role == QtCore.Qt.DecorationRole: if self.isPyz(index): with ZipFile(str(self.filePath(index)), 'r') as myzip: # print myzip.namelist() t...
[ "def", "data", "(", "self", ",", "index", ",", "role", ")", ":", "if", "index", ".", "column", "(", ")", "==", "0", "and", "role", "==", "QtCore", ".", "Qt", ".", "DecorationRole", ":", "if", "self", ".", "isPyz", "(", "index", ")", ":", "with", ...
use zipped icon.png as icon
[ "use", "zipped", "icon", ".", "png", "as", "icon" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Launcher.py#L524-L536
radjkarl/appBase
appbase/Launcher.py
_FileSystemModel.editStartScript
def editStartScript(self, index): """open, edit, replace __main__.py""" f = str(self.fileName(index)) if f.endswith('.%s' % self.file_type): zipname = str(self.filePath(index)) with ZipFile(zipname, 'a') as myzip: # extract+save script in tmp-dir: ...
python
def editStartScript(self, index): """open, edit, replace __main__.py""" f = str(self.fileName(index)) if f.endswith('.%s' % self.file_type): zipname = str(self.filePath(index)) with ZipFile(zipname, 'a') as myzip: # extract+save script in tmp-dir: ...
[ "def", "editStartScript", "(", "self", ",", "index", ")", ":", "f", "=", "str", "(", "self", ".", "fileName", "(", "index", ")", ")", "if", "f", ".", "endswith", "(", "'.%s'", "%", "self", ".", "file_type", ")", ":", "zipname", "=", "str", "(", "...
open, edit, replace __main__.py
[ "open", "edit", "replace", "__main__", ".", "py" ]
train
https://github.com/radjkarl/appBase/blob/72b514e6dee7c083f01a2d0b2cc93d46df55bdcb/appbase/Launcher.py#L538-L555
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/browser/tiles/sidebar.py
BaseTile.status_messages
def status_messages(self): """ Returns status messages if any """ messages = IStatusMessage(self.request) m = messages.show() for item in m: item.id = idnormalizer.normalize(item.message) return m
python
def status_messages(self): """ Returns status messages if any """ messages = IStatusMessage(self.request) m = messages.show() for item in m: item.id = idnormalizer.normalize(item.message) return m
[ "def", "status_messages", "(", "self", ")", ":", "messages", "=", "IStatusMessage", "(", "self", ".", "request", ")", "m", "=", "messages", ".", "show", "(", ")", "for", "item", "in", "m", ":", "item", ".", "id", "=", "idnormalizer", ".", "normalize", ...
Returns status messages if any
[ "Returns", "status", "messages", "if", "any" ]
train
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/browser/tiles/sidebar.py#L35-L42
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/browser/tiles/sidebar.py
SidebarSettingsMembers.users
def users(self): """Get current users and add in any search results. :returns: a list of dicts with keys - id - title :rtype: list """ existing_users = self.existing_users() existing_user_ids = [x['id'] for x in existing_users] # Only add searc...
python
def users(self): """Get current users and add in any search results. :returns: a list of dicts with keys - id - title :rtype: list """ existing_users = self.existing_users() existing_user_ids = [x['id'] for x in existing_users] # Only add searc...
[ "def", "users", "(", "self", ")", ":", "existing_users", "=", "self", ".", "existing_users", "(", ")", "existing_user_ids", "=", "[", "x", "[", "'id'", "]", "for", "x", "in", "existing_users", "]", "# Only add search results that are not already members", "sharing...
Get current users and add in any search results. :returns: a list of dicts with keys - id - title :rtype: list
[ "Get", "current", "users", "and", "add", "in", "any", "search", "results", "." ]
train
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/browser/tiles/sidebar.py#L54-L73
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/browser/tiles/sidebar.py
Sidebar.children
def children(self): """ returns a list of dicts of items in the current context """ items = [] catalog = self.context.portal_catalog current_path = '/'.join(self.context.getPhysicalPath()) sidebar_search = self.request.get('sidebar-search', None) if sidebar_searc...
python
def children(self): """ returns a list of dicts of items in the current context """ items = [] catalog = self.context.portal_catalog current_path = '/'.join(self.context.getPhysicalPath()) sidebar_search = self.request.get('sidebar-search', None) if sidebar_searc...
[ "def", "children", "(", "self", ")", ":", "items", "=", "[", "]", "catalog", "=", "self", ".", "context", ".", "portal_catalog", "current_path", "=", "'/'", ".", "join", "(", "self", ".", "context", ".", "getPhysicalPath", "(", ")", ")", "sidebar_search"...
returns a list of dicts of items in the current context
[ "returns", "a", "list", "of", "dicts", "of", "items", "in", "the", "current", "context" ]
train
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/browser/tiles/sidebar.py#L223-L286
telminov/sw-python-utils
swutils/network.py
get_ip4
def get_ip4(): """ return all ip v4 address of current computer :return: """ addresses = [] shell_cmd = "ifconfig | awk '/inet addr/{print substr($2,6)}'" proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() ip_addresses = out.spli...
python
def get_ip4(): """ return all ip v4 address of current computer :return: """ addresses = [] shell_cmd = "ifconfig | awk '/inet addr/{print substr($2,6)}'" proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() ip_addresses = out.spli...
[ "def", "get_ip4", "(", ")", ":", "addresses", "=", "[", "]", "shell_cmd", "=", "\"ifconfig | awk '/inet addr/{print substr($2,6)}'\"", "proc", "=", "subprocess", ".", "Popen", "(", "[", "shell_cmd", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "she...
return all ip v4 address of current computer :return:
[ "return", "all", "ip", "v4", "address", "of", "current", "computer", ":", "return", ":" ]
train
https://github.com/telminov/sw-python-utils/blob/68f976122dd26a581b8d833c023f7f06542ca85c/swutils/network.py#L6-L20
todddeluca/fabvenv
fabvenv.py
Venv.create
def create(self): ''' On the remote host, use an installed virtualenv executable (e.g. the globally installed virtualenv on the path) to create a virutal environment. The venv directory MUST NOT already exist. ''' # require that the venv does not yet exist. if se...
python
def create(self): ''' On the remote host, use an installed virtualenv executable (e.g. the globally installed virtualenv on the path) to create a virutal environment. The venv directory MUST NOT already exist. ''' # require that the venv does not yet exist. if se...
[ "def", "create", "(", "self", ")", ":", "# require that the venv does not yet exist.", "if", "self", ".", "exists", "(", ")", ":", "raise", "Exception", "(", "'Path already exists. Abort creation. venv={}'", ".", "format", "(", "self", ".", "venv", ")", ")", "# cr...
On the remote host, use an installed virtualenv executable (e.g. the globally installed virtualenv on the path) to create a virutal environment. The venv directory MUST NOT already exist.
[ "On", "the", "remote", "host", "use", "an", "installed", "virtualenv", "executable", "(", "e", ".", "g", ".", "the", "globally", "installed", "virtualenv", "on", "the", "path", ")", "to", "create", "a", "virutal", "environment", ".", "The", "venv", "direct...
train
https://github.com/todddeluca/fabvenv/blob/ba0121412a7f47b3732d45b6cee42ac2b8737159/fabvenv.py#L54-L68
todddeluca/fabvenv
fabvenv.py
Venv.install
def install(self): ''' Use pip to install the requirements file. ''' remote_path = os.path.join(self.venv, 'requirements.txt') put(self.requirements, remote_path) run('{pip} install -r {requirements}'.format( pip=self.pip(), requirements=remote_path))
python
def install(self): ''' Use pip to install the requirements file. ''' remote_path = os.path.join(self.venv, 'requirements.txt') put(self.requirements, remote_path) run('{pip} install -r {requirements}'.format( pip=self.pip(), requirements=remote_path))
[ "def", "install", "(", "self", ")", ":", "remote_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "venv", ",", "'requirements.txt'", ")", "put", "(", "self", ".", "requirements", ",", "remote_path", ")", "run", "(", "'{pip} install -r {require...
Use pip to install the requirements file.
[ "Use", "pip", "to", "install", "the", "requirements", "file", "." ]
train
https://github.com/todddeluca/fabvenv/blob/ba0121412a7f47b3732d45b6cee42ac2b8737159/fabvenv.py#L70-L77
todddeluca/fabvenv
fabvenv.py
Venv.freeze
def freeze(self): ''' Use pip to freeze the requirements and save them to the local requirements.txt file. ''' remote_path = os.path.join(self.venv, 'requirements.txt') run('{} freeze > {}'.format(self.pip(), remote_path)) get(remote_path, self.requirements)
python
def freeze(self): ''' Use pip to freeze the requirements and save them to the local requirements.txt file. ''' remote_path = os.path.join(self.venv, 'requirements.txt') run('{} freeze > {}'.format(self.pip(), remote_path)) get(remote_path, self.requirements)
[ "def", "freeze", "(", "self", ")", ":", "remote_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "venv", ",", "'requirements.txt'", ")", "run", "(", "'{} freeze > {}'", ".", "format", "(", "self", ".", "pip", "(", ")", ",", "remote_path", ...
Use pip to freeze the requirements and save them to the local requirements.txt file.
[ "Use", "pip", "to", "freeze", "the", "requirements", "and", "save", "them", "to", "the", "local", "requirements", ".", "txt", "file", "." ]
train
https://github.com/todddeluca/fabvenv/blob/ba0121412a7f47b3732d45b6cee42ac2b8737159/fabvenv.py#L90-L97
todddeluca/fabvenv
fabvenv.py
Venv.remove
def remove(self): ''' Remove the virtual environment completely ''' print 'remove' if self.exists(): print 'cleaning', self.venv run('rm -rf {}'.format(self.venv))
python
def remove(self): ''' Remove the virtual environment completely ''' print 'remove' if self.exists(): print 'cleaning', self.venv run('rm -rf {}'.format(self.venv))
[ "def", "remove", "(", "self", ")", ":", "print", "'remove'", "if", "self", ".", "exists", "(", ")", ":", "print", "'cleaning'", ",", "self", ".", "venv", "run", "(", "'rm -rf {}'", ".", "format", "(", "self", ".", "venv", ")", ")" ]
Remove the virtual environment completely
[ "Remove", "the", "virtual", "environment", "completely" ]
train
https://github.com/todddeluca/fabvenv/blob/ba0121412a7f47b3732d45b6cee42ac2b8737159/fabvenv.py#L99-L106
todddeluca/fabvenv
fabvenv.py
Venv.venv_pth
def venv_pth(self, dirs): ''' Add the directories in `dirs` to the `sys.path`. A venv.pth file will be written in the site-packages dir of this virtualenv to add dirs to sys.path. dirs: a list of directories. ''' # Create venv.pth to add dirs to sys.path when us...
python
def venv_pth(self, dirs): ''' Add the directories in `dirs` to the `sys.path`. A venv.pth file will be written in the site-packages dir of this virtualenv to add dirs to sys.path. dirs: a list of directories. ''' # Create venv.pth to add dirs to sys.path when us...
[ "def", "venv_pth", "(", "self", ",", "dirs", ")", ":", "# Create venv.pth to add dirs to sys.path when using the virtualenv.", "text", "=", "StringIO", ".", "StringIO", "(", ")", "text", ".", "write", "(", "\"# Autogenerated file. Do not modify.\\n\"", ")", "for", "pat...
Add the directories in `dirs` to the `sys.path`. A venv.pth file will be written in the site-packages dir of this virtualenv to add dirs to sys.path. dirs: a list of directories.
[ "Add", "the", "directories", "in", "dirs", "to", "the", "sys", ".", "path", ".", "A", "venv", ".", "pth", "file", "will", "be", "written", "in", "the", "site", "-", "packages", "dir", "of", "this", "virtualenv", "to", "add", "dirs", "to", "sys", ".",...
train
https://github.com/todddeluca/fabvenv/blob/ba0121412a7f47b3732d45b6cee42ac2b8737159/fabvenv.py#L111-L124
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/adapters.py
PloneIntranetWorkspace.add_to_team
def add_to_team(self, **kw): """ We override this method to add our additional participation policy groups, as detailed in available_groups above """ group = self.context.participant_policy.title() data = kw.copy() if "groups" in data: data["groups"].a...
python
def add_to_team(self, **kw): """ We override this method to add our additional participation policy groups, as detailed in available_groups above """ group = self.context.participant_policy.title() data = kw.copy() if "groups" in data: data["groups"].a...
[ "def", "add_to_team", "(", "self", ",", "*", "*", "kw", ")", ":", "group", "=", "self", ".", "context", ".", "participant_policy", ".", "title", "(", ")", "data", "=", "kw", ".", "copy", "(", ")", "if", "\"groups\"", "in", "data", ":", "data", "[",...
We override this method to add our additional participation policy groups, as detailed in available_groups above
[ "We", "override", "this", "method", "to", "add", "our", "additional", "participation", "policy", "groups", "as", "detailed", "in", "available_groups", "above" ]
train
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/adapters.py#L32-L44
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/adapters.py
PloneIntranetWorkspace.group_for_policy
def group_for_policy(self, policy=None): """ Lookup the collective.workspace usergroup corresponding to the given policy :param policy: The value of the policy to lookup, defaults to the current policy :type policy: str """ if policy is Non...
python
def group_for_policy(self, policy=None): """ Lookup the collective.workspace usergroup corresponding to the given policy :param policy: The value of the policy to lookup, defaults to the current policy :type policy: str """ if policy is Non...
[ "def", "group_for_policy", "(", "self", ",", "policy", "=", "None", ")", ":", "if", "policy", "is", "None", ":", "policy", "=", "self", ".", "context", ".", "participant_policy", "return", "\"%s:%s\"", "%", "(", "policy", ".", "title", "(", ")", ",", "...
Lookup the collective.workspace usergroup corresponding to the given policy :param policy: The value of the policy to lookup, defaults to the current policy :type policy: str
[ "Lookup", "the", "collective", ".", "workspace", "usergroup", "corresponding", "to", "the", "given", "policy" ]
train
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/adapters.py#L46-L57
ploneintranet/ploneintranet.workspace
src/ploneintranet/workspace/adapters.py
WorkspaceLocalRoleAdapter.getRoles
def getRoles(self, principal_id): """ give an Owner who is also a 'selfpublisher', the reviewer role """ context = self.context current_roles = list(DefaultLocalRoleAdapter.getRoles( self, principal_id, )) # check we are not on the workspa...
python
def getRoles(self, principal_id): """ give an Owner who is also a 'selfpublisher', the reviewer role """ context = self.context current_roles = list(DefaultLocalRoleAdapter.getRoles( self, principal_id, )) # check we are not on the workspa...
[ "def", "getRoles", "(", "self", ",", "principal_id", ")", ":", "context", "=", "self", ".", "context", "current_roles", "=", "list", "(", "DefaultLocalRoleAdapter", ".", "getRoles", "(", "self", ",", "principal_id", ",", ")", ")", "# check we are not on the work...
give an Owner who is also a 'selfpublisher', the reviewer role
[ "give", "an", "Owner", "who", "is", "also", "a", "selfpublisher", "the", "reviewer", "role" ]
train
https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/adapters.py#L69-L90
AnimusPEXUS/wayround_i2p_carafe
wayround_i2p/carafe/carafe.py
Router.add
def add(self, method, path_settings, target): """ Simply creates Route and appends it to self.routes read Route class docs for parameters meaning """ self.routes.append(Route(method, path_settings, target)) return
python
def add(self, method, path_settings, target): """ Simply creates Route and appends it to self.routes read Route class docs for parameters meaning """ self.routes.append(Route(method, path_settings, target)) return
[ "def", "add", "(", "self", ",", "method", ",", "path_settings", ",", "target", ")", ":", "self", ".", "routes", ".", "append", "(", "Route", "(", "method", ",", "path_settings", ",", "target", ")", ")", "return" ]
Simply creates Route and appends it to self.routes read Route class docs for parameters meaning
[ "Simply", "creates", "Route", "and", "appends", "it", "to", "self", ".", "routes" ]
train
https://github.com/AnimusPEXUS/wayround_i2p_carafe/blob/c92a72e1f7b559ac0bd6dc0ce2716ce1e61a9c5e/wayround_i2p/carafe/carafe.py#L189-L196
AnimusPEXUS/wayround_i2p_carafe
wayround_i2p/carafe/carafe.py
Router.add2
def add2(self, target, path_settings, method): """ add() with reordered paameters """ return self.add(method, path_settings, target)
python
def add2(self, target, path_settings, method): """ add() with reordered paameters """ return self.add(method, path_settings, target)
[ "def", "add2", "(", "self", ",", "target", ",", "path_settings", ",", "method", ")", ":", "return", "self", ".", "add", "(", "method", ",", "path_settings", ",", "target", ")" ]
add() with reordered paameters
[ "add", "()", "with", "reordered", "paameters" ]
train
https://github.com/AnimusPEXUS/wayround_i2p_carafe/blob/c92a72e1f7b559ac0bd6dc0ce2716ce1e61a9c5e/wayround_i2p/carafe/carafe.py#L198-L202
AnimusPEXUS/wayround_i2p_carafe
wayround_i2p/carafe/carafe.py
Router.add3
def add3(self, target, path_settings=None, method='GET'): """ add() with reordered paameters """ if path_settings is None: path_settings = [] return self.add(method, path_settings, target)
python
def add3(self, target, path_settings=None, method='GET'): """ add() with reordered paameters """ if path_settings is None: path_settings = [] return self.add(method, path_settings, target)
[ "def", "add3", "(", "self", ",", "target", ",", "path_settings", "=", "None", ",", "method", "=", "'GET'", ")", ":", "if", "path_settings", "is", "None", ":", "path_settings", "=", "[", "]", "return", "self", ".", "add", "(", "method", ",", "path_setti...
add() with reordered paameters
[ "add", "()", "with", "reordered", "paameters" ]
train
https://github.com/AnimusPEXUS/wayround_i2p_carafe/blob/c92a72e1f7b559ac0bd6dc0ce2716ce1e61a9c5e/wayround_i2p/carafe/carafe.py#L204-L210
AnimusPEXUS/wayround_i2p_carafe
wayround_i2p/carafe/carafe.py
Router.wsgi_server_target
def wsgi_server_target(self, wsgi_environment, response_start): """ Searches route in self.routes and passes found target wsgi_environment, response_start and route_result. explanation for route_result is in Route class. result from ranning this method is simply passed from targ...
python
def wsgi_server_target(self, wsgi_environment, response_start): """ Searches route in self.routes and passes found target wsgi_environment, response_start and route_result. explanation for route_result is in Route class. result from ranning this method is simply passed from targ...
[ "def", "wsgi_server_target", "(", "self", ",", "wsgi_environment", ",", "response_start", ")", ":", "route_result", "=", "{", "}", "request_method", "=", "wsgi_environment", "[", "'REQUEST_METHOD'", "]", "path_info", "=", "wsgi_environment", "[", "'PATH_INFO'", "]",...
Searches route in self.routes and passes found target wsgi_environment, response_start and route_result. explanation for route_result is in Route class. result from ranning this method is simply passed from target to carafe calling fuctionality. see Carafe class for explanations to this...
[ "Searches", "route", "in", "self", ".", "routes", "and", "passes", "found", "target", "wsgi_environment", "response_start", "and", "route_result", ".", "explanation", "for", "route_result", "is", "in", "Route", "class", "." ]
train
https://github.com/AnimusPEXUS/wayround_i2p_carafe/blob/c92a72e1f7b559ac0bd6dc0ce2716ce1e61a9c5e/wayround_i2p/carafe/carafe.py#L212-L362
gnahckire/ciscospark-py
ciscospark/core.py
Auth.clean_query_Dict
def clean_query_Dict(cls, query_Dict): """removes NoneTypes from the dict """ return {k: v for k, v in query_Dict.items() if v}
python
def clean_query_Dict(cls, query_Dict): """removes NoneTypes from the dict """ return {k: v for k, v in query_Dict.items() if v}
[ "def", "clean_query_Dict", "(", "cls", ",", "query_Dict", ")", ":", "return", "{", "k", ":", "v", "for", "k", ",", "v", "in", "query_Dict", ".", "items", "(", ")", "if", "v", "}" ]
removes NoneTypes from the dict
[ "removes", "NoneTypes", "from", "the", "dict" ]
train
https://github.com/gnahckire/ciscospark-py/blob/73b551c658f8f48f3a2fc1f1d891fb47883d5561/ciscospark/core.py#L47-L50
gnahckire/ciscospark-py
ciscospark/core.py
Rooms.list
def list(self, teamId=None, rType=None, maxResults=C.MAX_RESULT_DEFAULT, limit=C.ALL): """ rType can be DIRECT or GROUP """ queryParams = {'teamId': teamId, 'type': rType, 'max': maxResults} queryParams = self.clean_query_Dict(queryParams) ret = self.send_request(C.GET, s...
python
def list(self, teamId=None, rType=None, maxResults=C.MAX_RESULT_DEFAULT, limit=C.ALL): """ rType can be DIRECT or GROUP """ queryParams = {'teamId': teamId, 'type': rType, 'max': maxResults} queryParams = self.clean_query_Dict(queryParams) ret = self.send_request(C.GET, s...
[ "def", "list", "(", "self", ",", "teamId", "=", "None", ",", "rType", "=", "None", ",", "maxResults", "=", "C", ".", "MAX_RESULT_DEFAULT", ",", "limit", "=", "C", ".", "ALL", ")", ":", "queryParams", "=", "{", "'teamId'", ":", "teamId", ",", "'type'"...
rType can be DIRECT or GROUP
[ "rType", "can", "be", "DIRECT", "or", "GROUP" ]
train
https://github.com/gnahckire/ciscospark-py/blob/73b551c658f8f48f3a2fc1f1d891fb47883d5561/ciscospark/core.py#L97-L106
gnahckire/ciscospark-py
ciscospark/core.py
Rooms.create
def create(self, title): """ :param title: UTF-8 string that can contain emoji bytes http://apps.timwhitlock.info/emoji/tables/unicode """ return self.send_request(C.POST, self.end, data={'title':title})
python
def create(self, title): """ :param title: UTF-8 string that can contain emoji bytes http://apps.timwhitlock.info/emoji/tables/unicode """ return self.send_request(C.POST, self.end, data={'title':title})
[ "def", "create", "(", "self", ",", "title", ")", ":", "return", "self", ".", "send_request", "(", "C", ".", "POST", ",", "self", ".", "end", ",", "data", "=", "{", "'title'", ":", "title", "}", ")" ]
:param title: UTF-8 string that can contain emoji bytes http://apps.timwhitlock.info/emoji/tables/unicode
[ ":", "param", "title", ":", "UTF", "-", "8", "string", "that", "can", "contain", "emoji", "bytes", "http", ":", "//", "apps", ".", "timwhitlock", ".", "info", "/", "emoji", "/", "tables", "/", "unicode" ]
train
https://github.com/gnahckire/ciscospark-py/blob/73b551c658f8f48f3a2fc1f1d891fb47883d5561/ciscospark/core.py#L108-L113
townsenddw/jhubctl
jhubctl/utils.py
get_flag_args
def get_flag_args(**options): """Build a list of flags.""" flags = [] for key, value in options.items(): # Build short flags. if len(key) == 1: flag = f'-{key}' # Built long flags. else: flag = f'--{key}' flags = flags + [flag, value] retur...
python
def get_flag_args(**options): """Build a list of flags.""" flags = [] for key, value in options.items(): # Build short flags. if len(key) == 1: flag = f'-{key}' # Built long flags. else: flag = f'--{key}' flags = flags + [flag, value] retur...
[ "def", "get_flag_args", "(", "*", "*", "options", ")", ":", "flags", "=", "[", "]", "for", "key", ",", "value", "in", "options", ".", "items", "(", ")", ":", "# Build short flags.", "if", "len", "(", "key", ")", "==", "1", ":", "flag", "=", "f'-{ke...
Build a list of flags.
[ "Build", "a", "list", "of", "flags", "." ]
train
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/utils.py#L12-L23
townsenddw/jhubctl
jhubctl/utils.py
kubectl
def kubectl(*args, input=None, **flags): """Simple wrapper to kubectl.""" # Build command line call. line = ['kubectl'] + list(args) line = line + get_flag_args(**flags) if input is not None: line = line + ['-f', '-'] # Run subprocess output = subprocess.run( line, in...
python
def kubectl(*args, input=None, **flags): """Simple wrapper to kubectl.""" # Build command line call. line = ['kubectl'] + list(args) line = line + get_flag_args(**flags) if input is not None: line = line + ['-f', '-'] # Run subprocess output = subprocess.run( line, in...
[ "def", "kubectl", "(", "*", "args", ",", "input", "=", "None", ",", "*", "*", "flags", ")", ":", "# Build command line call.", "line", "=", "[", "'kubectl'", "]", "+", "list", "(", "args", ")", "line", "=", "line", "+", "get_flag_args", "(", "*", "*"...
Simple wrapper to kubectl.
[ "Simple", "wrapper", "to", "kubectl", "." ]
train
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/utils.py#L26-L40
townsenddw/jhubctl
jhubctl/utils.py
get_template
def get_template(template_path, **parameters): """Use jinja2 to fill in template with given parameters. Parameters ---------- template_path : str Name of template. Keyword Arguments ----------------- Parameters passed into the jinja2 template Returns ------- output...
python
def get_template(template_path, **parameters): """Use jinja2 to fill in template with given parameters. Parameters ---------- template_path : str Name of template. Keyword Arguments ----------------- Parameters passed into the jinja2 template Returns ------- output...
[ "def", "get_template", "(", "template_path", ",", "*", "*", "parameters", ")", ":", "path", "=", "sanitize_path", "(", "template_path", ")", "template_file", "=", "path", ".", "name", "template_dir", "=", "str", "(", "path", ".", "parent", ")", "## Apply ARN...
Use jinja2 to fill in template with given parameters. Parameters ---------- template_path : str Name of template. Keyword Arguments ----------------- Parameters passed into the jinja2 template Returns ------- output_text : str Template as a string filled in wit...
[ "Use", "jinja2", "to", "fill", "in", "template", "with", "given", "parameters", ".", "Parameters", "----------", "template_path", ":", "str", "Name", "of", "template", "." ]
train
https://github.com/townsenddw/jhubctl/blob/c8c20f86a16e9d01dd90e4607d81423417cc773b/jhubctl/utils.py#L70-L98
openpermissions/perch
perch/organisation.py
cleanString
def cleanString(someText): """ remove special characters and spaces from string and convert to lowercase """ ret = '' if someText is not None: ret = filter(unicode.isalnum, someText.lower()) return ret
python
def cleanString(someText): """ remove special characters and spaces from string and convert to lowercase """ ret = '' if someText is not None: ret = filter(unicode.isalnum, someText.lower()) return ret
[ "def", "cleanString", "(", "someText", ")", ":", "ret", "=", "''", "if", "someText", "is", "not", "None", ":", "ret", "=", "filter", "(", "unicode", ".", "isalnum", ",", "someText", ".", "lower", "(", ")", ")", "return", "ret" ]
remove special characters and spaces from string and convert to lowercase
[ "remove", "special", "characters", "and", "spaces", "from", "string", "and", "convert", "to", "lowercase" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L51-L59
openpermissions/perch
perch/organisation.py
group_permissions
def group_permissions(permissions): """ Groups a permissions list Returns a dictionary, with permission types as keys and sets of entities with access to the resource as values, e.g.: { 'organisation_id': { 'org1': set(['rw', 'r', 'w']), 'org2': set(...
python
def group_permissions(permissions): """ Groups a permissions list Returns a dictionary, with permission types as keys and sets of entities with access to the resource as values, e.g.: { 'organisation_id': { 'org1': set(['rw', 'r', 'w']), 'org2': set(...
[ "def", "group_permissions", "(", "permissions", ")", ":", "groups", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "set", ")", ")", "for", "p", "in", "sorted", "(", "permissions", ",", "key", "=", "itemgetter", "(", "'type'", ")", ")", ":", ...
Groups a permissions list Returns a dictionary, with permission types as keys and sets of entities with access to the resource as values, e.g.: { 'organisation_id': { 'org1': set(['rw', 'r', 'w']), 'org2': set(['-']), 'org3': set(['r', 'w']),...
[ "Groups", "a", "permissions", "list" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L288-L326
openpermissions/perch
perch/organisation.py
generate_secret
def generate_secret(length=30): """ Generate an ASCII secret using random.SysRandom Based on oauthlib's common.generate_token function """ rand = random.SystemRandom() ascii_characters = string.ascii_letters + string.digits return ''.join(rand.choice(ascii_characters) for _ in range(length...
python
def generate_secret(length=30): """ Generate an ASCII secret using random.SysRandom Based on oauthlib's common.generate_token function """ rand = random.SystemRandom() ascii_characters = string.ascii_letters + string.digits return ''.join(rand.choice(ascii_characters) for _ in range(length...
[ "def", "generate_secret", "(", "length", "=", "30", ")", ":", "rand", "=", "random", ".", "SystemRandom", "(", ")", "ascii_characters", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "return", "''", ".", "join", "(", "rand", ".", "cho...
Generate an ASCII secret using random.SysRandom Based on oauthlib's common.generate_token function
[ "Generate", "an", "ASCII", "secret", "using", "random", ".", "SysRandom" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L754-L763
openpermissions/perch
perch/organisation.py
Organisation.all
def all(cls, state=None, include_deactivated=False): """ Get all organisations :param state: State of organisation :param include_deactivated: Flag to include deactivated :returns: list of Organisation instances :raises: SocketError, CouchException """ if...
python
def all(cls, state=None, include_deactivated=False): """ Get all organisations :param state: State of organisation :param include_deactivated: Flag to include deactivated :returns: list of Organisation instances :raises: SocketError, CouchException """ if...
[ "def", "all", "(", "cls", ",", "state", "=", "None", ",", "include_deactivated", "=", "False", ")", ":", "if", "state", "and", "state", "not", "in", "validators", ".", "VALID_STATES", ":", "raise", "exceptions", ".", "ValidationError", "(", "'Invalid \"state...
Get all organisations :param state: State of organisation :param include_deactivated: Flag to include deactivated :returns: list of Organisation instances :raises: SocketError, CouchException
[ "Get", "all", "organisations" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L176-L195
openpermissions/perch
perch/organisation.py
Organisation.user_organisations
def user_organisations(cls, user_id, state=None, include_deactivated=False): """ Get organisations that the user has joined :param user_id: the user ID :param state: the user's "join" state :param include_deactivated: Include deactivated resources in response :returns: l...
python
def user_organisations(cls, user_id, state=None, include_deactivated=False): """ Get organisations that the user has joined :param user_id: the user ID :param state: the user's "join" state :param include_deactivated: Include deactivated resources in response :returns: l...
[ "def", "user_organisations", "(", "cls", ",", "user_id", ",", "state", "=", "None", ",", "include_deactivated", "=", "False", ")", ":", "if", "state", "and", "state", "not", "in", "validators", ".", "VALID_STATES", ":", "raise", "exceptions", ".", "Validatio...
Get organisations that the user has joined :param user_id: the user ID :param state: the user's "join" state :param include_deactivated: Include deactivated resources in response :returns: list of Organisation instances :raises: SocketError, CouchException
[ "Get", "organisations", "that", "the", "user", "has", "joined" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L199-L219
openpermissions/perch
perch/organisation.py
Organisation.can_update
def can_update(self, user, **data): """ Sys admins can always update an organisation. Organisation admins and creators can update, but may not update the following fields: - star_rating :param user: a User :param data: data that the user wants to update :re...
python
def can_update(self, user, **data): """ Sys admins can always update an organisation. Organisation admins and creators can update, but may not update the following fields: - star_rating :param user: a User :param data: data that the user wants to update :re...
[ "def", "can_update", "(", "self", ",", "user", ",", "*", "*", "data", ")", ":", "if", "user", ".", "is_admin", "(", ")", ":", "raise", "Return", "(", "(", "True", ",", "set", "(", "[", "]", ")", ")", ")", "org_admin", "=", "user", ".", "is_org_...
Sys admins can always update an organisation. Organisation admins and creators can update, but may not update the following fields: - star_rating :param user: a User :param data: data that the user wants to update :returns: bool, set of fields that the user was not authori...
[ "Sys", "admins", "can", "always", "update", "an", "organisation", "." ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L233-L257
openpermissions/perch
perch/organisation.py
Organisation.can_approve
def can_approve(self, user, **data): """ Only sys admins can approve an organisation, or a reseller sending pre_verified=true :param user: a User :param data: data that the user wants to update """ is_admin = user.is_admin() is_reseller_preverifying = user.is_rese...
python
def can_approve(self, user, **data): """ Only sys admins can approve an organisation, or a reseller sending pre_verified=true :param user: a User :param data: data that the user wants to update """ is_admin = user.is_admin() is_reseller_preverifying = user.is_rese...
[ "def", "can_approve", "(", "self", ",", "user", ",", "*", "*", "data", ")", ":", "is_admin", "=", "user", ".", "is_admin", "(", ")", "is_reseller_preverifying", "=", "user", ".", "is_reseller", "(", ")", "and", "data", ".", "get", "(", "'pre_verified'", ...
Only sys admins can approve an organisation, or a reseller sending pre_verified=true :param user: a User :param data: data that the user wants to update
[ "Only", "sys", "admins", "can", "approve", "an", "organisation", "or", "a", "reseller", "sending", "pre_verified", "=", "true", ":", "param", "user", ":", "a", "User", ":", "param", "data", ":", "data", "that", "the", "user", "wants", "to", "update" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L260-L268
openpermissions/perch
perch/organisation.py
Service.check_unique
def check_unique(self): """Check the service's name and location are unique""" errors = [] service_id = getattr(self, 'id', None) fields = [('location', views.service_location), ('name', views.service_name)] for field, view in fields: value = getatt...
python
def check_unique(self): """Check the service's name and location are unique""" errors = [] service_id = getattr(self, 'id', None) fields = [('location', views.service_location), ('name', views.service_name)] for field, view in fields: value = getatt...
[ "def", "check_unique", "(", "self", ")", ":", "errors", "=", "[", "]", "service_id", "=", "getattr", "(", "self", ",", "'id'", ",", "None", ")", "fields", "=", "[", "(", "'location'", ",", "views", ".", "service_location", ")", ",", "(", "'name'", ",...
Check the service's name and location are unique
[ "Check", "the", "service", "s", "name", "and", "location", "are", "unique" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L364-L383
openpermissions/perch
perch/organisation.py
Service.clean
def clean(self, user=None): """Remove internal fields""" doc = self._resource internal_fields = deepcopy(self.internal_fields) if user is None or not user.is_user(self.organisation_id): internal_fields.append('permissions') result = {k: v for k, v in doc.iteritems() ...
python
def clean(self, user=None): """Remove internal fields""" doc = self._resource internal_fields = deepcopy(self.internal_fields) if user is None or not user.is_user(self.organisation_id): internal_fields.append('permissions') result = {k: v for k, v in doc.iteritems() ...
[ "def", "clean", "(", "self", ",", "user", "=", "None", ")", ":", "doc", "=", "self", ".", "_resource", "internal_fields", "=", "deepcopy", "(", "self", ".", "internal_fields", ")", "if", "user", "is", "None", "or", "not", "user", ".", "is_user", "(", ...
Remove internal fields
[ "Remove", "internal", "fields" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L385-L394
openpermissions/perch
perch/organisation.py
Service.get_by_location
def get_by_location(cls, location, include_deactivated=False): """Get a service by it's location""" if include_deactivated: view = views.service_location else: view = views.active_service_location result = yield view.first(key=location, include_docs=True) ...
python
def get_by_location(cls, location, include_deactivated=False): """Get a service by it's location""" if include_deactivated: view = views.service_location else: view = views.active_service_location result = yield view.first(key=location, include_docs=True) ...
[ "def", "get_by_location", "(", "cls", ",", "location", ",", "include_deactivated", "=", "False", ")", ":", "if", "include_deactivated", ":", "view", "=", "views", ".", "service_location", "else", ":", "view", "=", "views", ".", "active_service_location", "result...
Get a service by it's location
[ "Get", "a", "service", "by", "it", "s", "location" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L398-L408
openpermissions/perch
perch/organisation.py
Service.all
def all(cls, service_type=None, organisation_id=None, include_deactivated=False): """ Get all resources :param service_type: Filter by service type :param organisation_id: Filter by organisation id :param include_deactivated: Flag to include deactivated Services :return...
python
def all(cls, service_type=None, organisation_id=None, include_deactivated=False): """ Get all resources :param service_type: Filter by service type :param organisation_id: Filter by organisation id :param include_deactivated: Flag to include deactivated Services :return...
[ "def", "all", "(", "cls", ",", "service_type", "=", "None", ",", "organisation_id", "=", "None", ",", "include_deactivated", "=", "False", ")", ":", "if", "include_deactivated", ":", "resources", "=", "yield", "views", ".", "services", ".", "get", "(", "ke...
Get all resources :param service_type: Filter by service type :param organisation_id: Filter by organisation id :param include_deactivated: Flag to include deactivated Services :returns: list of Resource instances :raises: SocketError, CouchException
[ "Get", "all", "resources" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L412-L429
openpermissions/perch
perch/organisation.py
Service.can_approve
def can_approve(self, user, **data): """ Only sys admins can approve a service :param user: a User :param data: data that the user wants to update """ is_external = data.get('service_type', self.service_type) == 'external' raise Return(user.is_admin() or is_extern...
python
def can_approve(self, user, **data): """ Only sys admins can approve a service :param user: a User :param data: data that the user wants to update """ is_external = data.get('service_type', self.service_type) == 'external' raise Return(user.is_admin() or is_extern...
[ "def", "can_approve", "(", "self", ",", "user", ",", "*", "*", "data", ")", ":", "is_external", "=", "data", ".", "get", "(", "'service_type'", ",", "self", ".", "service_type", ")", "==", "'external'", "raise", "Return", "(", "user", ".", "is_admin", ...
Only sys admins can approve a service :param user: a User :param data: data that the user wants to update
[ "Only", "sys", "admins", "can", "approve", "a", "service", ":", "param", "user", ":", "a", "User", ":", "param", "data", ":", "data", "that", "the", "user", "wants", "to", "update" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L465-L472
openpermissions/perch
perch/organisation.py
Service.can_update
def can_update(self, user, **kwargs): """Org admins may not update organisation_id or service_type""" if user.is_admin(): raise Return((True, set([]))) is_creator = self.created_by == user.id if not (user.is_org_admin(self.organisation_id) or is_creator): raise R...
python
def can_update(self, user, **kwargs): """Org admins may not update organisation_id or service_type""" if user.is_admin(): raise Return((True, set([]))) is_creator = self.created_by == user.id if not (user.is_org_admin(self.organisation_id) or is_creator): raise R...
[ "def", "can_update", "(", "self", ",", "user", ",", "*", "*", "kwargs", ")", ":", "if", "user", ".", "is_admin", "(", ")", ":", "raise", "Return", "(", "(", "True", ",", "set", "(", "[", "]", ")", ")", ")", "is_creator", "=", "self", ".", "crea...
Org admins may not update organisation_id or service_type
[ "Org", "admins", "may", "not", "update", "organisation_id", "or", "service_type" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L475-L488
openpermissions/perch
perch/organisation.py
Service.authenticate
def authenticate(cls, client_id, secret): """ Authenticate a client using it's secret :param client_id: the client / service ID :param secret: the client secret :returns: a Service instance """ result = yield views.oauth_client.get(key=[secret, client_id]) ...
python
def authenticate(cls, client_id, secret): """ Authenticate a client using it's secret :param client_id: the client / service ID :param secret: the client secret :returns: a Service instance """ result = yield views.oauth_client.get(key=[secret, client_id]) ...
[ "def", "authenticate", "(", "cls", ",", "client_id", ",", "secret", ")", ":", "result", "=", "yield", "views", ".", "oauth_client", ".", "get", "(", "key", "=", "[", "secret", ",", "client_id", "]", ")", "if", "not", "result", "[", "'rows'", "]", ":"...
Authenticate a client using it's secret :param client_id: the client / service ID :param secret: the client secret :returns: a Service instance
[ "Authenticate", "a", "client", "using", "it", "s", "secret" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L492-L505
openpermissions/perch
perch/organisation.py
Service.authorized
def authorized(self, requested_access, resource): """ Check whether the service is authorized to access the resource :param requested_access: "r", "w", or "rw" :param resource: a Resource or SubResource with "permissions" attribute :returns: True if has access, False otherwise ...
python
def authorized(self, requested_access, resource): """ Check whether the service is authorized to access the resource :param requested_access: "r", "w", or "rw" :param resource: a Resource or SubResource with "permissions" attribute :returns: True if has access, False otherwise ...
[ "def", "authorized", "(", "self", ",", "requested_access", ",", "resource", ")", ":", "if", "{", "self", ".", "state", ",", "resource", ".", "state", "}", "!=", "{", "State", ".", "approved", "}", ":", "return", "False", "permissions", "=", "group_permis...
Check whether the service is authorized to access the resource :param requested_access: "r", "w", or "rw" :param resource: a Resource or SubResource with "permissions" attribute :returns: True if has access, False otherwise
[ "Check", "whether", "the", "service", "is", "authorized", "to", "access", "the", "resource" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L507-L530
openpermissions/perch
perch/organisation.py
Repository.validate
def validate(self): """Validate the resource""" if not self._resource.get('permissions'): self.permissions = self.default_permissions try: # update _resource so have default values from the schema self._resource = self.schema(self._resource) except Mu...
python
def validate(self): """Validate the resource""" if not self._resource.get('permissions'): self.permissions = self.default_permissions try: # update _resource so have default values from the schema self._resource = self.schema(self._resource) except Mu...
[ "def", "validate", "(", "self", ")", ":", "if", "not", "self", ".", "_resource", ".", "get", "(", "'permissions'", ")", ":", "self", ".", "permissions", "=", "self", ".", "default_permissions", "try", ":", "# update _resource so have default values from the schema...
Validate the resource
[ "Validate", "the", "resource" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L604-L617
openpermissions/perch
perch/organisation.py
Repository.check_service
def check_service(self): """Check the service exists and is a repository service""" try: service = yield Service.get(self.service_id) except couch.NotFound: raise exceptions.ValidationError('Service {} not found' .format(self.s...
python
def check_service(self): """Check the service exists and is a repository service""" try: service = yield Service.get(self.service_id) except couch.NotFound: raise exceptions.ValidationError('Service {} not found' .format(self.s...
[ "def", "check_service", "(", "self", ")", ":", "try", ":", "service", "=", "yield", "Service", ".", "get", "(", "self", ".", "service_id", ")", "except", "couch", ".", "NotFound", ":", "raise", "exceptions", ".", "ValidationError", "(", "'Service {} not foun...
Check the service exists and is a repository service
[ "Check", "the", "service", "exists", "and", "is", "a", "repository", "service" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L620-L634
openpermissions/perch
perch/organisation.py
Repository.check_unique
def check_unique(self): """Check the repository's name is unique""" result = yield views.repository_name.values(key=self.name) repo_id = getattr(self, 'id', None) repos = {x for x in result if x != repo_id and x} if repos: raise exceptions.ValidationError( ...
python
def check_unique(self): """Check the repository's name is unique""" result = yield views.repository_name.values(key=self.name) repo_id = getattr(self, 'id', None) repos = {x for x in result if x != repo_id and x} if repos: raise exceptions.ValidationError( ...
[ "def", "check_unique", "(", "self", ")", ":", "result", "=", "yield", "views", ".", "repository_name", ".", "values", "(", "key", "=", "self", ".", "name", ")", "repo_id", "=", "getattr", "(", "self", ",", "'id'", ",", "None", ")", "repos", "=", "{",...
Check the repository's name is unique
[ "Check", "the", "repository", "s", "name", "is", "unique" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L637-L645
openpermissions/perch
perch/organisation.py
Repository.can_approve
def can_approve(self, user, **data): """ Admins of repository service or sys admins can approve a repository :param user: a User :param data: data that the user wants to update """ service_id = data.get('service_id', self.service_id) try: service = yi...
python
def can_approve(self, user, **data): """ Admins of repository service or sys admins can approve a repository :param user: a User :param data: data that the user wants to update """ service_id = data.get('service_id', self.service_id) try: service = yi...
[ "def", "can_approve", "(", "self", ",", "user", ",", "*", "*", "data", ")", ":", "service_id", "=", "data", ".", "get", "(", "'service_id'", ",", "self", ".", "service_id", ")", "try", ":", "service", "=", "yield", "Service", ".", "get", "(", "servic...
Admins of repository service or sys admins can approve a repository :param user: a User :param data: data that the user wants to update
[ "Admins", "of", "repository", "service", "or", "sys", "admins", "can", "approve", "a", "repository", ":", "param", "user", ":", "a", "User", ":", "param", "data", ":", "data", "that", "the", "user", "wants", "to", "update" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L658-L677
openpermissions/perch
perch/organisation.py
Repository.can_update
def can_update(self, user, **kwargs): """ Sys admin's can change anything If the user is an organisation administrator or created the repository, they may change any field other than "organisation_id" If the user is a service administrator the user may change the "state" ...
python
def can_update(self, user, **kwargs): """ Sys admin's can change anything If the user is an organisation administrator or created the repository, they may change any field other than "organisation_id" If the user is a service administrator the user may change the "state" ...
[ "def", "can_update", "(", "self", ",", "user", ",", "*", "*", "kwargs", ")", ":", "if", "user", ".", "is_admin", "(", ")", ":", "raise", "Return", "(", "(", "True", ",", "set", "(", "[", "]", ")", ")", ")", "is_creator", "=", "self", ".", "crea...
Sys admin's can change anything If the user is an organisation administrator or created the repository, they may change any field other than "organisation_id" If the user is a service administrator the user may change the "state" but no other fields.
[ "Sys", "admin", "s", "can", "change", "anything" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L680-L717
openpermissions/perch
perch/organisation.py
Repository.with_relations
def with_relations(self, user=None): """ Return a cleaned dictionary including relations :returns: a Repository instance """ repository = self.clean(user=user) try: parent = yield self.get_parent() repository['organisation'] = parent.clean() ...
python
def with_relations(self, user=None): """ Return a cleaned dictionary including relations :returns: a Repository instance """ repository = self.clean(user=user) try: parent = yield self.get_parent() repository['organisation'] = parent.clean() ...
[ "def", "with_relations", "(", "self", ",", "user", "=", "None", ")", ":", "repository", "=", "self", ".", "clean", "(", "user", "=", "user", ")", "try", ":", "parent", "=", "yield", "self", ".", "get_parent", "(", ")", "repository", "[", "'organisation...
Return a cleaned dictionary including relations :returns: a Repository instance
[ "Return", "a", "cleaned", "dictionary", "including", "relations" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L725-L751
openpermissions/perch
perch/organisation.py
OAuthSecret.client_secrets
def client_secrets(cls, client_id): """ Get the client's secrets using the client_id :param client_id: the client ID, e.g. a service ID :returns: list OAuthSecret instances """ secrets = yield cls.view.get(key=client_id, include_docs=True) raise Return([cls(**sec...
python
def client_secrets(cls, client_id): """ Get the client's secrets using the client_id :param client_id: the client ID, e.g. a service ID :returns: list OAuthSecret instances """ secrets = yield cls.view.get(key=client_id, include_docs=True) raise Return([cls(**sec...
[ "def", "client_secrets", "(", "cls", ",", "client_id", ")", ":", "secrets", "=", "yield", "cls", ".", "view", ".", "get", "(", "key", "=", "client_id", ",", "include_docs", "=", "True", ")", "raise", "Return", "(", "[", "cls", "(", "*", "*", "secret"...
Get the client's secrets using the client_id :param client_id: the client ID, e.g. a service ID :returns: list OAuthSecret instances
[ "Get", "the", "client", "s", "secrets", "using", "the", "client_id" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L801-L809
openpermissions/perch
perch/organisation.py
OAuthSecret.delete_all_secrets
def delete_all_secrets(cls, user, client_id): """Delete all of the client's credentials""" can_delete = yield cls(client_id=client_id).can_delete(user) if not can_delete: raise exceptions.Unauthorized('User may not delete {} secrets' .format(...
python
def delete_all_secrets(cls, user, client_id): """Delete all of the client's credentials""" can_delete = yield cls(client_id=client_id).can_delete(user) if not can_delete: raise exceptions.Unauthorized('User may not delete {} secrets' .format(...
[ "def", "delete_all_secrets", "(", "cls", ",", "user", ",", "client_id", ")", ":", "can_delete", "=", "yield", "cls", "(", "client_id", "=", "client_id", ")", ".", "can_delete", "(", "user", ")", "if", "not", "can_delete", ":", "raise", "exceptions", ".", ...
Delete all of the client's credentials
[ "Delete", "all", "of", "the", "client", "s", "credentials" ]
train
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/organisation.py#L813-L831
OpenVolunteeringPlatform/django-ovp-core
ovp_core/emails.py
ContactFormMail.sendContact
def sendContact(self, context={}): """ Send contact form message to single or multiple recipients """ for recipient in self.recipients: super(ContactFormMail, self).__init__(recipient, self.async) self.sendEmail('contactForm', 'New contact form message', context)
python
def sendContact(self, context={}): """ Send contact form message to single or multiple recipients """ for recipient in self.recipients: super(ContactFormMail, self).__init__(recipient, self.async) self.sendEmail('contactForm', 'New contact form message', context)
[ "def", "sendContact", "(", "self", ",", "context", "=", "{", "}", ")", ":", "for", "recipient", "in", "self", ".", "recipients", ":", "super", "(", "ContactFormMail", ",", "self", ")", ".", "__init__", "(", "recipient", ",", "self", ".", "async", ")", ...
Send contact form message to single or multiple recipients
[ "Send", "contact", "form", "message", "to", "single", "or", "multiple", "recipients" ]
train
https://github.com/OpenVolunteeringPlatform/django-ovp-core/blob/c81b868a0a4b317f7b1ec0718cabc34f7794dd20/ovp_core/emails.py#L75-L81
b3j0f/utils
b3j0f/utils/proxy.py
proxify_elt
def proxify_elt(elt, bases=None, _dict=None, public=False): """Proxify input elt. :param elt: elt to proxify. :param bases: elt class base classes. If None, use elt type. :param dict _dict: specific elt class content to use. :param bool public: if True (default False), proxify only public members ...
python
def proxify_elt(elt, bases=None, _dict=None, public=False): """Proxify input elt. :param elt: elt to proxify. :param bases: elt class base classes. If None, use elt type. :param dict _dict: specific elt class content to use. :param bool public: if True (default False), proxify only public members ...
[ "def", "proxify_elt", "(", "elt", ",", "bases", "=", "None", ",", "_dict", "=", "None", ",", "public", "=", "False", ")", ":", "# ensure _dict is a dictionary", "proxy_dict", "=", "{", "}", "if", "_dict", "is", "None", "else", "_dict", ".", "copy", "(", ...
Proxify input elt. :param elt: elt to proxify. :param bases: elt class base classes. If None, use elt type. :param dict _dict: specific elt class content to use. :param bool public: if True (default False), proxify only public members (where name starts with the character '_'). :return: pro...
[ "Proxify", "input", "elt", "." ]
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/proxy.py#L80-L171
b3j0f/utils
b3j0f/utils/proxy.py
proxify_routine
def proxify_routine(routine, impl=None): """Proxify a routine with input impl. :param routine: routine to proxify. :param impl: new impl to use. If None, use routine. """ # init impl impl = routine if impl is None else impl is_method = ismethod(routine) if is_method: function ...
python
def proxify_routine(routine, impl=None): """Proxify a routine with input impl. :param routine: routine to proxify. :param impl: new impl to use. If None, use routine. """ # init impl impl = routine if impl is None else impl is_method = ismethod(routine) if is_method: function ...
[ "def", "proxify_routine", "(", "routine", ",", "impl", "=", "None", ")", ":", "# init impl", "impl", "=", "routine", "if", "impl", "is", "None", "else", "impl", "is_method", "=", "ismethod", "(", "routine", ")", "if", "is_method", ":", "function", "=", "...
Proxify a routine with input impl. :param routine: routine to proxify. :param impl: new impl to use. If None, use routine.
[ "Proxify", "a", "routine", "with", "input", "impl", "." ]
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/proxy.py#L174-L259
b3j0f/utils
b3j0f/utils/proxy.py
_compilecode
def _compilecode(function, name, impl, args, varargs, kwargs): """Get generated code. :return: function proxy generated code. :rtype: str """ newcodestr, generatedname, impl_name = _generatecode( function=function, name=name, impl=impl, args=args, varargs=varargs, kwargs=kwargs ...
python
def _compilecode(function, name, impl, args, varargs, kwargs): """Get generated code. :return: function proxy generated code. :rtype: str """ newcodestr, generatedname, impl_name = _generatecode( function=function, name=name, impl=impl, args=args, varargs=varargs, kwargs=kwargs ...
[ "def", "_compilecode", "(", "function", ",", "name", ",", "impl", ",", "args", ",", "varargs", ",", "kwargs", ")", ":", "newcodestr", ",", "generatedname", ",", "impl_name", "=", "_generatecode", "(", "function", "=", "function", ",", "name", "=", "name", ...
Get generated code. :return: function proxy generated code. :rtype: str
[ "Get", "generated", "code", "." ]
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/proxy.py#L262-L333
b3j0f/utils
b3j0f/utils/proxy.py
get_proxy
def get_proxy(elt, bases=None, _dict=None): """Get proxy from an elt. If elt implements the proxy generator method (named ``__getproxy__``), use it instead of using this module functions. :param elt: elt to proxify. :type elt: object or function/method :param bases: base types to enrich in the...
python
def get_proxy(elt, bases=None, _dict=None): """Get proxy from an elt. If elt implements the proxy generator method (named ``__getproxy__``), use it instead of using this module functions. :param elt: elt to proxify. :type elt: object or function/method :param bases: base types to enrich in the...
[ "def", "get_proxy", "(", "elt", ",", "bases", "=", "None", ",", "_dict", "=", "None", ")", ":", "# try to find an instance proxy generator", "proxygenerator", "=", "getattr", "(", "elt", ",", "__GETPROXY__", ",", "None", ")", "# if a proxy generator is not found, us...
Get proxy from an elt. If elt implements the proxy generator method (named ``__getproxy__``), use it instead of using this module functions. :param elt: elt to proxify. :type elt: object or function/method :param bases: base types to enrich in the result cls if not None. :param _dict: class me...
[ "Get", "proxy", "from", "an", "elt", "." ]
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/proxy.py#L414-L440
b3j0f/utils
b3j0f/utils/proxy.py
proxified_elt
def proxified_elt(proxy): """Get proxified element. :param proxy: proxy element from where get proxified element. :return: proxified element. None if proxy is not proxified. """ if ismethod(proxy): proxy = get_method_function(proxy) result = getattr(proxy, __PROXIFIED__, None) ret...
python
def proxified_elt(proxy): """Get proxified element. :param proxy: proxy element from where get proxified element. :return: proxified element. None if proxy is not proxified. """ if ismethod(proxy): proxy = get_method_function(proxy) result = getattr(proxy, __PROXIFIED__, None) ret...
[ "def", "proxified_elt", "(", "proxy", ")", ":", "if", "ismethod", "(", "proxy", ")", ":", "proxy", "=", "get_method_function", "(", "proxy", ")", "result", "=", "getattr", "(", "proxy", ",", "__PROXIFIED__", ",", "None", ")", "return", "result" ]
Get proxified element. :param proxy: proxy element from where get proxified element. :return: proxified element. None if proxy is not proxified.
[ "Get", "proxified", "element", "." ]
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/proxy.py#L443-L454
b3j0f/utils
b3j0f/utils/proxy.py
is_proxy
def is_proxy(elt): """Return True if elt is a proxy. :param elt: elt to check such as a proxy. :return: True iif elt is a proxy. :rtype: bool """ if ismethod(elt): elt = get_method_function(elt) result = hasattr(elt, __PROXIFIED__) return result
python
def is_proxy(elt): """Return True if elt is a proxy. :param elt: elt to check such as a proxy. :return: True iif elt is a proxy. :rtype: bool """ if ismethod(elt): elt = get_method_function(elt) result = hasattr(elt, __PROXIFIED__) return result
[ "def", "is_proxy", "(", "elt", ")", ":", "if", "ismethod", "(", "elt", ")", ":", "elt", "=", "get_method_function", "(", "elt", ")", "result", "=", "hasattr", "(", "elt", ",", "__PROXIFIED__", ")", "return", "result" ]
Return True if elt is a proxy. :param elt: elt to check such as a proxy. :return: True iif elt is a proxy. :rtype: bool
[ "Return", "True", "if", "elt", "is", "a", "proxy", "." ]
train
https://github.com/b3j0f/utils/blob/793871b98e90fd1c7ce9ef0dce839cc18fcbc6ff/b3j0f/utils/proxy.py#L457-L470
hapylestat/apputils
apputils/utils/string_utils.py
safe_format
def safe_format(s, **kwargs): """ :type s str """ return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))
python
def safe_format(s, **kwargs): """ :type s str """ return string.Formatter().vformat(s, (), defaultdict(str, **kwargs))
[ "def", "safe_format", "(", "s", ",", "*", "*", "kwargs", ")", ":", "return", "string", ".", "Formatter", "(", ")", ".", "vformat", "(", "s", ",", "(", ")", ",", "defaultdict", "(", "str", ",", "*", "*", "kwargs", ")", ")" ]
:type s str
[ ":", "type", "s", "str" ]
train
https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/utils/string_utils.py#L16-L20
hapylestat/apputils
apputils/utils/string_utils.py
safe_format_sh
def safe_format_sh(s, **kwargs): """ :type s str """ to_replace = set(kwargs.keys()) & set(FORMAT_RE.findall(s)) for item in to_replace: s = s.replace("{{" + item + "}}", kwargs[item]) return s
python
def safe_format_sh(s, **kwargs): """ :type s str """ to_replace = set(kwargs.keys()) & set(FORMAT_RE.findall(s)) for item in to_replace: s = s.replace("{{" + item + "}}", kwargs[item]) return s
[ "def", "safe_format_sh", "(", "s", ",", "*", "*", "kwargs", ")", ":", "to_replace", "=", "set", "(", "kwargs", ".", "keys", "(", ")", ")", "&", "set", "(", "FORMAT_RE", ".", "findall", "(", "s", ")", ")", "for", "item", "in", "to_replace", ":", "...
:type s str
[ ":", "type", "s", "str" ]
train
https://github.com/hapylestat/apputils/blob/5d185616feda27e6e21273307161471ef11a3518/apputils/utils/string_utils.py#L23-L33
hvishwanath/libpaas
libpaas/drivers/heroku.py
Heroku.getInstance
def getInstance(cls, *args): ''' Returns a singleton instance of the class ''' if not cls.__singleton: cls.__singleton = Heroku(*args) return cls.__singleton
python
def getInstance(cls, *args): ''' Returns a singleton instance of the class ''' if not cls.__singleton: cls.__singleton = Heroku(*args) return cls.__singleton
[ "def", "getInstance", "(", "cls", ",", "*", "args", ")", ":", "if", "not", "cls", ".", "__singleton", ":", "cls", ".", "__singleton", "=", "Heroku", "(", "*", "args", ")", "return", "cls", ".", "__singleton" ]
Returns a singleton instance of the class
[ "Returns", "a", "singleton", "instance", "of", "the", "class" ]
train
https://github.com/hvishwanath/libpaas/blob/3df07adca59c003ee754c4e919cf506c13953be1/libpaas/drivers/heroku.py#L78-L84
mlavin/django-hilbert
hilbert/decorators.py
ajax_login_required
def ajax_login_required(view_func): """Handle non-authenticated users differently if it is an AJAX request.""" @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.is_ajax(): if request.user.is_authenticated(): re...
python
def ajax_login_required(view_func): """Handle non-authenticated users differently if it is an AJAX request.""" @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.is_ajax(): if request.user.is_authenticated(): re...
[ "def", "ajax_login_required", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")", "def", "_wrapped_view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "i...
Handle non-authenticated users differently if it is an AJAX request.
[ "Handle", "non", "-", "authenticated", "users", "differently", "if", "it", "is", "an", "AJAX", "request", "." ]
train
https://github.com/mlavin/django-hilbert/blob/e77b685f4afc6e1224dc7e616e9ee9f7c2bc55b6/hilbert/decorators.py#L20-L35
mlavin/django-hilbert
hilbert/decorators.py
ajax_only
def ajax_only(view_func): """Required the view is only accessed via AJAX.""" @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.is_ajax(): return view_func(request, *args, **kwargs) else: return http.HttpRes...
python
def ajax_only(view_func): """Required the view is only accessed via AJAX.""" @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.is_ajax(): return view_func(request, *args, **kwargs) else: return http.HttpRes...
[ "def", "ajax_only", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")", "def", "_wrapped_view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "req...
Required the view is only accessed via AJAX.
[ "Required", "the", "view", "is", "only", "accessed", "via", "AJAX", "." ]
train
https://github.com/mlavin/django-hilbert/blob/e77b685f4afc6e1224dc7e616e9ee9f7c2bc55b6/hilbert/decorators.py#L38-L47
mlavin/django-hilbert
hilbert/decorators.py
anonymous_required
def anonymous_required(func=None, url=None): """Required that the user is not logged in.""" url = url or "/" def _dec(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): ...
python
def anonymous_required(func=None, url=None): """Required that the user is not logged in.""" url = url or "/" def _dec(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if request.user.is_authenticated(): ...
[ "def", "anonymous_required", "(", "func", "=", "None", ",", "url", "=", "None", ")", ":", "url", "=", "url", "or", "\"/\"", "def", "_dec", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_f...
Required that the user is not logged in.
[ "Required", "that", "the", "user", "is", "not", "logged", "in", "." ]
train
https://github.com/mlavin/django-hilbert/blob/e77b685f4afc6e1224dc7e616e9ee9f7c2bc55b6/hilbert/decorators.py#L50-L67
mlavin/django-hilbert
hilbert/decorators.py
secure
def secure(view_func): """Handles SSL redirect on the view level.""" @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if not request.is_secure(): redirect = _redirect(request, True) if redirect: # Redirect mi...
python
def secure(view_func): """Handles SSL redirect on the view level.""" @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if not request.is_secure(): redirect = _redirect(request, True) if redirect: # Redirect mi...
[ "def", "secure", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")", "def", "_wrapped_view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", ...
Handles SSL redirect on the view level.
[ "Handles", "SSL", "redirect", "on", "the", "view", "level", "." ]
train
https://github.com/mlavin/django-hilbert/blob/e77b685f4afc6e1224dc7e616e9ee9f7c2bc55b6/hilbert/decorators.py#L70-L81
jmgilman/Neolib
neolib/pyamf/amf3.py
encode_int
def encode_int(n): """ Encodes an int as a variable length signed 29-bit integer as defined by the spec. @param n: The integer to be encoded @return: The encoded string @rtype: C{str} @raise OverflowError: Out of range. """ global ENCODED_INT_CACHE try: return ENCODED_I...
python
def encode_int(n): """ Encodes an int as a variable length signed 29-bit integer as defined by the spec. @param n: The integer to be encoded @return: The encoded string @rtype: C{str} @raise OverflowError: Out of range. """ global ENCODED_INT_CACHE try: return ENCODED_I...
[ "def", "encode_int", "(", "n", ")", ":", "global", "ENCODED_INT_CACHE", "try", ":", "return", "ENCODED_INT_CACHE", "[", "n", "]", "except", "KeyError", ":", "pass", "if", "n", "<", "MIN_29B_INT", "or", "n", ">", "MAX_29B_INT", ":", "raise", "OverflowError", ...
Encodes an int as a variable length signed 29-bit integer as defined by the spec. @param n: The integer to be encoded @return: The encoded string @rtype: C{str} @raise OverflowError: Out of range.
[ "Encodes", "an", "int", "as", "a", "variable", "length", "signed", "29", "-", "bit", "integer", "as", "defined", "by", "the", "spec", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/amf3.py#L1515-L1562
jmgilman/Neolib
neolib/pyamf/amf3.py
decode_int
def decode_int(stream, signed=False): """ Decode C{int}. """ n = result = 0 b = stream.read_uchar() while b & 0x80 != 0 and n < 3: result <<= 7 result |= b & 0x7f b = stream.read_uchar() n += 1 if n < 3: result <<= 7 result |= b else: ...
python
def decode_int(stream, signed=False): """ Decode C{int}. """ n = result = 0 b = stream.read_uchar() while b & 0x80 != 0 and n < 3: result <<= 7 result |= b & 0x7f b = stream.read_uchar() n += 1 if n < 3: result <<= 7 result |= b else: ...
[ "def", "decode_int", "(", "stream", ",", "signed", "=", "False", ")", ":", "n", "=", "result", "=", "0", "b", "=", "stream", ".", "read_uchar", "(", ")", "while", "b", "&", "0x80", "!=", "0", "and", "n", "<", "3", ":", "result", "<<=", "7", "re...
Decode C{int}.
[ "Decode", "C", "{", "int", "}", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/amf3.py#L1565-L1592
jmgilman/Neolib
neolib/pyamf/amf3.py
DataOutput.writeBoolean
def writeBoolean(self, value): """ Writes a Boolean value. @type value: C{bool} @param value: A C{Boolean} value determining which byte is written. If the parameter is C{True}, C{1} is written; if C{False}, C{0} is written. @raise ValueError: Non-boolean value f...
python
def writeBoolean(self, value): """ Writes a Boolean value. @type value: C{bool} @param value: A C{Boolean} value determining which byte is written. If the parameter is C{True}, C{1} is written; if C{False}, C{0} is written. @raise ValueError: Non-boolean value f...
[ "def", "writeBoolean", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "bool", ")", ":", "raise", "ValueError", "(", "\"Non-boolean value found\"", ")", "if", "value", "is", "True", ":", "self", ".", "stream", ".", "wri...
Writes a Boolean value. @type value: C{bool} @param value: A C{Boolean} value determining which byte is written. If the parameter is C{True}, C{1} is written; if C{False}, C{0} is written. @raise ValueError: Non-boolean value found.
[ "Writes", "a", "Boolean", "value", "." ]
train
https://github.com/jmgilman/Neolib/blob/228fafeaed0f3195676137732384a14820ae285c/neolib/pyamf/amf3.py#L173-L190