id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
238,000
|
Fortran-FOSS-Programmers/ford
|
ford/utils.py
|
quote_split
|
def quote_split(sep,string):
"""
Splits the strings into pieces divided by sep, when sep in not inside quotes.
"""
if len(sep) != 1: raise Exception("Separation string must be one character long")
retlist = []
squote = False
dquote = False
left = 0
i = 0
while i < len(string):
if string[i] == '"' and not dquote:
if not squote:
squote = True
elif (i+1) < len(string) and string[i+1] == '"':
i += 1
else:
squote = False
elif string[i] == "'" and not squote:
if not dquote:
dquote = True
elif (i+1) < len(string) and string[i+1] == "'":
i += 1
else:
dquote = False
elif string[i] == sep and not dquote and not squote:
retlist.append(string[left:i])
left = i + 1
i += 1
retlist.append(string[left:])
return retlist
|
python
|
def quote_split(sep,string):
"""
Splits the strings into pieces divided by sep, when sep in not inside quotes.
"""
if len(sep) != 1: raise Exception("Separation string must be one character long")
retlist = []
squote = False
dquote = False
left = 0
i = 0
while i < len(string):
if string[i] == '"' and not dquote:
if not squote:
squote = True
elif (i+1) < len(string) and string[i+1] == '"':
i += 1
else:
squote = False
elif string[i] == "'" and not squote:
if not dquote:
dquote = True
elif (i+1) < len(string) and string[i+1] == "'":
i += 1
else:
dquote = False
elif string[i] == sep and not dquote and not squote:
retlist.append(string[left:i])
left = i + 1
i += 1
retlist.append(string[left:])
return retlist
|
[
"def",
"quote_split",
"(",
"sep",
",",
"string",
")",
":",
"if",
"len",
"(",
"sep",
")",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"\"Separation string must be one character long\"",
")",
"retlist",
"=",
"[",
"]",
"squote",
"=",
"False",
"dquote",
"=",
"False",
"left",
"=",
"0",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"string",
")",
":",
"if",
"string",
"[",
"i",
"]",
"==",
"'\"'",
"and",
"not",
"dquote",
":",
"if",
"not",
"squote",
":",
"squote",
"=",
"True",
"elif",
"(",
"i",
"+",
"1",
")",
"<",
"len",
"(",
"string",
")",
"and",
"string",
"[",
"i",
"+",
"1",
"]",
"==",
"'\"'",
":",
"i",
"+=",
"1",
"else",
":",
"squote",
"=",
"False",
"elif",
"string",
"[",
"i",
"]",
"==",
"\"'\"",
"and",
"not",
"squote",
":",
"if",
"not",
"dquote",
":",
"dquote",
"=",
"True",
"elif",
"(",
"i",
"+",
"1",
")",
"<",
"len",
"(",
"string",
")",
"and",
"string",
"[",
"i",
"+",
"1",
"]",
"==",
"\"'\"",
":",
"i",
"+=",
"1",
"else",
":",
"dquote",
"=",
"False",
"elif",
"string",
"[",
"i",
"]",
"==",
"sep",
"and",
"not",
"dquote",
"and",
"not",
"squote",
":",
"retlist",
".",
"append",
"(",
"string",
"[",
"left",
":",
"i",
"]",
")",
"left",
"=",
"i",
"+",
"1",
"i",
"+=",
"1",
"retlist",
".",
"append",
"(",
"string",
"[",
"left",
":",
"]",
")",
"return",
"retlist"
] |
Splits the strings into pieces divided by sep, when sep in not inside quotes.
|
[
"Splits",
"the",
"strings",
"into",
"pieces",
"divided",
"by",
"sep",
"when",
"sep",
"in",
"not",
"inside",
"quotes",
"."
] |
d46a44eae20d99205292c31785f936fbed47070f
|
https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/utils.py#L110-L140
|
238,001
|
Fortran-FOSS-Programmers/ford
|
ford/utils.py
|
split_path
|
def split_path(path):
'''
Splits the argument into its constituent directories and returns them as
a list.
'''
def recurse_path(path,retlist):
if len(retlist) > 100:
fullpath = os.path.join(*([ path, ] + retlist))
print("Directory '{}' contains too many levels".format(fullpath))
exit(1)
head, tail = os.path.split(path)
if len(tail) > 0:
retlist.insert(0,tail)
recurse_path(head,retlist)
elif len(head) > 1:
recurse_path(head,retlist)
else:
return
retlist = []
path = os.path.realpath(os.path.normpath(path))
drive, path = os.path.splitdrive(path)
if len(drive) > 0: retlist.append(drive)
recurse_path(path,retlist)
return retlist
|
python
|
def split_path(path):
'''
Splits the argument into its constituent directories and returns them as
a list.
'''
def recurse_path(path,retlist):
if len(retlist) > 100:
fullpath = os.path.join(*([ path, ] + retlist))
print("Directory '{}' contains too many levels".format(fullpath))
exit(1)
head, tail = os.path.split(path)
if len(tail) > 0:
retlist.insert(0,tail)
recurse_path(head,retlist)
elif len(head) > 1:
recurse_path(head,retlist)
else:
return
retlist = []
path = os.path.realpath(os.path.normpath(path))
drive, path = os.path.splitdrive(path)
if len(drive) > 0: retlist.append(drive)
recurse_path(path,retlist)
return retlist
|
[
"def",
"split_path",
"(",
"path",
")",
":",
"def",
"recurse_path",
"(",
"path",
",",
"retlist",
")",
":",
"if",
"len",
"(",
"retlist",
")",
">",
"100",
":",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"(",
"[",
"path",
",",
"]",
"+",
"retlist",
")",
")",
"print",
"(",
"\"Directory '{}' contains too many levels\"",
".",
"format",
"(",
"fullpath",
")",
")",
"exit",
"(",
"1",
")",
"head",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"if",
"len",
"(",
"tail",
")",
">",
"0",
":",
"retlist",
".",
"insert",
"(",
"0",
",",
"tail",
")",
"recurse_path",
"(",
"head",
",",
"retlist",
")",
"elif",
"len",
"(",
"head",
")",
">",
"1",
":",
"recurse_path",
"(",
"head",
",",
"retlist",
")",
"else",
":",
"return",
"retlist",
"=",
"[",
"]",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")",
")",
"drive",
",",
"path",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"path",
")",
"if",
"len",
"(",
"drive",
")",
">",
"0",
":",
"retlist",
".",
"append",
"(",
"drive",
")",
"recurse_path",
"(",
"path",
",",
"retlist",
")",
"return",
"retlist"
] |
Splits the argument into its constituent directories and returns them as
a list.
|
[
"Splits",
"the",
"argument",
"into",
"its",
"constituent",
"directories",
"and",
"returns",
"them",
"as",
"a",
"list",
"."
] |
d46a44eae20d99205292c31785f936fbed47070f
|
https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/utils.py#L143-L167
|
238,002
|
Fortran-FOSS-Programmers/ford
|
ford/utils.py
|
sub_macros
|
def sub_macros(string,base_url):
'''
Replaces macros in documentation with their appropriate values. These macros
are used for things like providing URLs.
'''
macros = { '|url|': base_url,
'|media|': os.path.join(base_url,'media'),
'|page|': os.path.join(base_url,'page')
}
for key, val in macros.items():
string = string.replace(key,val)
return string
|
python
|
def sub_macros(string,base_url):
'''
Replaces macros in documentation with their appropriate values. These macros
are used for things like providing URLs.
'''
macros = { '|url|': base_url,
'|media|': os.path.join(base_url,'media'),
'|page|': os.path.join(base_url,'page')
}
for key, val in macros.items():
string = string.replace(key,val)
return string
|
[
"def",
"sub_macros",
"(",
"string",
",",
"base_url",
")",
":",
"macros",
"=",
"{",
"'|url|'",
":",
"base_url",
",",
"'|media|'",
":",
"os",
".",
"path",
".",
"join",
"(",
"base_url",
",",
"'media'",
")",
",",
"'|page|'",
":",
"os",
".",
"path",
".",
"join",
"(",
"base_url",
",",
"'page'",
")",
"}",
"for",
"key",
",",
"val",
"in",
"macros",
".",
"items",
"(",
")",
":",
"string",
"=",
"string",
".",
"replace",
"(",
"key",
",",
"val",
")",
"return",
"string"
] |
Replaces macros in documentation with their appropriate values. These macros
are used for things like providing URLs.
|
[
"Replaces",
"macros",
"in",
"documentation",
"with",
"their",
"appropriate",
"values",
".",
"These",
"macros",
"are",
"used",
"for",
"things",
"like",
"providing",
"URLs",
"."
] |
d46a44eae20d99205292c31785f936fbed47070f
|
https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/utils.py#L279-L290
|
238,003
|
Fortran-FOSS-Programmers/ford
|
ford/output.py
|
copytree
|
def copytree(src, dst):
"""Replaces shutil.copytree to avoid problems on certain file systems.
shutil.copytree() and shutil.copystat() invoke os.setxattr(), which seems
to fail when called for directories on at least one NFS file system.
The current routine is a simple replacement, which should be good enough for
Ford.
"""
def touch(path):
now = time.time()
try:
# assume it's there
os.utime(path, (now, now))
except os.error:
# if it isn't, try creating the directory,
# a file with that name
os.makedirs(os.path.dirname(path))
open(path, "w").close()
os.utime(path, (now, now))
for root, dirs, files in os.walk(src):
relsrcdir = os.path.relpath(root, src)
dstdir = os.path.join(dst, relsrcdir)
if not os.path.exists(dstdir):
try:
os.makedirs(dstdir)
except OSError as ex:
if ex.errno != errno.EEXIST:
raise
for ff in files:
shutil.copy(os.path.join(root, ff), os.path.join(dstdir, ff))
touch(os.path.join(dstdir, ff))
|
python
|
def copytree(src, dst):
"""Replaces shutil.copytree to avoid problems on certain file systems.
shutil.copytree() and shutil.copystat() invoke os.setxattr(), which seems
to fail when called for directories on at least one NFS file system.
The current routine is a simple replacement, which should be good enough for
Ford.
"""
def touch(path):
now = time.time()
try:
# assume it's there
os.utime(path, (now, now))
except os.error:
# if it isn't, try creating the directory,
# a file with that name
os.makedirs(os.path.dirname(path))
open(path, "w").close()
os.utime(path, (now, now))
for root, dirs, files in os.walk(src):
relsrcdir = os.path.relpath(root, src)
dstdir = os.path.join(dst, relsrcdir)
if not os.path.exists(dstdir):
try:
os.makedirs(dstdir)
except OSError as ex:
if ex.errno != errno.EEXIST:
raise
for ff in files:
shutil.copy(os.path.join(root, ff), os.path.join(dstdir, ff))
touch(os.path.join(dstdir, ff))
|
[
"def",
"copytree",
"(",
"src",
",",
"dst",
")",
":",
"def",
"touch",
"(",
"path",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
"# assume it's there",
"os",
".",
"utime",
"(",
"path",
",",
"(",
"now",
",",
"now",
")",
")",
"except",
"os",
".",
"error",
":",
"# if it isn't, try creating the directory,",
"# a file with that name",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
"open",
"(",
"path",
",",
"\"w\"",
")",
".",
"close",
"(",
")",
"os",
".",
"utime",
"(",
"path",
",",
"(",
"now",
",",
"now",
")",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"src",
")",
":",
"relsrcdir",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"root",
",",
"src",
")",
"dstdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst",
",",
"relsrcdir",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dstdir",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"dstdir",
")",
"except",
"OSError",
"as",
"ex",
":",
"if",
"ex",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"for",
"ff",
"in",
"files",
":",
"shutil",
".",
"copy",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"ff",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"dstdir",
",",
"ff",
")",
")",
"touch",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dstdir",
",",
"ff",
")",
")"
] |
Replaces shutil.copytree to avoid problems on certain file systems.
shutil.copytree() and shutil.copystat() invoke os.setxattr(), which seems
to fail when called for directories on at least one NFS file system.
The current routine is a simple replacement, which should be good enough for
Ford.
|
[
"Replaces",
"shutil",
".",
"copytree",
"to",
"avoid",
"problems",
"on",
"certain",
"file",
"systems",
"."
] |
d46a44eae20d99205292c31785f936fbed47070f
|
https://github.com/Fortran-FOSS-Programmers/ford/blob/d46a44eae20d99205292c31785f936fbed47070f/ford/output.py#L520-L551
|
238,004
|
KelSolaar/Umbra
|
umbra/ui/widgets/active_QLabel.py
|
Active_QLabel.set_checked
|
def set_checked(self, state):
"""
Sets the Widget checked state.
:param state: New check state.
:type state: bool
:return: Method success.
:rtype: bool
"""
if not self.__checkable:
return False
if state:
self.__checked = True
self.setPixmap(self.__active_pixmap)
else:
self.__checked = False
self.setPixmap(self.__default_pixmap)
self.toggled.emit(state)
return True
|
python
|
def set_checked(self, state):
"""
Sets the Widget checked state.
:param state: New check state.
:type state: bool
:return: Method success.
:rtype: bool
"""
if not self.__checkable:
return False
if state:
self.__checked = True
self.setPixmap(self.__active_pixmap)
else:
self.__checked = False
self.setPixmap(self.__default_pixmap)
self.toggled.emit(state)
return True
|
[
"def",
"set_checked",
"(",
"self",
",",
"state",
")",
":",
"if",
"not",
"self",
".",
"__checkable",
":",
"return",
"False",
"if",
"state",
":",
"self",
".",
"__checked",
"=",
"True",
"self",
".",
"setPixmap",
"(",
"self",
".",
"__active_pixmap",
")",
"else",
":",
"self",
".",
"__checked",
"=",
"False",
"self",
".",
"setPixmap",
"(",
"self",
".",
"__default_pixmap",
")",
"self",
".",
"toggled",
".",
"emit",
"(",
"state",
")",
"return",
"True"
] |
Sets the Widget checked state.
:param state: New check state.
:type state: bool
:return: Method success.
:rtype: bool
|
[
"Sets",
"the",
"Widget",
"checked",
"state",
"."
] |
66f45f08d9d723787f1191989f8b0dda84b412ce
|
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/widgets/active_QLabel.py#L386-L406
|
238,005
|
KelSolaar/Umbra
|
umbra/ui/widgets/active_QLabel.py
|
Active_QLabel.set_menu
|
def set_menu(self, menu):
"""
Sets the Widget menu.
:param menu: Menu.
:type menu: QMenu
:return: Method success.
:rtype: bool
"""
self.__menu = menu
if not self.parent():
return False
parent = [parent for parent in umbra.ui.common.parents_walker(self)].pop()
for action in self.__menu.actions():
not action.shortcut().isEmpty() and parent.addAction(action)
return True
|
python
|
def set_menu(self, menu):
"""
Sets the Widget menu.
:param menu: Menu.
:type menu: QMenu
:return: Method success.
:rtype: bool
"""
self.__menu = menu
if not self.parent():
return False
parent = [parent for parent in umbra.ui.common.parents_walker(self)].pop()
for action in self.__menu.actions():
not action.shortcut().isEmpty() and parent.addAction(action)
return True
|
[
"def",
"set_menu",
"(",
"self",
",",
"menu",
")",
":",
"self",
".",
"__menu",
"=",
"menu",
"if",
"not",
"self",
".",
"parent",
"(",
")",
":",
"return",
"False",
"parent",
"=",
"[",
"parent",
"for",
"parent",
"in",
"umbra",
".",
"ui",
".",
"common",
".",
"parents_walker",
"(",
"self",
")",
"]",
".",
"pop",
"(",
")",
"for",
"action",
"in",
"self",
".",
"__menu",
".",
"actions",
"(",
")",
":",
"not",
"action",
".",
"shortcut",
"(",
")",
".",
"isEmpty",
"(",
")",
"and",
"parent",
".",
"addAction",
"(",
"action",
")",
"return",
"True"
] |
Sets the Widget menu.
:param menu: Menu.
:type menu: QMenu
:return: Method success.
:rtype: bool
|
[
"Sets",
"the",
"Widget",
"menu",
"."
] |
66f45f08d9d723787f1191989f8b0dda84b412ce
|
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/widgets/active_QLabel.py#L408-L426
|
238,006
|
KelSolaar/Umbra
|
umbra/managers/file_system_events_manager.py
|
FileSystemEventsManager.get
|
def get(self, path, default=None):
"""
Returns given path value.
:param path: Path name.
:type path: unicode
:param default: Default value if path is not found.
:type default: object
:return: Action.
:rtype: QAction
"""
try:
return self.__getitem__(path)
except KeyError as error:
return default
|
python
|
def get(self, path, default=None):
"""
Returns given path value.
:param path: Path name.
:type path: unicode
:param default: Default value if path is not found.
:type default: object
:return: Action.
:rtype: QAction
"""
try:
return self.__getitem__(path)
except KeyError as error:
return default
|
[
"def",
"get",
"(",
"self",
",",
"path",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"__getitem__",
"(",
"path",
")",
"except",
"KeyError",
"as",
"error",
":",
"return",
"default"
] |
Returns given path value.
:param path: Path name.
:type path: unicode
:param default: Default value if path is not found.
:type default: object
:return: Action.
:rtype: QAction
|
[
"Returns",
"given",
"path",
"value",
"."
] |
66f45f08d9d723787f1191989f8b0dda84b412ce
|
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/managers/file_system_events_manager.py#L289-L304
|
238,007
|
KelSolaar/Umbra
|
umbra/managers/file_system_events_manager.py
|
FileSystemEventsManager.__watch_file_system
|
def __watch_file_system(self):
"""
Watches the file system for paths that have been changed or invalidated on disk.
"""
for path, data in self.__paths.items():
stored_modified_time, is_file = data
try:
if not foundations.common.path_exists(path):
LOGGER.warning(
"!> {0} | '{1}' path has been invalidated and will be unregistered!".format(
self.__class__.__name__, path))
del (self.__paths[path])
if is_file:
self.file_invalidated.emit(path)
else:
self.directory_invalidated.emit(path)
continue
except KeyError:
LOGGER.debug("> {0} | '{1}' path has been unregistered while iterating!".format(
self.__class__.__name__, path))
continue
try:
modified_time = self.get_path_modified_time(path)
except OSError:
LOGGER.debug("> {0} | '{1}' path has been invalidated while iterating!".format(
self.__class__.__name__, path))
continue
if stored_modified_time != modified_time:
self.__paths[path] = (modified_time, os.path.isfile(path))
LOGGER.debug("> {0} | '{1}' path has been changed!".format(self.__class__.__name__, path))
if is_file:
self.file_changed.emit(path)
else:
self.directory_changed.emit(path)
|
python
|
def __watch_file_system(self):
"""
Watches the file system for paths that have been changed or invalidated on disk.
"""
for path, data in self.__paths.items():
stored_modified_time, is_file = data
try:
if not foundations.common.path_exists(path):
LOGGER.warning(
"!> {0} | '{1}' path has been invalidated and will be unregistered!".format(
self.__class__.__name__, path))
del (self.__paths[path])
if is_file:
self.file_invalidated.emit(path)
else:
self.directory_invalidated.emit(path)
continue
except KeyError:
LOGGER.debug("> {0} | '{1}' path has been unregistered while iterating!".format(
self.__class__.__name__, path))
continue
try:
modified_time = self.get_path_modified_time(path)
except OSError:
LOGGER.debug("> {0} | '{1}' path has been invalidated while iterating!".format(
self.__class__.__name__, path))
continue
if stored_modified_time != modified_time:
self.__paths[path] = (modified_time, os.path.isfile(path))
LOGGER.debug("> {0} | '{1}' path has been changed!".format(self.__class__.__name__, path))
if is_file:
self.file_changed.emit(path)
else:
self.directory_changed.emit(path)
|
[
"def",
"__watch_file_system",
"(",
"self",
")",
":",
"for",
"path",
",",
"data",
"in",
"self",
".",
"__paths",
".",
"items",
"(",
")",
":",
"stored_modified_time",
",",
"is_file",
"=",
"data",
"try",
":",
"if",
"not",
"foundations",
".",
"common",
".",
"path_exists",
"(",
"path",
")",
":",
"LOGGER",
".",
"warning",
"(",
"\"!> {0} | '{1}' path has been invalidated and will be unregistered!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"path",
")",
")",
"del",
"(",
"self",
".",
"__paths",
"[",
"path",
"]",
")",
"if",
"is_file",
":",
"self",
".",
"file_invalidated",
".",
"emit",
"(",
"path",
")",
"else",
":",
"self",
".",
"directory_invalidated",
".",
"emit",
"(",
"path",
")",
"continue",
"except",
"KeyError",
":",
"LOGGER",
".",
"debug",
"(",
"\"> {0} | '{1}' path has been unregistered while iterating!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"path",
")",
")",
"continue",
"try",
":",
"modified_time",
"=",
"self",
".",
"get_path_modified_time",
"(",
"path",
")",
"except",
"OSError",
":",
"LOGGER",
".",
"debug",
"(",
"\"> {0} | '{1}' path has been invalidated while iterating!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"path",
")",
")",
"continue",
"if",
"stored_modified_time",
"!=",
"modified_time",
":",
"self",
".",
"__paths",
"[",
"path",
"]",
"=",
"(",
"modified_time",
",",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
")",
"LOGGER",
".",
"debug",
"(",
"\"> {0} | '{1}' path has been changed!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"path",
")",
")",
"if",
"is_file",
":",
"self",
".",
"file_changed",
".",
"emit",
"(",
"path",
")",
"else",
":",
"self",
".",
"directory_changed",
".",
"emit",
"(",
"path",
")"
] |
Watches the file system for paths that have been changed or invalidated on disk.
|
[
"Watches",
"the",
"file",
"system",
"for",
"paths",
"that",
"have",
"been",
"changed",
"or",
"invalidated",
"on",
"disk",
"."
] |
66f45f08d9d723787f1191989f8b0dda84b412ce
|
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/managers/file_system_events_manager.py#L319-L355
|
238,008
|
KelSolaar/Umbra
|
umbra/managers/file_system_events_manager.py
|
FileSystemEventsManager.register_path
|
def register_path(self, path, modified_time=None):
"""
Registers given path.
:param path: Path name.
:type path: unicode
:param modified_time: Custom modified time.
:type modified_time: int or float
:return: Method success.
:rtype: bool
"""
if not foundations.common.path_exists(path):
raise foundations.exceptions.PathExistsError("{0} | '{1}' path doesn't exists!".format(
self.__class__.__name__, path))
if path in self:
raise umbra.exceptions.PathRegistrationError("{0} | '{1}' path is already registered!".format(
self.__class__.__name__, path))
self.__paths[path] = (self.get_path_modified_time(
path) if modified_time is None else modified_time, os.path.isfile(path))
return True
|
python
|
def register_path(self, path, modified_time=None):
"""
Registers given path.
:param path: Path name.
:type path: unicode
:param modified_time: Custom modified time.
:type modified_time: int or float
:return: Method success.
:rtype: bool
"""
if not foundations.common.path_exists(path):
raise foundations.exceptions.PathExistsError("{0} | '{1}' path doesn't exists!".format(
self.__class__.__name__, path))
if path in self:
raise umbra.exceptions.PathRegistrationError("{0} | '{1}' path is already registered!".format(
self.__class__.__name__, path))
self.__paths[path] = (self.get_path_modified_time(
path) if modified_time is None else modified_time, os.path.isfile(path))
return True
|
[
"def",
"register_path",
"(",
"self",
",",
"path",
",",
"modified_time",
"=",
"None",
")",
":",
"if",
"not",
"foundations",
".",
"common",
".",
"path_exists",
"(",
"path",
")",
":",
"raise",
"foundations",
".",
"exceptions",
".",
"PathExistsError",
"(",
"\"{0} | '{1}' path doesn't exists!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"path",
")",
")",
"if",
"path",
"in",
"self",
":",
"raise",
"umbra",
".",
"exceptions",
".",
"PathRegistrationError",
"(",
"\"{0} | '{1}' path is already registered!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"path",
")",
")",
"self",
".",
"__paths",
"[",
"path",
"]",
"=",
"(",
"self",
".",
"get_path_modified_time",
"(",
"path",
")",
"if",
"modified_time",
"is",
"None",
"else",
"modified_time",
",",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
")",
"return",
"True"
] |
Registers given path.
:param path: Path name.
:type path: unicode
:param modified_time: Custom modified time.
:type modified_time: int or float
:return: Method success.
:rtype: bool
|
[
"Registers",
"given",
"path",
"."
] |
66f45f08d9d723787f1191989f8b0dda84b412ce
|
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/managers/file_system_events_manager.py#L381-L403
|
238,009
|
KelSolaar/Umbra
|
umbra/managers/file_system_events_manager.py
|
FileSystemEventsManager.unregister_path
|
def unregister_path(self, path):
"""
Unregisters given path.
:param path: Path name.
:type path: unicode
:return: Method success.
:rtype: bool
"""
if not path in self:
raise umbra.exceptions.PathExistsError("{0} | '{1}' path isn't registered!".format(
self.__class__.__name__, path))
del (self.__paths[path])
return True
|
python
|
def unregister_path(self, path):
"""
Unregisters given path.
:param path: Path name.
:type path: unicode
:return: Method success.
:rtype: bool
"""
if not path in self:
raise umbra.exceptions.PathExistsError("{0} | '{1}' path isn't registered!".format(
self.__class__.__name__, path))
del (self.__paths[path])
return True
|
[
"def",
"unregister_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"path",
"in",
"self",
":",
"raise",
"umbra",
".",
"exceptions",
".",
"PathExistsError",
"(",
"\"{0} | '{1}' path isn't registered!\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"path",
")",
")",
"del",
"(",
"self",
".",
"__paths",
"[",
"path",
"]",
")",
"return",
"True"
] |
Unregisters given path.
:param path: Path name.
:type path: unicode
:return: Method success.
:rtype: bool
|
[
"Unregisters",
"given",
"path",
"."
] |
66f45f08d9d723787f1191989f8b0dda84b412ce
|
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/managers/file_system_events_manager.py#L406-L421
|
238,010
|
KelSolaar/Umbra
|
umbra/managers/file_system_events_manager.py
|
FileSystemEventsManager.get_path_modified_time
|
def get_path_modified_time(path):
"""
Returns given path modification time.
:param path: Path.
:type path: unicode
:return: Modification time.
:rtype: int
"""
return float(foundations.common.get_first_item(str(os.path.getmtime(path)).split(".")))
|
python
|
def get_path_modified_time(path):
"""
Returns given path modification time.
:param path: Path.
:type path: unicode
:return: Modification time.
:rtype: int
"""
return float(foundations.common.get_first_item(str(os.path.getmtime(path)).split(".")))
|
[
"def",
"get_path_modified_time",
"(",
"path",
")",
":",
"return",
"float",
"(",
"foundations",
".",
"common",
".",
"get_first_item",
"(",
"str",
"(",
"os",
".",
"path",
".",
"getmtime",
"(",
"path",
")",
")",
".",
"split",
"(",
"\".\"",
")",
")",
")"
] |
Returns given path modification time.
:param path: Path.
:type path: unicode
:return: Modification time.
:rtype: int
|
[
"Returns",
"given",
"path",
"modification",
"time",
"."
] |
66f45f08d9d723787f1191989f8b0dda84b412ce
|
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/managers/file_system_events_manager.py#L424-L434
|
238,011
|
titilambert/pyfido
|
pyfido/client.py
|
FidoClient._post_login_page
|
def _post_login_page(self):
"""Login to Janrain."""
# Prepare post data
data = {
"form": "signInForm",
"client_id": JANRAIN_CLIENT_ID,
"redirect_uri": "https://www.fido.ca/pages/#/",
"response_type": "token",
"locale": "en-US",
"userID": self.username,
"currentPassword": self.password,
}
# HTTP request
try:
raw_res = yield from self._session.post(LOGIN_URL,
headers=self._headers,
data=data,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not sign in")
return True
|
python
|
def _post_login_page(self):
"""Login to Janrain."""
# Prepare post data
data = {
"form": "signInForm",
"client_id": JANRAIN_CLIENT_ID,
"redirect_uri": "https://www.fido.ca/pages/#/",
"response_type": "token",
"locale": "en-US",
"userID": self.username,
"currentPassword": self.password,
}
# HTTP request
try:
raw_res = yield from self._session.post(LOGIN_URL,
headers=self._headers,
data=data,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not sign in")
return True
|
[
"def",
"_post_login_page",
"(",
"self",
")",
":",
"# Prepare post data",
"data",
"=",
"{",
"\"form\"",
":",
"\"signInForm\"",
",",
"\"client_id\"",
":",
"JANRAIN_CLIENT_ID",
",",
"\"redirect_uri\"",
":",
"\"https://www.fido.ca/pages/#/\"",
",",
"\"response_type\"",
":",
"\"token\"",
",",
"\"locale\"",
":",
"\"en-US\"",
",",
"\"userID\"",
":",
"self",
".",
"username",
",",
"\"currentPassword\"",
":",
"self",
".",
"password",
",",
"}",
"# HTTP request",
"try",
":",
"raw_res",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
"post",
"(",
"LOGIN_URL",
",",
"headers",
"=",
"self",
".",
"_headers",
",",
"data",
"=",
"data",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"except",
"OSError",
":",
"raise",
"PyFidoError",
"(",
"\"Can not sign in\"",
")",
"return",
"True"
] |
Login to Janrain.
|
[
"Login",
"to",
"Janrain",
"."
] |
8302b76f4d9d7b05b97926c003ca02409aa23281
|
https://github.com/titilambert/pyfido/blob/8302b76f4d9d7b05b97926c003ca02409aa23281/pyfido/client.py#L57-L78
|
238,012
|
titilambert/pyfido
|
pyfido/client.py
|
FidoClient._get_token
|
def _get_token(self):
"""Get token from JanRain."""
# HTTP request
try:
raw_res = yield from self._session.get(TOKEN_URL,
headers=self._headers,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not get token")
# Research for json in answer
content = yield from raw_res.text()
reg_res = re.search(r"\({.*}\)", content)
if reg_res is None:
raise PyFidoError("Can not finf token json")
# Load data as json
return_data = json.loads(reg_res.group()[1:-1])
# Get token and uuid
token = return_data.get('result', {}).get('accessToken')
uuid = return_data.get('result', {}).get('userData', {}).get('uuid')
# Check values
if token is None or uuid is None:
raise PyFidoError("Can not get token or uuid")
return token, uuid
|
python
|
def _get_token(self):
"""Get token from JanRain."""
# HTTP request
try:
raw_res = yield from self._session.get(TOKEN_URL,
headers=self._headers,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not get token")
# Research for json in answer
content = yield from raw_res.text()
reg_res = re.search(r"\({.*}\)", content)
if reg_res is None:
raise PyFidoError("Can not finf token json")
# Load data as json
return_data = json.loads(reg_res.group()[1:-1])
# Get token and uuid
token = return_data.get('result', {}).get('accessToken')
uuid = return_data.get('result', {}).get('userData', {}).get('uuid')
# Check values
if token is None or uuid is None:
raise PyFidoError("Can not get token or uuid")
return token, uuid
|
[
"def",
"_get_token",
"(",
"self",
")",
":",
"# HTTP request",
"try",
":",
"raw_res",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
"get",
"(",
"TOKEN_URL",
",",
"headers",
"=",
"self",
".",
"_headers",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"except",
"OSError",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get token\"",
")",
"# Research for json in answer",
"content",
"=",
"yield",
"from",
"raw_res",
".",
"text",
"(",
")",
"reg_res",
"=",
"re",
".",
"search",
"(",
"r\"\\({.*}\\)\"",
",",
"content",
")",
"if",
"reg_res",
"is",
"None",
":",
"raise",
"PyFidoError",
"(",
"\"Can not finf token json\"",
")",
"# Load data as json",
"return_data",
"=",
"json",
".",
"loads",
"(",
"reg_res",
".",
"group",
"(",
")",
"[",
"1",
":",
"-",
"1",
"]",
")",
"# Get token and uuid",
"token",
"=",
"return_data",
".",
"get",
"(",
"'result'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'accessToken'",
")",
"uuid",
"=",
"return_data",
".",
"get",
"(",
"'result'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'userData'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'uuid'",
")",
"# Check values",
"if",
"token",
"is",
"None",
"or",
"uuid",
"is",
"None",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get token or uuid\"",
")",
"return",
"token",
",",
"uuid"
] |
Get token from JanRain.
|
[
"Get",
"token",
"from",
"JanRain",
"."
] |
8302b76f4d9d7b05b97926c003ca02409aa23281
|
https://github.com/titilambert/pyfido/blob/8302b76f4d9d7b05b97926c003ca02409aa23281/pyfido/client.py#L81-L104
|
238,013
|
titilambert/pyfido
|
pyfido/client.py
|
FidoClient._get_account_number
|
def _get_account_number(self, token, uuid):
"""Get fido account number."""
# Data
data = {"accessToken": token,
"uuid": uuid}
# Http request
try:
raw_res = yield from self._session.post(ACCOUNT_URL,
data=data,
headers=self._headers,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not get account number")
# Load answer as json
try:
json_content = yield from raw_res.json()
account_number = json_content\
.get('getCustomerAccounts', {})\
.get('accounts', [{}])[0]\
.get('accountNumber')
except (OSError, ValueError):
raise PyFidoError("Bad json getting account number")
# Check collected data
if account_number is None:
raise PyFidoError("Can not get account number")
return account_number
|
python
|
def _get_account_number(self, token, uuid):
"""Get fido account number."""
# Data
data = {"accessToken": token,
"uuid": uuid}
# Http request
try:
raw_res = yield from self._session.post(ACCOUNT_URL,
data=data,
headers=self._headers,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not get account number")
# Load answer as json
try:
json_content = yield from raw_res.json()
account_number = json_content\
.get('getCustomerAccounts', {})\
.get('accounts', [{}])[0]\
.get('accountNumber')
except (OSError, ValueError):
raise PyFidoError("Bad json getting account number")
# Check collected data
if account_number is None:
raise PyFidoError("Can not get account number")
return account_number
|
[
"def",
"_get_account_number",
"(",
"self",
",",
"token",
",",
"uuid",
")",
":",
"# Data",
"data",
"=",
"{",
"\"accessToken\"",
":",
"token",
",",
"\"uuid\"",
":",
"uuid",
"}",
"# Http request",
"try",
":",
"raw_res",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
"post",
"(",
"ACCOUNT_URL",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"self",
".",
"_headers",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"except",
"OSError",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get account number\"",
")",
"# Load answer as json",
"try",
":",
"json_content",
"=",
"yield",
"from",
"raw_res",
".",
"json",
"(",
")",
"account_number",
"=",
"json_content",
".",
"get",
"(",
"'getCustomerAccounts'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'accounts'",
",",
"[",
"{",
"}",
"]",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'accountNumber'",
")",
"except",
"(",
"OSError",
",",
"ValueError",
")",
":",
"raise",
"PyFidoError",
"(",
"\"Bad json getting account number\"",
")",
"# Check collected data",
"if",
"account_number",
"is",
"None",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get account number\"",
")",
"return",
"account_number"
] |
Get fido account number.
|
[
"Get",
"fido",
"account",
"number",
"."
] |
8302b76f4d9d7b05b97926c003ca02409aa23281
|
https://github.com/titilambert/pyfido/blob/8302b76f4d9d7b05b97926c003ca02409aa23281/pyfido/client.py#L107-L133
|
238,014
|
titilambert/pyfido
|
pyfido/client.py
|
FidoClient._get_balance
|
def _get_balance(self, account_number):
"""Get current balance from Fido."""
# Prepare data
data = {"ctn": self.username,
"language": "en-US",
"accountNumber": account_number}
# Http request
try:
raw_res = yield from self._session.post(BALANCE_URL,
data=data,
headers=self._headers,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not get balance")
# Get balance
try:
json_content = yield from raw_res.json()
balance_str = json_content\
.get("getAccountInfo", {})\
.get("balance")
except (OSError, ValueError):
raise PyFidoError("Can not get balance as json")
if balance_str is None:
raise PyFidoError("Can not get balance")
# Casting to float
try:
balance = float(balance_str)
except ValueError:
raise PyFidoError("Can not get balance as float")
return balance
|
python
|
def _get_balance(self, account_number):
"""Get current balance from Fido."""
# Prepare data
data = {"ctn": self.username,
"language": "en-US",
"accountNumber": account_number}
# Http request
try:
raw_res = yield from self._session.post(BALANCE_URL,
data=data,
headers=self._headers,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not get balance")
# Get balance
try:
json_content = yield from raw_res.json()
balance_str = json_content\
.get("getAccountInfo", {})\
.get("balance")
except (OSError, ValueError):
raise PyFidoError("Can not get balance as json")
if balance_str is None:
raise PyFidoError("Can not get balance")
# Casting to float
try:
balance = float(balance_str)
except ValueError:
raise PyFidoError("Can not get balance as float")
return balance
|
[
"def",
"_get_balance",
"(",
"self",
",",
"account_number",
")",
":",
"# Prepare data",
"data",
"=",
"{",
"\"ctn\"",
":",
"self",
".",
"username",
",",
"\"language\"",
":",
"\"en-US\"",
",",
"\"accountNumber\"",
":",
"account_number",
"}",
"# Http request",
"try",
":",
"raw_res",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
"post",
"(",
"BALANCE_URL",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"self",
".",
"_headers",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"except",
"OSError",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get balance\"",
")",
"# Get balance",
"try",
":",
"json_content",
"=",
"yield",
"from",
"raw_res",
".",
"json",
"(",
")",
"balance_str",
"=",
"json_content",
".",
"get",
"(",
"\"getAccountInfo\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"balance\"",
")",
"except",
"(",
"OSError",
",",
"ValueError",
")",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get balance as json\"",
")",
"if",
"balance_str",
"is",
"None",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get balance\"",
")",
"# Casting to float",
"try",
":",
"balance",
"=",
"float",
"(",
"balance_str",
")",
"except",
"ValueError",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get balance as float\"",
")",
"return",
"balance"
] |
Get current balance from Fido.
|
[
"Get",
"current",
"balance",
"from",
"Fido",
"."
] |
8302b76f4d9d7b05b97926c003ca02409aa23281
|
https://github.com/titilambert/pyfido/blob/8302b76f4d9d7b05b97926c003ca02409aa23281/pyfido/client.py#L170-L200
|
238,015
|
titilambert/pyfido
|
pyfido/client.py
|
FidoClient._get_fido_dollar
|
def _get_fido_dollar(self, account_number, number):
"""Get current Fido dollar balance."""
# Prepare data
data = json.dumps({"fidoDollarBalanceFormList":
[{"phoneNumber": number,
"accountNumber": account_number}]})
# Prepare headers
headers_json = self._headers.copy()
headers_json["Content-Type"] = "application/json;charset=UTF-8"
# Http request
try:
raw_res = yield from self._session.post(FIDO_DOLLAR_URL,
data=data,
headers=headers_json,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not get fido dollar")
# Get fido dollar
try:
json_content = yield from raw_res.json()
fido_dollar_str = json_content\
.get("fidoDollarBalanceInfoList", [{}])[0]\
.get("fidoDollarBalance")
except (OSError, ValueError):
raise PyFidoError("Can not get fido dollar as json")
if fido_dollar_str is None:
raise PyFidoError("Can not get fido dollar")
# Casting to float
try:
fido_dollar = float(fido_dollar_str)
except ValueError:
raise PyFidoError("Can not get fido dollar")
return fido_dollar
|
python
|
def _get_fido_dollar(self, account_number, number):
"""Get current Fido dollar balance."""
# Prepare data
data = json.dumps({"fidoDollarBalanceFormList":
[{"phoneNumber": number,
"accountNumber": account_number}]})
# Prepare headers
headers_json = self._headers.copy()
headers_json["Content-Type"] = "application/json;charset=UTF-8"
# Http request
try:
raw_res = yield from self._session.post(FIDO_DOLLAR_URL,
data=data,
headers=headers_json,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not get fido dollar")
# Get fido dollar
try:
json_content = yield from raw_res.json()
fido_dollar_str = json_content\
.get("fidoDollarBalanceInfoList", [{}])[0]\
.get("fidoDollarBalance")
except (OSError, ValueError):
raise PyFidoError("Can not get fido dollar as json")
if fido_dollar_str is None:
raise PyFidoError("Can not get fido dollar")
# Casting to float
try:
fido_dollar = float(fido_dollar_str)
except ValueError:
raise PyFidoError("Can not get fido dollar")
return fido_dollar
|
[
"def",
"_get_fido_dollar",
"(",
"self",
",",
"account_number",
",",
"number",
")",
":",
"# Prepare data",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"fidoDollarBalanceFormList\"",
":",
"[",
"{",
"\"phoneNumber\"",
":",
"number",
",",
"\"accountNumber\"",
":",
"account_number",
"}",
"]",
"}",
")",
"# Prepare headers",
"headers_json",
"=",
"self",
".",
"_headers",
".",
"copy",
"(",
")",
"headers_json",
"[",
"\"Content-Type\"",
"]",
"=",
"\"application/json;charset=UTF-8\"",
"# Http request",
"try",
":",
"raw_res",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
"post",
"(",
"FIDO_DOLLAR_URL",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers_json",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"except",
"OSError",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get fido dollar\"",
")",
"# Get fido dollar",
"try",
":",
"json_content",
"=",
"yield",
"from",
"raw_res",
".",
"json",
"(",
")",
"fido_dollar_str",
"=",
"json_content",
".",
"get",
"(",
"\"fidoDollarBalanceInfoList\"",
",",
"[",
"{",
"}",
"]",
")",
"[",
"0",
"]",
".",
"get",
"(",
"\"fidoDollarBalance\"",
")",
"except",
"(",
"OSError",
",",
"ValueError",
")",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get fido dollar as json\"",
")",
"if",
"fido_dollar_str",
"is",
"None",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get fido dollar\"",
")",
"# Casting to float",
"try",
":",
"fido_dollar",
"=",
"float",
"(",
"fido_dollar_str",
")",
"except",
"ValueError",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get fido dollar\"",
")",
"return",
"fido_dollar"
] |
Get current Fido dollar balance.
|
[
"Get",
"current",
"Fido",
"dollar",
"balance",
"."
] |
8302b76f4d9d7b05b97926c003ca02409aa23281
|
https://github.com/titilambert/pyfido/blob/8302b76f4d9d7b05b97926c003ca02409aa23281/pyfido/client.py#L203-L236
|
238,016
|
titilambert/pyfido
|
pyfido/client.py
|
FidoClient._get_usage
|
def _get_usage(self, account_number, number):
"""Get Fido usage.
Get the following data
- talk
- text
- data
Roaming data is not supported yet
"""
# Prepare data
data = {"ctn": number,
"language": "en-US",
"accountNumber": account_number}
# Http request
try:
raw_res = yield from self._session.post(USAGE_URL,
data=data,
headers=self._headers,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not get usage")
# Load answer as json
try:
output = yield from raw_res.json()
except (OSError, ValueError):
raise PyFidoError("Can not get usage as json")
# Format data
ret_data = {}
for data_name, keys in DATA_MAP.items():
key, subkey = keys
for data in output.get(key)[0].get('wirelessUsageSummaryInfoList'):
if data.get('usageSummaryType') == subkey:
# Prepare keys:
used_key = "{}_used".format(data_name)
remaining_key = "{}_remaining".format(data_name)
limit_key = "{}_limit".format(data_name)
# Get values
ret_data[used_key] = data.get('used', 0.0)
if data.get('remaining') >= 0:
ret_data[remaining_key] = data.get('remaining')
else:
ret_data[remaining_key] = None
if data.get('total') >= 0:
ret_data[limit_key] = data.get('total')
else:
ret_data[limit_key] = None
return ret_data
|
python
|
def _get_usage(self, account_number, number):
"""Get Fido usage.
Get the following data
- talk
- text
- data
Roaming data is not supported yet
"""
# Prepare data
data = {"ctn": number,
"language": "en-US",
"accountNumber": account_number}
# Http request
try:
raw_res = yield from self._session.post(USAGE_URL,
data=data,
headers=self._headers,
timeout=self._timeout)
except OSError:
raise PyFidoError("Can not get usage")
# Load answer as json
try:
output = yield from raw_res.json()
except (OSError, ValueError):
raise PyFidoError("Can not get usage as json")
# Format data
ret_data = {}
for data_name, keys in DATA_MAP.items():
key, subkey = keys
for data in output.get(key)[0].get('wirelessUsageSummaryInfoList'):
if data.get('usageSummaryType') == subkey:
# Prepare keys:
used_key = "{}_used".format(data_name)
remaining_key = "{}_remaining".format(data_name)
limit_key = "{}_limit".format(data_name)
# Get values
ret_data[used_key] = data.get('used', 0.0)
if data.get('remaining') >= 0:
ret_data[remaining_key] = data.get('remaining')
else:
ret_data[remaining_key] = None
if data.get('total') >= 0:
ret_data[limit_key] = data.get('total')
else:
ret_data[limit_key] = None
return ret_data
|
[
"def",
"_get_usage",
"(",
"self",
",",
"account_number",
",",
"number",
")",
":",
"# Prepare data",
"data",
"=",
"{",
"\"ctn\"",
":",
"number",
",",
"\"language\"",
":",
"\"en-US\"",
",",
"\"accountNumber\"",
":",
"account_number",
"}",
"# Http request",
"try",
":",
"raw_res",
"=",
"yield",
"from",
"self",
".",
"_session",
".",
"post",
"(",
"USAGE_URL",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"self",
".",
"_headers",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
"except",
"OSError",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get usage\"",
")",
"# Load answer as json",
"try",
":",
"output",
"=",
"yield",
"from",
"raw_res",
".",
"json",
"(",
")",
"except",
"(",
"OSError",
",",
"ValueError",
")",
":",
"raise",
"PyFidoError",
"(",
"\"Can not get usage as json\"",
")",
"# Format data",
"ret_data",
"=",
"{",
"}",
"for",
"data_name",
",",
"keys",
"in",
"DATA_MAP",
".",
"items",
"(",
")",
":",
"key",
",",
"subkey",
"=",
"keys",
"for",
"data",
"in",
"output",
".",
"get",
"(",
"key",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'wirelessUsageSummaryInfoList'",
")",
":",
"if",
"data",
".",
"get",
"(",
"'usageSummaryType'",
")",
"==",
"subkey",
":",
"# Prepare keys:",
"used_key",
"=",
"\"{}_used\"",
".",
"format",
"(",
"data_name",
")",
"remaining_key",
"=",
"\"{}_remaining\"",
".",
"format",
"(",
"data_name",
")",
"limit_key",
"=",
"\"{}_limit\"",
".",
"format",
"(",
"data_name",
")",
"# Get values",
"ret_data",
"[",
"used_key",
"]",
"=",
"data",
".",
"get",
"(",
"'used'",
",",
"0.0",
")",
"if",
"data",
".",
"get",
"(",
"'remaining'",
")",
">=",
"0",
":",
"ret_data",
"[",
"remaining_key",
"]",
"=",
"data",
".",
"get",
"(",
"'remaining'",
")",
"else",
":",
"ret_data",
"[",
"remaining_key",
"]",
"=",
"None",
"if",
"data",
".",
"get",
"(",
"'total'",
")",
">=",
"0",
":",
"ret_data",
"[",
"limit_key",
"]",
"=",
"data",
".",
"get",
"(",
"'total'",
")",
"else",
":",
"ret_data",
"[",
"limit_key",
"]",
"=",
"None",
"return",
"ret_data"
] |
Get Fido usage.
Get the following data
- talk
- text
- data
Roaming data is not supported yet
|
[
"Get",
"Fido",
"usage",
"."
] |
8302b76f4d9d7b05b97926c003ca02409aa23281
|
https://github.com/titilambert/pyfido/blob/8302b76f4d9d7b05b97926c003ca02409aa23281/pyfido/client.py#L239-L287
|
238,017
|
titilambert/pyfido
|
pyfido/client.py
|
FidoClient.fetch_data
|
def fetch_data(self):
"""Fetch the latest data from Fido."""
# Get http session
yield from self._get_httpsession()
# Post login page
yield from self._post_login_page()
# Get token
token_uuid = yield from self._get_token()
# Get account number
account_number = yield from self._get_account_number(*token_uuid)
# List phone numbers
self._phone_numbers = yield from self._list_phone_numbers(account_number)
# Get balance
balance = yield from self._get_balance(account_number)
self._data['balance'] = balance
# Get fido dollar
for number in self._phone_numbers:
fido_dollar = yield from self._get_fido_dollar(account_number,
number)
self._data[number]= {'fido_dollar': fido_dollar}
# Get usage
for number in self._phone_numbers:
usage = yield from self._get_usage(account_number, number)
self._data[number].update(usage)
|
python
|
def fetch_data(self):
"""Fetch the latest data from Fido."""
# Get http session
yield from self._get_httpsession()
# Post login page
yield from self._post_login_page()
# Get token
token_uuid = yield from self._get_token()
# Get account number
account_number = yield from self._get_account_number(*token_uuid)
# List phone numbers
self._phone_numbers = yield from self._list_phone_numbers(account_number)
# Get balance
balance = yield from self._get_balance(account_number)
self._data['balance'] = balance
# Get fido dollar
for number in self._phone_numbers:
fido_dollar = yield from self._get_fido_dollar(account_number,
number)
self._data[number]= {'fido_dollar': fido_dollar}
# Get usage
for number in self._phone_numbers:
usage = yield from self._get_usage(account_number, number)
self._data[number].update(usage)
|
[
"def",
"fetch_data",
"(",
"self",
")",
":",
"# Get http session",
"yield",
"from",
"self",
".",
"_get_httpsession",
"(",
")",
"# Post login page",
"yield",
"from",
"self",
".",
"_post_login_page",
"(",
")",
"# Get token",
"token_uuid",
"=",
"yield",
"from",
"self",
".",
"_get_token",
"(",
")",
"# Get account number",
"account_number",
"=",
"yield",
"from",
"self",
".",
"_get_account_number",
"(",
"*",
"token_uuid",
")",
"# List phone numbers",
"self",
".",
"_phone_numbers",
"=",
"yield",
"from",
"self",
".",
"_list_phone_numbers",
"(",
"account_number",
")",
"# Get balance",
"balance",
"=",
"yield",
"from",
"self",
".",
"_get_balance",
"(",
"account_number",
")",
"self",
".",
"_data",
"[",
"'balance'",
"]",
"=",
"balance",
"# Get fido dollar",
"for",
"number",
"in",
"self",
".",
"_phone_numbers",
":",
"fido_dollar",
"=",
"yield",
"from",
"self",
".",
"_get_fido_dollar",
"(",
"account_number",
",",
"number",
")",
"self",
".",
"_data",
"[",
"number",
"]",
"=",
"{",
"'fido_dollar'",
":",
"fido_dollar",
"}",
"# Get usage",
"for",
"number",
"in",
"self",
".",
"_phone_numbers",
":",
"usage",
"=",
"yield",
"from",
"self",
".",
"_get_usage",
"(",
"account_number",
",",
"number",
")",
"self",
".",
"_data",
"[",
"number",
"]",
".",
"update",
"(",
"usage",
")"
] |
Fetch the latest data from Fido.
|
[
"Fetch",
"the",
"latest",
"data",
"from",
"Fido",
"."
] |
8302b76f4d9d7b05b97926c003ca02409aa23281
|
https://github.com/titilambert/pyfido/blob/8302b76f4d9d7b05b97926c003ca02409aa23281/pyfido/client.py#L290-L313
|
238,018
|
aleontiev/dj
|
dj/utils/system.py
|
execute
|
def execute(
command,
abort=True,
capture=False,
verbose=False,
echo=False,
stream=None,
):
"""Run a command locally.
Arguments:
command: a command to execute.
abort: If True, a non-zero return code will trigger an exception.
capture: If True, returns the output of the command.
If False, returns a subprocess result.
echo: if True, prints the command before executing it.
verbose: If True, prints the output of the command.
stream: If set, stdout/stderr will be redirected to the given stream.
Ignored if `capture` is True.
"""
stream = stream or sys.stdout
if echo:
out = stream
out.write(u'$ %s' % command)
# Capture stdout and stderr in the same stream
command = u'%s 2>&1' % command
if verbose:
out = stream
err = stream
else:
out = subprocess.PIPE
err = subprocess.PIPE
process = subprocess.Popen(
command,
shell=True,
stdout=out,
stderr=err,
)
# propagate SIGTERM to all child processes within
# the process group. this prevents subprocesses from
# being orphaned when the current process is terminated
signal.signal(
signal.SIGTERM,
make_terminate_handler(process)
)
# Wait for the process to complete
stdout, _ = process.communicate()
stdout = stdout.strip() if stdout else ''
if not isinstance(stdout, unicode):
stdout = stdout.decode('utf-8')
if abort and process.returncode != 0:
message = (
u'Error #%d running "%s"%s' % (
process.returncode,
command,
':\n====================\n'
'%s\n'
'====================\n' % (
stdout
) if stdout else ''
)
)
raise Exception(message)
if capture:
return stdout
else:
return process
|
python
|
def execute(
command,
abort=True,
capture=False,
verbose=False,
echo=False,
stream=None,
):
"""Run a command locally.
Arguments:
command: a command to execute.
abort: If True, a non-zero return code will trigger an exception.
capture: If True, returns the output of the command.
If False, returns a subprocess result.
echo: if True, prints the command before executing it.
verbose: If True, prints the output of the command.
stream: If set, stdout/stderr will be redirected to the given stream.
Ignored if `capture` is True.
"""
stream = stream or sys.stdout
if echo:
out = stream
out.write(u'$ %s' % command)
# Capture stdout and stderr in the same stream
command = u'%s 2>&1' % command
if verbose:
out = stream
err = stream
else:
out = subprocess.PIPE
err = subprocess.PIPE
process = subprocess.Popen(
command,
shell=True,
stdout=out,
stderr=err,
)
# propagate SIGTERM to all child processes within
# the process group. this prevents subprocesses from
# being orphaned when the current process is terminated
signal.signal(
signal.SIGTERM,
make_terminate_handler(process)
)
# Wait for the process to complete
stdout, _ = process.communicate()
stdout = stdout.strip() if stdout else ''
if not isinstance(stdout, unicode):
stdout = stdout.decode('utf-8')
if abort and process.returncode != 0:
message = (
u'Error #%d running "%s"%s' % (
process.returncode,
command,
':\n====================\n'
'%s\n'
'====================\n' % (
stdout
) if stdout else ''
)
)
raise Exception(message)
if capture:
return stdout
else:
return process
|
[
"def",
"execute",
"(",
"command",
",",
"abort",
"=",
"True",
",",
"capture",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"echo",
"=",
"False",
",",
"stream",
"=",
"None",
",",
")",
":",
"stream",
"=",
"stream",
"or",
"sys",
".",
"stdout",
"if",
"echo",
":",
"out",
"=",
"stream",
"out",
".",
"write",
"(",
"u'$ %s'",
"%",
"command",
")",
"# Capture stdout and stderr in the same stream",
"command",
"=",
"u'%s 2>&1'",
"%",
"command",
"if",
"verbose",
":",
"out",
"=",
"stream",
"err",
"=",
"stream",
"else",
":",
"out",
"=",
"subprocess",
".",
"PIPE",
"err",
"=",
"subprocess",
".",
"PIPE",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"out",
",",
"stderr",
"=",
"err",
",",
")",
"# propagate SIGTERM to all child processes within",
"# the process group. this prevents subprocesses from",
"# being orphaned when the current process is terminated",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"make_terminate_handler",
"(",
"process",
")",
")",
"# Wait for the process to complete",
"stdout",
",",
"_",
"=",
"process",
".",
"communicate",
"(",
")",
"stdout",
"=",
"stdout",
".",
"strip",
"(",
")",
"if",
"stdout",
"else",
"''",
"if",
"not",
"isinstance",
"(",
"stdout",
",",
"unicode",
")",
":",
"stdout",
"=",
"stdout",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"abort",
"and",
"process",
".",
"returncode",
"!=",
"0",
":",
"message",
"=",
"(",
"u'Error #%d running \"%s\"%s'",
"%",
"(",
"process",
".",
"returncode",
",",
"command",
",",
"':\\n====================\\n'",
"'%s\\n'",
"'====================\\n'",
"%",
"(",
"stdout",
")",
"if",
"stdout",
"else",
"''",
")",
")",
"raise",
"Exception",
"(",
"message",
")",
"if",
"capture",
":",
"return",
"stdout",
"else",
":",
"return",
"process"
] |
Run a command locally.
Arguments:
command: a command to execute.
abort: If True, a non-zero return code will trigger an exception.
capture: If True, returns the output of the command.
If False, returns a subprocess result.
echo: if True, prints the command before executing it.
verbose: If True, prints the output of the command.
stream: If set, stdout/stderr will be redirected to the given stream.
Ignored if `capture` is True.
|
[
"Run",
"a",
"command",
"locally",
"."
] |
0612d442fdd8d472aea56466568b9857556ecb51
|
https://github.com/aleontiev/dj/blob/0612d442fdd8d472aea56466568b9857556ecb51/dj/utils/system.py#L76-L148
|
238,019
|
amol-/tgext.mailer
|
tgext/mailer/message.py
|
to_message
|
def to_message(base):
"""
Given a MailBase, this will construct a MIME part that is canonicalized for
use with the Python email API.
"""
ctype, ctparams = base.get_content_type()
if not ctype:
if base.parts:
ctype = 'multipart/mixed'
else:
ctype = 'text/plain'
maintype, subtype = ctype.split('/')
is_text = maintype == 'text'
is_multipart = maintype == 'multipart'
if base.parts and not is_multipart:
raise RuntimeError(
'Content type should be multipart, not %r' % ctype
)
body = base.get_body()
ctenc = base.get_transfer_encoding()
charset = ctparams.get('charset')
if is_multipart:
out = MIMEMultipart(subtype, **ctparams)
else:
out = MIMENonMultipart(maintype, subtype, **ctparams)
if ctenc:
out['Content-Transfer-Encoding'] = ctenc
if isinstance(body, text_type):
if not charset:
if is_text:
charset, _ = best_charset(body)
else:
charset = 'utf-8'
if PY2:
body = body.encode(charset)
else: # pragma: no cover
body = body.encode(charset, 'surrogateescape')
if body is not None:
if ctenc:
body = transfer_encode(ctenc, body)
if not PY2: # pragma: no cover
body = body.decode(charset or 'ascii', 'replace')
out.set_payload(body, charset)
for k in base.keys(): # returned sorted
value = base[k]
if not value:
continue
out[k] = value
cdisp, cdisp_params = base.get_content_disposition()
if cdisp:
out.add_header('Content-Disposition', cdisp, **cdisp_params)
# go through the children
for part in base.parts:
sub = to_message(part)
out.attach(sub)
return out
|
python
|
def to_message(base):
"""
Given a MailBase, this will construct a MIME part that is canonicalized for
use with the Python email API.
"""
ctype, ctparams = base.get_content_type()
if not ctype:
if base.parts:
ctype = 'multipart/mixed'
else:
ctype = 'text/plain'
maintype, subtype = ctype.split('/')
is_text = maintype == 'text'
is_multipart = maintype == 'multipart'
if base.parts and not is_multipart:
raise RuntimeError(
'Content type should be multipart, not %r' % ctype
)
body = base.get_body()
ctenc = base.get_transfer_encoding()
charset = ctparams.get('charset')
if is_multipart:
out = MIMEMultipart(subtype, **ctparams)
else:
out = MIMENonMultipart(maintype, subtype, **ctparams)
if ctenc:
out['Content-Transfer-Encoding'] = ctenc
if isinstance(body, text_type):
if not charset:
if is_text:
charset, _ = best_charset(body)
else:
charset = 'utf-8'
if PY2:
body = body.encode(charset)
else: # pragma: no cover
body = body.encode(charset, 'surrogateescape')
if body is not None:
if ctenc:
body = transfer_encode(ctenc, body)
if not PY2: # pragma: no cover
body = body.decode(charset or 'ascii', 'replace')
out.set_payload(body, charset)
for k in base.keys(): # returned sorted
value = base[k]
if not value:
continue
out[k] = value
cdisp, cdisp_params = base.get_content_disposition()
if cdisp:
out.add_header('Content-Disposition', cdisp, **cdisp_params)
# go through the children
for part in base.parts:
sub = to_message(part)
out.attach(sub)
return out
|
[
"def",
"to_message",
"(",
"base",
")",
":",
"ctype",
",",
"ctparams",
"=",
"base",
".",
"get_content_type",
"(",
")",
"if",
"not",
"ctype",
":",
"if",
"base",
".",
"parts",
":",
"ctype",
"=",
"'multipart/mixed'",
"else",
":",
"ctype",
"=",
"'text/plain'",
"maintype",
",",
"subtype",
"=",
"ctype",
".",
"split",
"(",
"'/'",
")",
"is_text",
"=",
"maintype",
"==",
"'text'",
"is_multipart",
"=",
"maintype",
"==",
"'multipart'",
"if",
"base",
".",
"parts",
"and",
"not",
"is_multipart",
":",
"raise",
"RuntimeError",
"(",
"'Content type should be multipart, not %r'",
"%",
"ctype",
")",
"body",
"=",
"base",
".",
"get_body",
"(",
")",
"ctenc",
"=",
"base",
".",
"get_transfer_encoding",
"(",
")",
"charset",
"=",
"ctparams",
".",
"get",
"(",
"'charset'",
")",
"if",
"is_multipart",
":",
"out",
"=",
"MIMEMultipart",
"(",
"subtype",
",",
"*",
"*",
"ctparams",
")",
"else",
":",
"out",
"=",
"MIMENonMultipart",
"(",
"maintype",
",",
"subtype",
",",
"*",
"*",
"ctparams",
")",
"if",
"ctenc",
":",
"out",
"[",
"'Content-Transfer-Encoding'",
"]",
"=",
"ctenc",
"if",
"isinstance",
"(",
"body",
",",
"text_type",
")",
":",
"if",
"not",
"charset",
":",
"if",
"is_text",
":",
"charset",
",",
"_",
"=",
"best_charset",
"(",
"body",
")",
"else",
":",
"charset",
"=",
"'utf-8'",
"if",
"PY2",
":",
"body",
"=",
"body",
".",
"encode",
"(",
"charset",
")",
"else",
":",
"# pragma: no cover",
"body",
"=",
"body",
".",
"encode",
"(",
"charset",
",",
"'surrogateescape'",
")",
"if",
"body",
"is",
"not",
"None",
":",
"if",
"ctenc",
":",
"body",
"=",
"transfer_encode",
"(",
"ctenc",
",",
"body",
")",
"if",
"not",
"PY2",
":",
"# pragma: no cover",
"body",
"=",
"body",
".",
"decode",
"(",
"charset",
"or",
"'ascii'",
",",
"'replace'",
")",
"out",
".",
"set_payload",
"(",
"body",
",",
"charset",
")",
"for",
"k",
"in",
"base",
".",
"keys",
"(",
")",
":",
"# returned sorted",
"value",
"=",
"base",
"[",
"k",
"]",
"if",
"not",
"value",
":",
"continue",
"out",
"[",
"k",
"]",
"=",
"value",
"cdisp",
",",
"cdisp_params",
"=",
"base",
".",
"get_content_disposition",
"(",
")",
"if",
"cdisp",
":",
"out",
".",
"add_header",
"(",
"'Content-Disposition'",
",",
"cdisp",
",",
"*",
"*",
"cdisp_params",
")",
"# go through the children",
"for",
"part",
"in",
"base",
".",
"parts",
":",
"sub",
"=",
"to_message",
"(",
"part",
")",
"out",
".",
"attach",
"(",
"sub",
")",
"return",
"out"
] |
Given a MailBase, this will construct a MIME part that is canonicalized for
use with the Python email API.
|
[
"Given",
"a",
"MailBase",
"this",
"will",
"construct",
"a",
"MIME",
"part",
"that",
"is",
"canonicalized",
"for",
"use",
"with",
"the",
"Python",
"email",
"API",
"."
] |
4c452244969b98431e57d5ebba930f365006dfbd
|
https://github.com/amol-/tgext.mailer/blob/4c452244969b98431e57d5ebba930f365006dfbd/tgext/mailer/message.py#L425-L490
|
238,020
|
amol-/tgext.mailer
|
tgext/mailer/message.py
|
Message.to_message
|
def to_message(self):
"""
Returns raw email.Message instance. Validates message first.
"""
self.validate()
bodies = [(self.body, 'text/plain'), (self.html, 'text/html')]
for idx, (val, content_type) in enumerate(bodies):
if val is None:
bodies[idx] = None
elif isinstance(val, Attachment):
bodies[idx] = val.to_mailbase(content_type)
else:
# presumed to be a textual val
attachment = Attachment(
data=val,
content_type=content_type,
transfer_encoding='quoted-printable',
disposition='inline'
)
bodies[idx] = attachment.to_mailbase(content_type)
body, html = bodies
base = MailBase([
('To', ', '.join(self.recipients)),
('From', self.sender),
('Subject', self.subject),
])
# base represents the outermost mime part; it will be one of the
# following types:
#
# - a multipart/mixed type if there are attachments. this
# part will contain a single multipart/alternative type if there
# is both an html part and a plaintext part (the alternative part
# will contain both the text and html), it will contain
# a single text/plain part if there is only a plaintext part,
# or it will contain a single text/html part if there is only
# an html part. it will also contain N parts representing
# each attachment as children of the base mixed type.
#
# - a multipart/alternative type if there are no attachments but
# both an html part and a plaintext part. it will contain
# a single text/plain part if there is only a plaintext part,
# or it will contain a single text/html part if there is only
# an html part.
#
# - a text/plain type if there is only a plaintext part
#
# - a text/html type if there is only an html part
if self.cc:
base['Cc'] = ', '.join(self.cc)
if self.extra_headers:
base.update(dict(self.extra_headers))
if self.attachments:
base.set_content_type('multipart/mixed')
altpart = MailBase()
base.attach_part(altpart)
else:
altpart = base
if body and html:
altpart.set_content_type('multipart/alternative')
altpart.set_body(None)
# Per RFC2046, HTML part comes last in multipart/alternative
altpart.attach_part(body)
altpart.attach_part(html)
elif body is not None:
altpart.merge_part(body)
elif html is not None:
altpart.merge_part(html)
for attachment in self.attachments:
attachment_mailbase = attachment.to_mailbase()
base.attach_part(attachment_mailbase)
return to_message(base)
|
python
|
def to_message(self):
"""
Returns raw email.Message instance. Validates message first.
"""
self.validate()
bodies = [(self.body, 'text/plain'), (self.html, 'text/html')]
for idx, (val, content_type) in enumerate(bodies):
if val is None:
bodies[idx] = None
elif isinstance(val, Attachment):
bodies[idx] = val.to_mailbase(content_type)
else:
# presumed to be a textual val
attachment = Attachment(
data=val,
content_type=content_type,
transfer_encoding='quoted-printable',
disposition='inline'
)
bodies[idx] = attachment.to_mailbase(content_type)
body, html = bodies
base = MailBase([
('To', ', '.join(self.recipients)),
('From', self.sender),
('Subject', self.subject),
])
# base represents the outermost mime part; it will be one of the
# following types:
#
# - a multipart/mixed type if there are attachments. this
# part will contain a single multipart/alternative type if there
# is both an html part and a plaintext part (the alternative part
# will contain both the text and html), it will contain
# a single text/plain part if there is only a plaintext part,
# or it will contain a single text/html part if there is only
# an html part. it will also contain N parts representing
# each attachment as children of the base mixed type.
#
# - a multipart/alternative type if there are no attachments but
# both an html part and a plaintext part. it will contain
# a single text/plain part if there is only a plaintext part,
# or it will contain a single text/html part if there is only
# an html part.
#
# - a text/plain type if there is only a plaintext part
#
# - a text/html type if there is only an html part
if self.cc:
base['Cc'] = ', '.join(self.cc)
if self.extra_headers:
base.update(dict(self.extra_headers))
if self.attachments:
base.set_content_type('multipart/mixed')
altpart = MailBase()
base.attach_part(altpart)
else:
altpart = base
if body and html:
altpart.set_content_type('multipart/alternative')
altpart.set_body(None)
# Per RFC2046, HTML part comes last in multipart/alternative
altpart.attach_part(body)
altpart.attach_part(html)
elif body is not None:
altpart.merge_part(body)
elif html is not None:
altpart.merge_part(html)
for attachment in self.attachments:
attachment_mailbase = attachment.to_mailbase()
base.attach_part(attachment_mailbase)
return to_message(base)
|
[
"def",
"to_message",
"(",
"self",
")",
":",
"self",
".",
"validate",
"(",
")",
"bodies",
"=",
"[",
"(",
"self",
".",
"body",
",",
"'text/plain'",
")",
",",
"(",
"self",
".",
"html",
",",
"'text/html'",
")",
"]",
"for",
"idx",
",",
"(",
"val",
",",
"content_type",
")",
"in",
"enumerate",
"(",
"bodies",
")",
":",
"if",
"val",
"is",
"None",
":",
"bodies",
"[",
"idx",
"]",
"=",
"None",
"elif",
"isinstance",
"(",
"val",
",",
"Attachment",
")",
":",
"bodies",
"[",
"idx",
"]",
"=",
"val",
".",
"to_mailbase",
"(",
"content_type",
")",
"else",
":",
"# presumed to be a textual val",
"attachment",
"=",
"Attachment",
"(",
"data",
"=",
"val",
",",
"content_type",
"=",
"content_type",
",",
"transfer_encoding",
"=",
"'quoted-printable'",
",",
"disposition",
"=",
"'inline'",
")",
"bodies",
"[",
"idx",
"]",
"=",
"attachment",
".",
"to_mailbase",
"(",
"content_type",
")",
"body",
",",
"html",
"=",
"bodies",
"base",
"=",
"MailBase",
"(",
"[",
"(",
"'To'",
",",
"', '",
".",
"join",
"(",
"self",
".",
"recipients",
")",
")",
",",
"(",
"'From'",
",",
"self",
".",
"sender",
")",
",",
"(",
"'Subject'",
",",
"self",
".",
"subject",
")",
",",
"]",
")",
"# base represents the outermost mime part; it will be one of the",
"# following types:",
"#",
"# - a multipart/mixed type if there are attachments. this",
"# part will contain a single multipart/alternative type if there",
"# is both an html part and a plaintext part (the alternative part",
"# will contain both the text and html), it will contain",
"# a single text/plain part if there is only a plaintext part,",
"# or it will contain a single text/html part if there is only",
"# an html part. it will also contain N parts representing",
"# each attachment as children of the base mixed type.",
"#",
"# - a multipart/alternative type if there are no attachments but",
"# both an html part and a plaintext part. it will contain",
"# a single text/plain part if there is only a plaintext part,",
"# or it will contain a single text/html part if there is only",
"# an html part.",
"#",
"# - a text/plain type if there is only a plaintext part",
"#",
"# - a text/html type if there is only an html part",
"if",
"self",
".",
"cc",
":",
"base",
"[",
"'Cc'",
"]",
"=",
"', '",
".",
"join",
"(",
"self",
".",
"cc",
")",
"if",
"self",
".",
"extra_headers",
":",
"base",
".",
"update",
"(",
"dict",
"(",
"self",
".",
"extra_headers",
")",
")",
"if",
"self",
".",
"attachments",
":",
"base",
".",
"set_content_type",
"(",
"'multipart/mixed'",
")",
"altpart",
"=",
"MailBase",
"(",
")",
"base",
".",
"attach_part",
"(",
"altpart",
")",
"else",
":",
"altpart",
"=",
"base",
"if",
"body",
"and",
"html",
":",
"altpart",
".",
"set_content_type",
"(",
"'multipart/alternative'",
")",
"altpart",
".",
"set_body",
"(",
"None",
")",
"# Per RFC2046, HTML part comes last in multipart/alternative",
"altpart",
".",
"attach_part",
"(",
"body",
")",
"altpart",
".",
"attach_part",
"(",
"html",
")",
"elif",
"body",
"is",
"not",
"None",
":",
"altpart",
".",
"merge_part",
"(",
"body",
")",
"elif",
"html",
"is",
"not",
"None",
":",
"altpart",
".",
"merge_part",
"(",
"html",
")",
"for",
"attachment",
"in",
"self",
".",
"attachments",
":",
"attachment_mailbase",
"=",
"attachment",
".",
"to_mailbase",
"(",
")",
"base",
".",
"attach_part",
"(",
"attachment_mailbase",
")",
"return",
"to_message",
"(",
"base",
")"
] |
Returns raw email.Message instance. Validates message first.
|
[
"Returns",
"raw",
"email",
".",
"Message",
"instance",
".",
"Validates",
"message",
"first",
"."
] |
4c452244969b98431e57d5ebba930f365006dfbd
|
https://github.com/amol-/tgext.mailer/blob/4c452244969b98431e57d5ebba930f365006dfbd/tgext/mailer/message.py#L189-L271
|
238,021
|
amol-/tgext.mailer
|
tgext/mailer/message.py
|
Message.is_bad_headers
|
def is_bad_headers(self):
"""
Checks for bad headers i.e. newlines in subject, sender or recipients.
"""
headers = [self.subject, self.sender]
headers += list(self.send_to)
headers += dict(self.extra_headers).values()
for val in headers:
for c in '\r\n':
if c in val:
return True
return False
|
python
|
def is_bad_headers(self):
"""
Checks for bad headers i.e. newlines in subject, sender or recipients.
"""
headers = [self.subject, self.sender]
headers += list(self.send_to)
headers += dict(self.extra_headers).values()
for val in headers:
for c in '\r\n':
if c in val:
return True
return False
|
[
"def",
"is_bad_headers",
"(",
"self",
")",
":",
"headers",
"=",
"[",
"self",
".",
"subject",
",",
"self",
".",
"sender",
"]",
"headers",
"+=",
"list",
"(",
"self",
".",
"send_to",
")",
"headers",
"+=",
"dict",
"(",
"self",
".",
"extra_headers",
")",
".",
"values",
"(",
")",
"for",
"val",
"in",
"headers",
":",
"for",
"c",
"in",
"'\\r\\n'",
":",
"if",
"c",
"in",
"val",
":",
"return",
"True",
"return",
"False"
] |
Checks for bad headers i.e. newlines in subject, sender or recipients.
|
[
"Checks",
"for",
"bad",
"headers",
"i",
".",
"e",
".",
"newlines",
"in",
"subject",
"sender",
"or",
"recipients",
"."
] |
4c452244969b98431e57d5ebba930f365006dfbd
|
https://github.com/amol-/tgext.mailer/blob/4c452244969b98431e57d5ebba930f365006dfbd/tgext/mailer/message.py#L273-L286
|
238,022
|
amol-/tgext.mailer
|
tgext/mailer/message.py
|
Message.validate
|
def validate(self):
"""
Checks if message is valid and raises appropriate exception.
"""
if not (self.recipients or self.cc or self.bcc):
raise InvalidMessage("No recipients have been added")
if not self.body and not self.html:
raise InvalidMessage("No body has been set")
if not self.sender:
raise InvalidMessage("No sender address has been set")
if self.is_bad_headers():
raise BadHeaders
|
python
|
def validate(self):
"""
Checks if message is valid and raises appropriate exception.
"""
if not (self.recipients or self.cc or self.bcc):
raise InvalidMessage("No recipients have been added")
if not self.body and not self.html:
raise InvalidMessage("No body has been set")
if not self.sender:
raise InvalidMessage("No sender address has been set")
if self.is_bad_headers():
raise BadHeaders
|
[
"def",
"validate",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"recipients",
"or",
"self",
".",
"cc",
"or",
"self",
".",
"bcc",
")",
":",
"raise",
"InvalidMessage",
"(",
"\"No recipients have been added\"",
")",
"if",
"not",
"self",
".",
"body",
"and",
"not",
"self",
".",
"html",
":",
"raise",
"InvalidMessage",
"(",
"\"No body has been set\"",
")",
"if",
"not",
"self",
".",
"sender",
":",
"raise",
"InvalidMessage",
"(",
"\"No sender address has been set\"",
")",
"if",
"self",
".",
"is_bad_headers",
"(",
")",
":",
"raise",
"BadHeaders"
] |
Checks if message is valid and raises appropriate exception.
|
[
"Checks",
"if",
"message",
"is",
"valid",
"and",
"raises",
"appropriate",
"exception",
"."
] |
4c452244969b98431e57d5ebba930f365006dfbd
|
https://github.com/amol-/tgext.mailer/blob/4c452244969b98431e57d5ebba930f365006dfbd/tgext/mailer/message.py#L288-L303
|
238,023
|
amol-/tgext.mailer
|
tgext/mailer/mailer.py
|
DebugMailer.from_settings
|
def from_settings(cls, settings, prefix='mail.'):
"""Create a new instance of 'DebugMailer' from settings dict.
:param settings: a settings dict-like
:param prefix: prefix separating 'tgext.mailer' settings
"""
settings = settings or {}
top_level_directory = settings.get(prefix+'top_level_directory')
if top_level_directory is None:
raise ValueError("DebugMailer: must specify "
"'%stop_level_directory'" % prefix)
return cls(top_level_directory)
|
python
|
def from_settings(cls, settings, prefix='mail.'):
"""Create a new instance of 'DebugMailer' from settings dict.
:param settings: a settings dict-like
:param prefix: prefix separating 'tgext.mailer' settings
"""
settings = settings or {}
top_level_directory = settings.get(prefix+'top_level_directory')
if top_level_directory is None:
raise ValueError("DebugMailer: must specify "
"'%stop_level_directory'" % prefix)
return cls(top_level_directory)
|
[
"def",
"from_settings",
"(",
"cls",
",",
"settings",
",",
"prefix",
"=",
"'mail.'",
")",
":",
"settings",
"=",
"settings",
"or",
"{",
"}",
"top_level_directory",
"=",
"settings",
".",
"get",
"(",
"prefix",
"+",
"'top_level_directory'",
")",
"if",
"top_level_directory",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"DebugMailer: must specify \"",
"\"'%stop_level_directory'\"",
"%",
"prefix",
")",
"return",
"cls",
"(",
"top_level_directory",
")"
] |
Create a new instance of 'DebugMailer' from settings dict.
:param settings: a settings dict-like
:param prefix: prefix separating 'tgext.mailer' settings
|
[
"Create",
"a",
"new",
"instance",
"of",
"DebugMailer",
"from",
"settings",
"dict",
"."
] |
4c452244969b98431e57d5ebba930f365006dfbd
|
https://github.com/amol-/tgext.mailer/blob/4c452244969b98431e57d5ebba930f365006dfbd/tgext/mailer/mailer.py#L27-L38
|
238,024
|
amol-/tgext.mailer
|
tgext/mailer/mailer.py
|
DebugMailer._send
|
def _send(self, message, fail_silently=False):
"""Save message to a file for debugging
"""
seeds = '1234567890qwertyuiopasdfghjklzxcvbnm'
file_part1 = datetime.now().strftime('%Y%m%d%H%M%S')
file_part2 = ''.join(sample(seeds, 4))
filename = join(self.tld, '%s_%s.msg' % (file_part1, file_part2))
with open(filename, 'w') as fd:
fd.write(str(message.to_message()))
|
python
|
def _send(self, message, fail_silently=False):
"""Save message to a file for debugging
"""
seeds = '1234567890qwertyuiopasdfghjklzxcvbnm'
file_part1 = datetime.now().strftime('%Y%m%d%H%M%S')
file_part2 = ''.join(sample(seeds, 4))
filename = join(self.tld, '%s_%s.msg' % (file_part1, file_part2))
with open(filename, 'w') as fd:
fd.write(str(message.to_message()))
|
[
"def",
"_send",
"(",
"self",
",",
"message",
",",
"fail_silently",
"=",
"False",
")",
":",
"seeds",
"=",
"'1234567890qwertyuiopasdfghjklzxcvbnm'",
"file_part1",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%Y%m%d%H%M%S'",
")",
"file_part2",
"=",
"''",
".",
"join",
"(",
"sample",
"(",
"seeds",
",",
"4",
")",
")",
"filename",
"=",
"join",
"(",
"self",
".",
"tld",
",",
"'%s_%s.msg'",
"%",
"(",
"file_part1",
",",
"file_part2",
")",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fd",
":",
"fd",
".",
"write",
"(",
"str",
"(",
"message",
".",
"to_message",
"(",
")",
")",
")"
] |
Save message to a file for debugging
|
[
"Save",
"message",
"to",
"a",
"file",
"for",
"debugging"
] |
4c452244969b98431e57d5ebba930f365006dfbd
|
https://github.com/amol-/tgext.mailer/blob/4c452244969b98431e57d5ebba930f365006dfbd/tgext/mailer/mailer.py#L40-L48
|
238,025
|
amol-/tgext.mailer
|
tgext/mailer/mailer.py
|
Mailer.from_settings
|
def from_settings(cls, settings, prefix='mail.'):
"""Create a new instance of 'Mailer' from settings dict.
:param settings: a settings dict-like
:param prefix: prefix separating 'tgext.mailer' settings
"""
settings = settings or {}
kwarg_names = [prefix + k for k in (
'host', 'port', 'username',
'password', 'tls', 'ssl', 'keyfile',
'certfile', 'queue_path', 'debug', 'default_sender')]
size = len(prefix)
kwargs = dict(((k[size:], settings[k]) for k in settings.keys() if
k in kwarg_names))
for key in ('tls', 'ssl'):
val = kwargs.get(key)
if val:
kwargs[key] = asbool(val)
return cls(**kwargs)
|
python
|
def from_settings(cls, settings, prefix='mail.'):
"""Create a new instance of 'Mailer' from settings dict.
:param settings: a settings dict-like
:param prefix: prefix separating 'tgext.mailer' settings
"""
settings = settings or {}
kwarg_names = [prefix + k for k in (
'host', 'port', 'username',
'password', 'tls', 'ssl', 'keyfile',
'certfile', 'queue_path', 'debug', 'default_sender')]
size = len(prefix)
kwargs = dict(((k[size:], settings[k]) for k in settings.keys() if
k in kwarg_names))
for key in ('tls', 'ssl'):
val = kwargs.get(key)
if val:
kwargs[key] = asbool(val)
return cls(**kwargs)
|
[
"def",
"from_settings",
"(",
"cls",
",",
"settings",
",",
"prefix",
"=",
"'mail.'",
")",
":",
"settings",
"=",
"settings",
"or",
"{",
"}",
"kwarg_names",
"=",
"[",
"prefix",
"+",
"k",
"for",
"k",
"in",
"(",
"'host'",
",",
"'port'",
",",
"'username'",
",",
"'password'",
",",
"'tls'",
",",
"'ssl'",
",",
"'keyfile'",
",",
"'certfile'",
",",
"'queue_path'",
",",
"'debug'",
",",
"'default_sender'",
")",
"]",
"size",
"=",
"len",
"(",
"prefix",
")",
"kwargs",
"=",
"dict",
"(",
"(",
"(",
"k",
"[",
"size",
":",
"]",
",",
"settings",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"settings",
".",
"keys",
"(",
")",
"if",
"k",
"in",
"kwarg_names",
")",
")",
"for",
"key",
"in",
"(",
"'tls'",
",",
"'ssl'",
")",
":",
"val",
"=",
"kwargs",
".",
"get",
"(",
"key",
")",
"if",
"val",
":",
"kwargs",
"[",
"key",
"]",
"=",
"asbool",
"(",
"val",
")",
"return",
"cls",
"(",
"*",
"*",
"kwargs",
")"
] |
Create a new instance of 'Mailer' from settings dict.
:param settings: a settings dict-like
:param prefix: prefix separating 'tgext.mailer' settings
|
[
"Create",
"a",
"new",
"instance",
"of",
"Mailer",
"from",
"settings",
"dict",
"."
] |
4c452244969b98431e57d5ebba930f365006dfbd
|
https://github.com/amol-/tgext.mailer/blob/4c452244969b98431e57d5ebba930f365006dfbd/tgext/mailer/mailer.py#L182-L205
|
238,026
|
amol-/tgext.mailer
|
tgext/mailer/mailer.py
|
Mailer.send_immediately
|
def send_immediately(self, message, fail_silently=False):
"""Send a message immediately, outside the transaction manager.
If there is a connection error to the mail server this will have to
be handled manually. However if you pass ``fail_silently`` the error
will be swallowed.
:versionadded: 0.3
:param message: a 'Message' instance.
:param fail_silently: silently handle connection errors.
"""
try:
return self.smtp_mailer.send(*self._message_args(message))
except smtplib.socket.error:
if not fail_silently:
raise
|
python
|
def send_immediately(self, message, fail_silently=False):
"""Send a message immediately, outside the transaction manager.
If there is a connection error to the mail server this will have to
be handled manually. However if you pass ``fail_silently`` the error
will be swallowed.
:versionadded: 0.3
:param message: a 'Message' instance.
:param fail_silently: silently handle connection errors.
"""
try:
return self.smtp_mailer.send(*self._message_args(message))
except smtplib.socket.error:
if not fail_silently:
raise
|
[
"def",
"send_immediately",
"(",
"self",
",",
"message",
",",
"fail_silently",
"=",
"False",
")",
":",
"try",
":",
"return",
"self",
".",
"smtp_mailer",
".",
"send",
"(",
"*",
"self",
".",
"_message_args",
"(",
"message",
")",
")",
"except",
"smtplib",
".",
"socket",
".",
"error",
":",
"if",
"not",
"fail_silently",
":",
"raise"
] |
Send a message immediately, outside the transaction manager.
If there is a connection error to the mail server this will have to
be handled manually. However if you pass ``fail_silently`` the error
will be swallowed.
:versionadded: 0.3
:param message: a 'Message' instance.
:param fail_silently: silently handle connection errors.
|
[
"Send",
"a",
"message",
"immediately",
"outside",
"the",
"transaction",
"manager",
"."
] |
4c452244969b98431e57d5ebba930f365006dfbd
|
https://github.com/amol-/tgext.mailer/blob/4c452244969b98431e57d5ebba930f365006dfbd/tgext/mailer/mailer.py#L217-L234
|
238,027
|
amol-/tgext.mailer
|
tgext/mailer/mailer.py
|
Mailer.send_to_queue
|
def send_to_queue(self, message):
"""Add a message to a maildir queue.
In order to handle this, the setting 'mail.queue_path' must be
provided and must point to a valid maildir.
:param message: a 'Message' instance.
"""
if not self.queue_delivery:
raise RuntimeError("No queue_path provided")
return self.queue_delivery.send(*self._message_args(message))
|
python
|
def send_to_queue(self, message):
"""Add a message to a maildir queue.
In order to handle this, the setting 'mail.queue_path' must be
provided and must point to a valid maildir.
:param message: a 'Message' instance.
"""
if not self.queue_delivery:
raise RuntimeError("No queue_path provided")
return self.queue_delivery.send(*self._message_args(message))
|
[
"def",
"send_to_queue",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"self",
".",
"queue_delivery",
":",
"raise",
"RuntimeError",
"(",
"\"No queue_path provided\"",
")",
"return",
"self",
".",
"queue_delivery",
".",
"send",
"(",
"*",
"self",
".",
"_message_args",
"(",
"message",
")",
")"
] |
Add a message to a maildir queue.
In order to handle this, the setting 'mail.queue_path' must be
provided and must point to a valid maildir.
:param message: a 'Message' instance.
|
[
"Add",
"a",
"message",
"to",
"a",
"maildir",
"queue",
"."
] |
4c452244969b98431e57d5ebba930f365006dfbd
|
https://github.com/amol-/tgext.mailer/blob/4c452244969b98431e57d5ebba930f365006dfbd/tgext/mailer/mailer.py#L236-L247
|
238,028
|
ChrisCummins/labm8
|
labtypes.py
|
is_seq
|
def is_seq(obj):
"""
Check if an object is a sequence.
"""
return (not is_str(obj) and not is_dict(obj) and
(hasattr(obj, "__getitem__") or hasattr(obj, "__iter__")))
|
python
|
def is_seq(obj):
"""
Check if an object is a sequence.
"""
return (not is_str(obj) and not is_dict(obj) and
(hasattr(obj, "__getitem__") or hasattr(obj, "__iter__")))
|
[
"def",
"is_seq",
"(",
"obj",
")",
":",
"return",
"(",
"not",
"is_str",
"(",
"obj",
")",
"and",
"not",
"is_dict",
"(",
"obj",
")",
"and",
"(",
"hasattr",
"(",
"obj",
",",
"\"__getitem__\"",
")",
"or",
"hasattr",
"(",
"obj",
",",
"\"__iter__\"",
")",
")",
")"
] |
Check if an object is a sequence.
|
[
"Check",
"if",
"an",
"object",
"is",
"a",
"sequence",
"."
] |
dd10d67a757aefb180cb508f86696f99440c94f5
|
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/labtypes.py#L47-L52
|
238,029
|
ChrisCummins/labm8
|
labtypes.py
|
update
|
def update(dst, src):
"""
Recursively update values in dst from src.
Unlike the builtin dict.update() function, this method will decend into
nested dicts, updating all nested values.
Arguments:
dst (dict): Destination dict.
src (dict): Source dict.
Returns:
dict: dst updated with entries from src.
"""
for k, v in src.items():
if isinstance(v, Mapping):
r = update(dst.get(k, {}), v)
dst[k] = r
else:
dst[k] = src[k]
return dst
|
python
|
def update(dst, src):
"""
Recursively update values in dst from src.
Unlike the builtin dict.update() function, this method will decend into
nested dicts, updating all nested values.
Arguments:
dst (dict): Destination dict.
src (dict): Source dict.
Returns:
dict: dst updated with entries from src.
"""
for k, v in src.items():
if isinstance(v, Mapping):
r = update(dst.get(k, {}), v)
dst[k] = r
else:
dst[k] = src[k]
return dst
|
[
"def",
"update",
"(",
"dst",
",",
"src",
")",
":",
"for",
"k",
",",
"v",
"in",
"src",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"Mapping",
")",
":",
"r",
"=",
"update",
"(",
"dst",
".",
"get",
"(",
"k",
",",
"{",
"}",
")",
",",
"v",
")",
"dst",
"[",
"k",
"]",
"=",
"r",
"else",
":",
"dst",
"[",
"k",
"]",
"=",
"src",
"[",
"k",
"]",
"return",
"dst"
] |
Recursively update values in dst from src.
Unlike the builtin dict.update() function, this method will decend into
nested dicts, updating all nested values.
Arguments:
dst (dict): Destination dict.
src (dict): Source dict.
Returns:
dict: dst updated with entries from src.
|
[
"Recursively",
"update",
"values",
"in",
"dst",
"from",
"src",
"."
] |
dd10d67a757aefb180cb508f86696f99440c94f5
|
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/labtypes.py#L62-L82
|
238,030
|
ChrisCummins/labm8
|
labtypes.py
|
dict_values
|
def dict_values(src):
"""
Recursively get values in dict.
Unlike the builtin dict.values() function, this method will descend into
nested dicts, returning all nested values.
Arguments:
src (dict): Source dict.
Returns:
list: List of values.
"""
for v in src.values():
if isinstance(v, dict):
for v in dict_values(v):
yield v
else:
yield v
|
python
|
def dict_values(src):
"""
Recursively get values in dict.
Unlike the builtin dict.values() function, this method will descend into
nested dicts, returning all nested values.
Arguments:
src (dict): Source dict.
Returns:
list: List of values.
"""
for v in src.values():
if isinstance(v, dict):
for v in dict_values(v):
yield v
else:
yield v
|
[
"def",
"dict_values",
"(",
"src",
")",
":",
"for",
"v",
"in",
"src",
".",
"values",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"for",
"v",
"in",
"dict_values",
"(",
"v",
")",
":",
"yield",
"v",
"else",
":",
"yield",
"v"
] |
Recursively get values in dict.
Unlike the builtin dict.values() function, this method will descend into
nested dicts, returning all nested values.
Arguments:
src (dict): Source dict.
Returns:
list: List of values.
|
[
"Recursively",
"get",
"values",
"in",
"dict",
"."
] |
dd10d67a757aefb180cb508f86696f99440c94f5
|
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/labtypes.py#L85-L103
|
238,031
|
blazelibs/blazeutils
|
blazeutils/importing.py
|
find_path_package
|
def find_path_package(thepath):
"""
Takes a file system path and returns the module object of the python
package the said path belongs to. If the said path can not be
determined, it returns None.
"""
pname = find_path_package_name(thepath)
if not pname:
return None
fromlist = b'' if six.PY2 else ''
return __import__(pname, globals(), locals(), [fromlist])
|
python
|
def find_path_package(thepath):
"""
Takes a file system path and returns the module object of the python
package the said path belongs to. If the said path can not be
determined, it returns None.
"""
pname = find_path_package_name(thepath)
if not pname:
return None
fromlist = b'' if six.PY2 else ''
return __import__(pname, globals(), locals(), [fromlist])
|
[
"def",
"find_path_package",
"(",
"thepath",
")",
":",
"pname",
"=",
"find_path_package_name",
"(",
"thepath",
")",
"if",
"not",
"pname",
":",
"return",
"None",
"fromlist",
"=",
"b''",
"if",
"six",
".",
"PY2",
"else",
"''",
"return",
"__import__",
"(",
"pname",
",",
"globals",
"(",
")",
",",
"locals",
"(",
")",
",",
"[",
"fromlist",
"]",
")"
] |
Takes a file system path and returns the module object of the python
package the said path belongs to. If the said path can not be
determined, it returns None.
|
[
"Takes",
"a",
"file",
"system",
"path",
"and",
"returns",
"the",
"module",
"object",
"of",
"the",
"python",
"package",
"the",
"said",
"path",
"belongs",
"to",
".",
"If",
"the",
"said",
"path",
"can",
"not",
"be",
"determined",
"it",
"returns",
"None",
"."
] |
c94476325146007553cbddeeb9ef83394756babf
|
https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/importing.py#L78-L88
|
238,032
|
blazelibs/blazeutils
|
blazeutils/importing.py
|
find_path_package_name
|
def find_path_package_name(thepath):
"""
Takes a file system path and returns the name of the python package
the said path belongs to. If the said path can not be determined, it
returns None.
"""
module_found = False
last_module_found = None
continue_ = True
while continue_:
module_found = is_path_python_module(thepath)
next_path = path.dirname(thepath)
if next_path == thepath:
continue_ = False
if module_found:
init_names = ['__init__%s' % suffix.lower() for suffix in _py_suffixes]
if path.basename(thepath).lower() in init_names:
last_module_found = path.basename(path.dirname(thepath))
else:
last_module_found = path.basename(thepath)
if last_module_found and not module_found:
continue_ = False
thepath = next_path
return last_module_found
|
python
|
def find_path_package_name(thepath):
"""
Takes a file system path and returns the name of the python package
the said path belongs to. If the said path can not be determined, it
returns None.
"""
module_found = False
last_module_found = None
continue_ = True
while continue_:
module_found = is_path_python_module(thepath)
next_path = path.dirname(thepath)
if next_path == thepath:
continue_ = False
if module_found:
init_names = ['__init__%s' % suffix.lower() for suffix in _py_suffixes]
if path.basename(thepath).lower() in init_names:
last_module_found = path.basename(path.dirname(thepath))
else:
last_module_found = path.basename(thepath)
if last_module_found and not module_found:
continue_ = False
thepath = next_path
return last_module_found
|
[
"def",
"find_path_package_name",
"(",
"thepath",
")",
":",
"module_found",
"=",
"False",
"last_module_found",
"=",
"None",
"continue_",
"=",
"True",
"while",
"continue_",
":",
"module_found",
"=",
"is_path_python_module",
"(",
"thepath",
")",
"next_path",
"=",
"path",
".",
"dirname",
"(",
"thepath",
")",
"if",
"next_path",
"==",
"thepath",
":",
"continue_",
"=",
"False",
"if",
"module_found",
":",
"init_names",
"=",
"[",
"'__init__%s'",
"%",
"suffix",
".",
"lower",
"(",
")",
"for",
"suffix",
"in",
"_py_suffixes",
"]",
"if",
"path",
".",
"basename",
"(",
"thepath",
")",
".",
"lower",
"(",
")",
"in",
"init_names",
":",
"last_module_found",
"=",
"path",
".",
"basename",
"(",
"path",
".",
"dirname",
"(",
"thepath",
")",
")",
"else",
":",
"last_module_found",
"=",
"path",
".",
"basename",
"(",
"thepath",
")",
"if",
"last_module_found",
"and",
"not",
"module_found",
":",
"continue_",
"=",
"False",
"thepath",
"=",
"next_path",
"return",
"last_module_found"
] |
Takes a file system path and returns the name of the python package
the said path belongs to. If the said path can not be determined, it
returns None.
|
[
"Takes",
"a",
"file",
"system",
"path",
"and",
"returns",
"the",
"name",
"of",
"the",
"python",
"package",
"the",
"said",
"path",
"belongs",
"to",
".",
"If",
"the",
"said",
"path",
"can",
"not",
"be",
"determined",
"it",
"returns",
"None",
"."
] |
c94476325146007553cbddeeb9ef83394756babf
|
https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/importing.py#L93-L116
|
238,033
|
blazelibs/blazeutils
|
blazeutils/importing.py
|
is_path_python_module
|
def is_path_python_module(thepath):
"""
Given a path, find out of the path is a python module or is inside
a python module.
"""
thepath = path.normpath(thepath)
if path.isfile(thepath):
base, ext = path.splitext(thepath)
if ext in _py_suffixes:
return True
return False
if path.isdir(thepath):
for suffix in _py_suffixes:
if path.isfile(path.join(thepath, '__init__%s' % suffix)):
return True
return False
|
python
|
def is_path_python_module(thepath):
"""
Given a path, find out of the path is a python module or is inside
a python module.
"""
thepath = path.normpath(thepath)
if path.isfile(thepath):
base, ext = path.splitext(thepath)
if ext in _py_suffixes:
return True
return False
if path.isdir(thepath):
for suffix in _py_suffixes:
if path.isfile(path.join(thepath, '__init__%s' % suffix)):
return True
return False
|
[
"def",
"is_path_python_module",
"(",
"thepath",
")",
":",
"thepath",
"=",
"path",
".",
"normpath",
"(",
"thepath",
")",
"if",
"path",
".",
"isfile",
"(",
"thepath",
")",
":",
"base",
",",
"ext",
"=",
"path",
".",
"splitext",
"(",
"thepath",
")",
"if",
"ext",
"in",
"_py_suffixes",
":",
"return",
"True",
"return",
"False",
"if",
"path",
".",
"isdir",
"(",
"thepath",
")",
":",
"for",
"suffix",
"in",
"_py_suffixes",
":",
"if",
"path",
".",
"isfile",
"(",
"path",
".",
"join",
"(",
"thepath",
",",
"'__init__%s'",
"%",
"suffix",
")",
")",
":",
"return",
"True",
"return",
"False"
] |
Given a path, find out of the path is a python module or is inside
a python module.
|
[
"Given",
"a",
"path",
"find",
"out",
"of",
"the",
"path",
"is",
"a",
"python",
"module",
"or",
"is",
"inside",
"a",
"python",
"module",
"."
] |
c94476325146007553cbddeeb9ef83394756babf
|
https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/importing.py#L119-L136
|
238,034
|
farzadghanei/distutilazy
|
distutilazy/util.py
|
find_files
|
def find_files(root, pattern):
"""Find all files matching the glob pattern recursively
:param root: string
:param pattern: string
:return: list of file paths relative to root
"""
results = []
for base, dirs, files in os.walk(root):
matched = fnmatch.filter(files, pattern)
results.extend(os.path.join(base, f) for f in matched)
return results
|
python
|
def find_files(root, pattern):
"""Find all files matching the glob pattern recursively
:param root: string
:param pattern: string
:return: list of file paths relative to root
"""
results = []
for base, dirs, files in os.walk(root):
matched = fnmatch.filter(files, pattern)
results.extend(os.path.join(base, f) for f in matched)
return results
|
[
"def",
"find_files",
"(",
"root",
",",
"pattern",
")",
":",
"results",
"=",
"[",
"]",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root",
")",
":",
"matched",
"=",
"fnmatch",
".",
"filter",
"(",
"files",
",",
"pattern",
")",
"results",
".",
"extend",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"f",
")",
"for",
"f",
"in",
"matched",
")",
"return",
"results"
] |
Find all files matching the glob pattern recursively
:param root: string
:param pattern: string
:return: list of file paths relative to root
|
[
"Find",
"all",
"files",
"matching",
"the",
"glob",
"pattern",
"recursively"
] |
c3c7d062f7cb79abb7677cac57dd752127ff78e7
|
https://github.com/farzadghanei/distutilazy/blob/c3c7d062f7cb79abb7677cac57dd752127ff78e7/distutilazy/util.py#L14-L25
|
238,035
|
farzadghanei/distutilazy
|
distutilazy/util.py
|
find_directories
|
def find_directories(root, pattern):
"""Find all directories matching the glob pattern recursively
:param root: string
:param pattern: string
:return: list of dir paths relative to root
"""
results = []
for base, dirs, files in os.walk(root):
matched = fnmatch.filter(dirs, pattern)
results.extend(os.path.join(base, d) for d in matched)
return results
|
python
|
def find_directories(root, pattern):
"""Find all directories matching the glob pattern recursively
:param root: string
:param pattern: string
:return: list of dir paths relative to root
"""
results = []
for base, dirs, files in os.walk(root):
matched = fnmatch.filter(dirs, pattern)
results.extend(os.path.join(base, d) for d in matched)
return results
|
[
"def",
"find_directories",
"(",
"root",
",",
"pattern",
")",
":",
"results",
"=",
"[",
"]",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root",
")",
":",
"matched",
"=",
"fnmatch",
".",
"filter",
"(",
"dirs",
",",
"pattern",
")",
"results",
".",
"extend",
"(",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"d",
")",
"for",
"d",
"in",
"matched",
")",
"return",
"results"
] |
Find all directories matching the glob pattern recursively
:param root: string
:param pattern: string
:return: list of dir paths relative to root
|
[
"Find",
"all",
"directories",
"matching",
"the",
"glob",
"pattern",
"recursively"
] |
c3c7d062f7cb79abb7677cac57dd752127ff78e7
|
https://github.com/farzadghanei/distutilazy/blob/c3c7d062f7cb79abb7677cac57dd752127ff78e7/distutilazy/util.py#L28-L39
|
238,036
|
blazelibs/blazeutils
|
blazeutils/functional.py
|
posargs_limiter
|
def posargs_limiter(func, *args):
""" takes a function a positional arguments and sends only the number of
positional arguments the function is expecting
"""
posargs = inspect.getargspec(func)[0]
length = len(posargs)
if inspect.ismethod(func):
length -= 1
if length == 0:
return func()
return func(*args[0:length])
|
python
|
def posargs_limiter(func, *args):
""" takes a function a positional arguments and sends only the number of
positional arguments the function is expecting
"""
posargs = inspect.getargspec(func)[0]
length = len(posargs)
if inspect.ismethod(func):
length -= 1
if length == 0:
return func()
return func(*args[0:length])
|
[
"def",
"posargs_limiter",
"(",
"func",
",",
"*",
"args",
")",
":",
"posargs",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"[",
"0",
"]",
"length",
"=",
"len",
"(",
"posargs",
")",
"if",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"length",
"-=",
"1",
"if",
"length",
"==",
"0",
":",
"return",
"func",
"(",
")",
"return",
"func",
"(",
"*",
"args",
"[",
"0",
":",
"length",
"]",
")"
] |
takes a function a positional arguments and sends only the number of
positional arguments the function is expecting
|
[
"takes",
"a",
"function",
"a",
"positional",
"arguments",
"and",
"sends",
"only",
"the",
"number",
"of",
"positional",
"arguments",
"the",
"function",
"is",
"expecting"
] |
c94476325146007553cbddeeb9ef83394756babf
|
https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/functional.py#L13-L23
|
238,037
|
blazelibs/blazeutils
|
blazeutils/functional.py
|
compose
|
def compose(*functions):
"""Function composition on a series of functions.
Remember that function composition runs right-to-left: `f . g . h = f(g(h(x)))`. As a unix
pipeline, it would be written: `h | g | f`.
From https://mathieularose.com/function-composition-in-python/.
"""
return functools.reduce(lambda f, g: lambda x: f(g(x)), functions, identity)
|
python
|
def compose(*functions):
"""Function composition on a series of functions.
Remember that function composition runs right-to-left: `f . g . h = f(g(h(x)))`. As a unix
pipeline, it would be written: `h | g | f`.
From https://mathieularose.com/function-composition-in-python/.
"""
return functools.reduce(lambda f, g: lambda x: f(g(x)), functions, identity)
|
[
"def",
"compose",
"(",
"*",
"functions",
")",
":",
"return",
"functools",
".",
"reduce",
"(",
"lambda",
"f",
",",
"g",
":",
"lambda",
"x",
":",
"f",
"(",
"g",
"(",
"x",
")",
")",
",",
"functions",
",",
"identity",
")"
] |
Function composition on a series of functions.
Remember that function composition runs right-to-left: `f . g . h = f(g(h(x)))`. As a unix
pipeline, it would be written: `h | g | f`.
From https://mathieularose.com/function-composition-in-python/.
|
[
"Function",
"composition",
"on",
"a",
"series",
"of",
"functions",
"."
] |
c94476325146007553cbddeeb9ef83394756babf
|
https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/functional.py#L58-L66
|
238,038
|
blazelibs/blazeutils
|
blazeutils/functional.py
|
first_where
|
def first_where(pred, iterable, default=None):
"""Returns the first element in an iterable that meets the given predicate.
:param default: is the default value to use if the predicate matches none of the elements.
"""
return next(six.moves.filter(pred, iterable), default)
|
python
|
def first_where(pred, iterable, default=None):
"""Returns the first element in an iterable that meets the given predicate.
:param default: is the default value to use if the predicate matches none of the elements.
"""
return next(six.moves.filter(pred, iterable), default)
|
[
"def",
"first_where",
"(",
"pred",
",",
"iterable",
",",
"default",
"=",
"None",
")",
":",
"return",
"next",
"(",
"six",
".",
"moves",
".",
"filter",
"(",
"pred",
",",
"iterable",
")",
",",
"default",
")"
] |
Returns the first element in an iterable that meets the given predicate.
:param default: is the default value to use if the predicate matches none of the elements.
|
[
"Returns",
"the",
"first",
"element",
"in",
"an",
"iterable",
"that",
"meets",
"the",
"given",
"predicate",
"."
] |
c94476325146007553cbddeeb9ef83394756babf
|
https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/functional.py#L75-L80
|
238,039
|
blazelibs/blazeutils
|
blazeutils/functional.py
|
partition_iter
|
def partition_iter(pred, iterable):
"""Partitions an iterable with a predicate into two iterables, one with elements satisfying
the predicate and one with elements that do not satisfy it.
:returns: a tuple (satisfiers, unsatisfiers).
"""
left, right = itertools.tee(iterable, 2)
return (
(x for x in left if pred(x)),
(y for y in right if not pred(y))
)
|
python
|
def partition_iter(pred, iterable):
"""Partitions an iterable with a predicate into two iterables, one with elements satisfying
the predicate and one with elements that do not satisfy it.
:returns: a tuple (satisfiers, unsatisfiers).
"""
left, right = itertools.tee(iterable, 2)
return (
(x for x in left if pred(x)),
(y for y in right if not pred(y))
)
|
[
"def",
"partition_iter",
"(",
"pred",
",",
"iterable",
")",
":",
"left",
",",
"right",
"=",
"itertools",
".",
"tee",
"(",
"iterable",
",",
"2",
")",
"return",
"(",
"(",
"x",
"for",
"x",
"in",
"left",
"if",
"pred",
"(",
"x",
")",
")",
",",
"(",
"y",
"for",
"y",
"in",
"right",
"if",
"not",
"pred",
"(",
"y",
")",
")",
")"
] |
Partitions an iterable with a predicate into two iterables, one with elements satisfying
the predicate and one with elements that do not satisfy it.
:returns: a tuple (satisfiers, unsatisfiers).
|
[
"Partitions",
"an",
"iterable",
"with",
"a",
"predicate",
"into",
"two",
"iterables",
"one",
"with",
"elements",
"satisfying",
"the",
"predicate",
"and",
"one",
"with",
"elements",
"that",
"do",
"not",
"satisfy",
"it",
"."
] |
c94476325146007553cbddeeb9ef83394756babf
|
https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/functional.py#L88-L98
|
238,040
|
blazelibs/blazeutils
|
blazeutils/functional.py
|
partition_list
|
def partition_list(pred, iterable):
"""Partitions an iterable with a predicate into two lists, one with elements satisfying
the predicate and one with elements that do not satisfy it.
.. note: this just converts the results of partition_iter to a list for you so that you don't
have to in most cases using `partition_iter` is a better option.
:returns: a tuple (satisfiers, unsatisfiers).
"""
left, right = partition_iter(pred, iterable)
return list(left), list(right)
|
python
|
def partition_list(pred, iterable):
"""Partitions an iterable with a predicate into two lists, one with elements satisfying
the predicate and one with elements that do not satisfy it.
.. note: this just converts the results of partition_iter to a list for you so that you don't
have to in most cases using `partition_iter` is a better option.
:returns: a tuple (satisfiers, unsatisfiers).
"""
left, right = partition_iter(pred, iterable)
return list(left), list(right)
|
[
"def",
"partition_list",
"(",
"pred",
",",
"iterable",
")",
":",
"left",
",",
"right",
"=",
"partition_iter",
"(",
"pred",
",",
"iterable",
")",
"return",
"list",
"(",
"left",
")",
",",
"list",
"(",
"right",
")"
] |
Partitions an iterable with a predicate into two lists, one with elements satisfying
the predicate and one with elements that do not satisfy it.
.. note: this just converts the results of partition_iter to a list for you so that you don't
have to in most cases using `partition_iter` is a better option.
:returns: a tuple (satisfiers, unsatisfiers).
|
[
"Partitions",
"an",
"iterable",
"with",
"a",
"predicate",
"into",
"two",
"lists",
"one",
"with",
"elements",
"satisfying",
"the",
"predicate",
"and",
"one",
"with",
"elements",
"that",
"do",
"not",
"satisfy",
"it",
"."
] |
c94476325146007553cbddeeb9ef83394756babf
|
https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/functional.py#L101-L111
|
238,041
|
blazelibs/blazeutils
|
blazeutils/functional.py
|
split_every
|
def split_every(n, iterable):
"""Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have
less than n elements.
See http://stackoverflow.com/a/22919323/503377."""
items = iter(iterable)
return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))
|
python
|
def split_every(n, iterable):
"""Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have
less than n elements.
See http://stackoverflow.com/a/22919323/503377."""
items = iter(iterable)
return itertools.takewhile(bool, (list(itertools.islice(items, n)) for _ in itertools.count()))
|
[
"def",
"split_every",
"(",
"n",
",",
"iterable",
")",
":",
"items",
"=",
"iter",
"(",
"iterable",
")",
"return",
"itertools",
".",
"takewhile",
"(",
"bool",
",",
"(",
"list",
"(",
"itertools",
".",
"islice",
"(",
"items",
",",
"n",
")",
")",
"for",
"_",
"in",
"itertools",
".",
"count",
"(",
")",
")",
")"
] |
Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have
less than n elements.
See http://stackoverflow.com/a/22919323/503377.
|
[
"Returns",
"a",
"generator",
"that",
"spits",
"an",
"iteratable",
"into",
"n",
"-",
"sized",
"chunks",
".",
"The",
"last",
"chunk",
"may",
"have",
"less",
"than",
"n",
"elements",
"."
] |
c94476325146007553cbddeeb9ef83394756babf
|
https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/functional.py#L132-L138
|
238,042
|
blazelibs/blazeutils
|
blazeutils/functional.py
|
unique
|
def unique(iterable, key=identity):
"""Yields all the unique values in an iterable maintaining order"""
seen = set()
for item in iterable:
item_key = key(item)
if item_key not in seen:
seen.add(item_key)
yield item
|
python
|
def unique(iterable, key=identity):
"""Yields all the unique values in an iterable maintaining order"""
seen = set()
for item in iterable:
item_key = key(item)
if item_key not in seen:
seen.add(item_key)
yield item
|
[
"def",
"unique",
"(",
"iterable",
",",
"key",
"=",
"identity",
")",
":",
"seen",
"=",
"set",
"(",
")",
"for",
"item",
"in",
"iterable",
":",
"item_key",
"=",
"key",
"(",
"item",
")",
"if",
"item_key",
"not",
"in",
"seen",
":",
"seen",
".",
"add",
"(",
"item_key",
")",
"yield",
"item"
] |
Yields all the unique values in an iterable maintaining order
|
[
"Yields",
"all",
"the",
"unique",
"values",
"in",
"an",
"iterable",
"maintaining",
"order"
] |
c94476325146007553cbddeeb9ef83394756babf
|
https://github.com/blazelibs/blazeutils/blob/c94476325146007553cbddeeb9ef83394756babf/blazeutils/functional.py#L141-L148
|
238,043
|
moliware/dicts
|
dicts/sorteddict.py
|
SortedDict.iteritems
|
def iteritems(self):
""" Sort and then iterate the dictionary """
sorted_data = sorted(self.data.iteritems(), self.cmp, self.key,
self.reverse)
for k,v in sorted_data:
yield k,v
|
python
|
def iteritems(self):
""" Sort and then iterate the dictionary """
sorted_data = sorted(self.data.iteritems(), self.cmp, self.key,
self.reverse)
for k,v in sorted_data:
yield k,v
|
[
"def",
"iteritems",
"(",
"self",
")",
":",
"sorted_data",
"=",
"sorted",
"(",
"self",
".",
"data",
".",
"iteritems",
"(",
")",
",",
"self",
".",
"cmp",
",",
"self",
".",
"key",
",",
"self",
".",
"reverse",
")",
"for",
"k",
",",
"v",
"in",
"sorted_data",
":",
"yield",
"k",
",",
"v"
] |
Sort and then iterate the dictionary
|
[
"Sort",
"and",
"then",
"iterate",
"the",
"dictionary"
] |
0e8258cc3dc00fe929685cae9cda062222722715
|
https://github.com/moliware/dicts/blob/0e8258cc3dc00fe929685cae9cda062222722715/dicts/sorteddict.py#L35-L40
|
238,044
|
six8/anticipate
|
src/anticipate/decorators.py
|
anticipate_wrapper._adapt_param
|
def _adapt_param(self, key, val):
"""
Adapt the value if an adapter is defined.
"""
if key in self.param_adapters:
try:
return self.param_adapters[key](val)
except (AdaptError, AdaptErrors, TypeError, ValueError) as e:
if hasattr(e, 'errors'):
errors = e.errors
else:
errors = [e]
raise AnticipateParamError(
message='Input value %r for parameter `%s` does not match '
'anticipated type %r' % (type(val), key, self.params[key]),
name=key,
value=val,
anticipated=self.params[key],
errors=errors)
else:
return val
|
python
|
def _adapt_param(self, key, val):
"""
Adapt the value if an adapter is defined.
"""
if key in self.param_adapters:
try:
return self.param_adapters[key](val)
except (AdaptError, AdaptErrors, TypeError, ValueError) as e:
if hasattr(e, 'errors'):
errors = e.errors
else:
errors = [e]
raise AnticipateParamError(
message='Input value %r for parameter `%s` does not match '
'anticipated type %r' % (type(val), key, self.params[key]),
name=key,
value=val,
anticipated=self.params[key],
errors=errors)
else:
return val
|
[
"def",
"_adapt_param",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"if",
"key",
"in",
"self",
".",
"param_adapters",
":",
"try",
":",
"return",
"self",
".",
"param_adapters",
"[",
"key",
"]",
"(",
"val",
")",
"except",
"(",
"AdaptError",
",",
"AdaptErrors",
",",
"TypeError",
",",
"ValueError",
")",
"as",
"e",
":",
"if",
"hasattr",
"(",
"e",
",",
"'errors'",
")",
":",
"errors",
"=",
"e",
".",
"errors",
"else",
":",
"errors",
"=",
"[",
"e",
"]",
"raise",
"AnticipateParamError",
"(",
"message",
"=",
"'Input value %r for parameter `%s` does not match '",
"'anticipated type %r'",
"%",
"(",
"type",
"(",
"val",
")",
",",
"key",
",",
"self",
".",
"params",
"[",
"key",
"]",
")",
",",
"name",
"=",
"key",
",",
"value",
"=",
"val",
",",
"anticipated",
"=",
"self",
".",
"params",
"[",
"key",
"]",
",",
"errors",
"=",
"errors",
")",
"else",
":",
"return",
"val"
] |
Adapt the value if an adapter is defined.
|
[
"Adapt",
"the",
"value",
"if",
"an",
"adapter",
"is",
"defined",
"."
] |
5c0651f9829ba0140e7cf185505da6109ef1f55c
|
https://github.com/six8/anticipate/blob/5c0651f9829ba0140e7cf185505da6109ef1f55c/src/anticipate/decorators.py#L64-L85
|
238,045
|
six8/anticipate
|
src/anticipate/decorators.py
|
anticipate_wrapper.input
|
def input(self, *args, **kwargs):
"""
Adapt the input and check for errors.
Returns a tuple of adapted (args, kwargs) or raises
AnticipateErrors
"""
errors = []
if args and self.arg_names:
args = list(args)
# Replace args inline that have adapters
for i, (key, val) in enumerate(izip(self.arg_names, args)):
try:
args[i] = self._adapt_param(key, val)
except AnticipateParamError as e:
errors.append(e)
args = tuple(args)
if kwargs and self.params:
# Adapt all adaptable arguments
for key, val in kwargs.items():
try:
kwargs[key] = self._adapt_param(key, val)
except AnticipateParamError as e:
errors.append(e)
if errors:
raise AnticipateErrors(
message='Invalid input for %s' % self.func,
errors=errors)
return args, kwargs
|
python
|
def input(self, *args, **kwargs):
"""
Adapt the input and check for errors.
Returns a tuple of adapted (args, kwargs) or raises
AnticipateErrors
"""
errors = []
if args and self.arg_names:
args = list(args)
# Replace args inline that have adapters
for i, (key, val) in enumerate(izip(self.arg_names, args)):
try:
args[i] = self._adapt_param(key, val)
except AnticipateParamError as e:
errors.append(e)
args = tuple(args)
if kwargs and self.params:
# Adapt all adaptable arguments
for key, val in kwargs.items():
try:
kwargs[key] = self._adapt_param(key, val)
except AnticipateParamError as e:
errors.append(e)
if errors:
raise AnticipateErrors(
message='Invalid input for %s' % self.func,
errors=errors)
return args, kwargs
|
[
"def",
"input",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"args",
"and",
"self",
".",
"arg_names",
":",
"args",
"=",
"list",
"(",
"args",
")",
"# Replace args inline that have adapters",
"for",
"i",
",",
"(",
"key",
",",
"val",
")",
"in",
"enumerate",
"(",
"izip",
"(",
"self",
".",
"arg_names",
",",
"args",
")",
")",
":",
"try",
":",
"args",
"[",
"i",
"]",
"=",
"self",
".",
"_adapt_param",
"(",
"key",
",",
"val",
")",
"except",
"AnticipateParamError",
"as",
"e",
":",
"errors",
".",
"append",
"(",
"e",
")",
"args",
"=",
"tuple",
"(",
"args",
")",
"if",
"kwargs",
"and",
"self",
".",
"params",
":",
"# Adapt all adaptable arguments",
"for",
"key",
",",
"val",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"try",
":",
"kwargs",
"[",
"key",
"]",
"=",
"self",
".",
"_adapt_param",
"(",
"key",
",",
"val",
")",
"except",
"AnticipateParamError",
"as",
"e",
":",
"errors",
".",
"append",
"(",
"e",
")",
"if",
"errors",
":",
"raise",
"AnticipateErrors",
"(",
"message",
"=",
"'Invalid input for %s'",
"%",
"self",
".",
"func",
",",
"errors",
"=",
"errors",
")",
"return",
"args",
",",
"kwargs"
] |
Adapt the input and check for errors.
Returns a tuple of adapted (args, kwargs) or raises
AnticipateErrors
|
[
"Adapt",
"the",
"input",
"and",
"check",
"for",
"errors",
"."
] |
5c0651f9829ba0140e7cf185505da6109ef1f55c
|
https://github.com/six8/anticipate/blob/5c0651f9829ba0140e7cf185505da6109ef1f55c/src/anticipate/decorators.py#L95-L127
|
238,046
|
six8/anticipate
|
src/anticipate/decorators.py
|
anticipate_wrapper.output
|
def output(self, result):
"""
Adapts the result of a function based on the returns definition.
"""
if self.returns:
errors = None
try:
return self._adapt_result(result)
except AdaptErrors as e:
errors = e.errors
except AdaptError as e:
errors = [e]
raise AnticipateErrors(
message='Return value %r does not match anticipated type %r'
% (type(result), self.returns),
errors=errors)
elif self.strict:
if result is not None:
raise AnticipateErrors(
message='Return value %r does not match anticipated value '
'of None' % type(result),
errors=None)
return None
else:
return result
|
python
|
def output(self, result):
"""
Adapts the result of a function based on the returns definition.
"""
if self.returns:
errors = None
try:
return self._adapt_result(result)
except AdaptErrors as e:
errors = e.errors
except AdaptError as e:
errors = [e]
raise AnticipateErrors(
message='Return value %r does not match anticipated type %r'
% (type(result), self.returns),
errors=errors)
elif self.strict:
if result is not None:
raise AnticipateErrors(
message='Return value %r does not match anticipated value '
'of None' % type(result),
errors=None)
return None
else:
return result
|
[
"def",
"output",
"(",
"self",
",",
"result",
")",
":",
"if",
"self",
".",
"returns",
":",
"errors",
"=",
"None",
"try",
":",
"return",
"self",
".",
"_adapt_result",
"(",
"result",
")",
"except",
"AdaptErrors",
"as",
"e",
":",
"errors",
"=",
"e",
".",
"errors",
"except",
"AdaptError",
"as",
"e",
":",
"errors",
"=",
"[",
"e",
"]",
"raise",
"AnticipateErrors",
"(",
"message",
"=",
"'Return value %r does not match anticipated type %r'",
"%",
"(",
"type",
"(",
"result",
")",
",",
"self",
".",
"returns",
")",
",",
"errors",
"=",
"errors",
")",
"elif",
"self",
".",
"strict",
":",
"if",
"result",
"is",
"not",
"None",
":",
"raise",
"AnticipateErrors",
"(",
"message",
"=",
"'Return value %r does not match anticipated value '",
"'of None'",
"%",
"type",
"(",
"result",
")",
",",
"errors",
"=",
"None",
")",
"return",
"None",
"else",
":",
"return",
"result"
] |
Adapts the result of a function based on the returns definition.
|
[
"Adapts",
"the",
"result",
"of",
"a",
"function",
"based",
"on",
"the",
"returns",
"definition",
"."
] |
5c0651f9829ba0140e7cf185505da6109ef1f55c
|
https://github.com/six8/anticipate/blob/5c0651f9829ba0140e7cf185505da6109ef1f55c/src/anticipate/decorators.py#L129-L154
|
238,047
|
jpscaletti/solution
|
solution/fields/file/image.py
|
Image.clean
|
def clean(self, value):
"""Passes the value to FileField and resizes the image at the path the parent
returns if needed.
"""
path = super(Image, self).clean(value)
if path and self.size:
self.resize_image(join(self.base_path, path))
return path
|
python
|
def clean(self, value):
"""Passes the value to FileField and resizes the image at the path the parent
returns if needed.
"""
path = super(Image, self).clean(value)
if path and self.size:
self.resize_image(join(self.base_path, path))
return path
|
[
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"path",
"=",
"super",
"(",
"Image",
",",
"self",
")",
".",
"clean",
"(",
"value",
")",
"if",
"path",
"and",
"self",
".",
"size",
":",
"self",
".",
"resize_image",
"(",
"join",
"(",
"self",
".",
"base_path",
",",
"path",
")",
")",
"return",
"path"
] |
Passes the value to FileField and resizes the image at the path the parent
returns if needed.
|
[
"Passes",
"the",
"value",
"to",
"FileField",
"and",
"resizes",
"the",
"image",
"at",
"the",
"path",
"the",
"parent",
"returns",
"if",
"needed",
"."
] |
eabafd8e695bbb0209242e002dbcc05ffb327f43
|
https://github.com/jpscaletti/solution/blob/eabafd8e695bbb0209242e002dbcc05ffb327f43/solution/fields/file/image.py#L22-L30
|
238,048
|
jpscaletti/solution
|
solution/fields/file/image.py
|
Image.calculate_dimensions
|
def calculate_dimensions(image_size, desired_size):
"""Return the Tuple with the arguments to pass to Image.crop.
If the image is smaller than than the desired_size Don't do
anything. Otherwise, first calculate the (truncated) center and then
take half the width and height (truncated again) for x and y.
x0, y0: the center coordinates
"""
current_x, current_y = image_size
target_x, target_y = desired_size
if current_x < target_x and current_y < target_y:
return None
if current_x > target_x:
new_x0 = floor(current_x / 2)
new_x = new_x0 - ceil(target_x / 2)
new_width = target_x
else:
new_x = 0
new_width = current_x
if current_y > target_y:
new_y0 = floor(current_y / 2)
new_y = new_y0 - ceil(target_y / 2)
new_height = target_y
else:
new_y = 0
new_height = current_y
return (int(new_x), int(new_y), new_width, new_height)
|
python
|
def calculate_dimensions(image_size, desired_size):
"""Return the Tuple with the arguments to pass to Image.crop.
If the image is smaller than than the desired_size Don't do
anything. Otherwise, first calculate the (truncated) center and then
take half the width and height (truncated again) for x and y.
x0, y0: the center coordinates
"""
current_x, current_y = image_size
target_x, target_y = desired_size
if current_x < target_x and current_y < target_y:
return None
if current_x > target_x:
new_x0 = floor(current_x / 2)
new_x = new_x0 - ceil(target_x / 2)
new_width = target_x
else:
new_x = 0
new_width = current_x
if current_y > target_y:
new_y0 = floor(current_y / 2)
new_y = new_y0 - ceil(target_y / 2)
new_height = target_y
else:
new_y = 0
new_height = current_y
return (int(new_x), int(new_y), new_width, new_height)
|
[
"def",
"calculate_dimensions",
"(",
"image_size",
",",
"desired_size",
")",
":",
"current_x",
",",
"current_y",
"=",
"image_size",
"target_x",
",",
"target_y",
"=",
"desired_size",
"if",
"current_x",
"<",
"target_x",
"and",
"current_y",
"<",
"target_y",
":",
"return",
"None",
"if",
"current_x",
">",
"target_x",
":",
"new_x0",
"=",
"floor",
"(",
"current_x",
"/",
"2",
")",
"new_x",
"=",
"new_x0",
"-",
"ceil",
"(",
"target_x",
"/",
"2",
")",
"new_width",
"=",
"target_x",
"else",
":",
"new_x",
"=",
"0",
"new_width",
"=",
"current_x",
"if",
"current_y",
">",
"target_y",
":",
"new_y0",
"=",
"floor",
"(",
"current_y",
"/",
"2",
")",
"new_y",
"=",
"new_y0",
"-",
"ceil",
"(",
"target_y",
"/",
"2",
")",
"new_height",
"=",
"target_y",
"else",
":",
"new_y",
"=",
"0",
"new_height",
"=",
"current_y",
"return",
"(",
"int",
"(",
"new_x",
")",
",",
"int",
"(",
"new_y",
")",
",",
"new_width",
",",
"new_height",
")"
] |
Return the Tuple with the arguments to pass to Image.crop.
If the image is smaller than than the desired_size Don't do
anything. Otherwise, first calculate the (truncated) center and then
take half the width and height (truncated again) for x and y.
x0, y0: the center coordinates
|
[
"Return",
"the",
"Tuple",
"with",
"the",
"arguments",
"to",
"pass",
"to",
"Image",
".",
"crop",
"."
] |
eabafd8e695bbb0209242e002dbcc05ffb327f43
|
https://github.com/jpscaletti/solution/blob/eabafd8e695bbb0209242e002dbcc05ffb327f43/solution/fields/file/image.py#L45-L77
|
238,049
|
openpermissions/koi
|
koi/base.py
|
CorsHandler.options
|
def options(self, *args, **kwargs):
"""Default OPTIONS response
If the 'cors' option is True, will respond with an empty response and
set the 'Access-Control-Allow-Headers' and
'Access-Control-Allow-Methods' headers
"""
if getattr(options, 'cors', False):
self.set_header('Access-Control-Allow-Headers',
'Content-Type, Authorization, '
'Accept, X-Requested-With')
self.set_header('Access-Control-Allow-Methods',
'OPTIONS, TRACE, GET, HEAD, POST, '
'PUT, PATCH, DELETE')
self.finish()
|
python
|
def options(self, *args, **kwargs):
"""Default OPTIONS response
If the 'cors' option is True, will respond with an empty response and
set the 'Access-Control-Allow-Headers' and
'Access-Control-Allow-Methods' headers
"""
if getattr(options, 'cors', False):
self.set_header('Access-Control-Allow-Headers',
'Content-Type, Authorization, '
'Accept, X-Requested-With')
self.set_header('Access-Control-Allow-Methods',
'OPTIONS, TRACE, GET, HEAD, POST, '
'PUT, PATCH, DELETE')
self.finish()
|
[
"def",
"options",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"getattr",
"(",
"options",
",",
"'cors'",
",",
"False",
")",
":",
"self",
".",
"set_header",
"(",
"'Access-Control-Allow-Headers'",
",",
"'Content-Type, Authorization, '",
"'Accept, X-Requested-With'",
")",
"self",
".",
"set_header",
"(",
"'Access-Control-Allow-Methods'",
",",
"'OPTIONS, TRACE, GET, HEAD, POST, '",
"'PUT, PATCH, DELETE'",
")",
"self",
".",
"finish",
"(",
")"
] |
Default OPTIONS response
If the 'cors' option is True, will respond with an empty response and
set the 'Access-Control-Allow-Headers' and
'Access-Control-Allow-Methods' headers
|
[
"Default",
"OPTIONS",
"response"
] |
d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281
|
https://github.com/openpermissions/koi/blob/d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281/koi/base.py#L42-L57
|
238,050
|
openpermissions/koi
|
koi/base.py
|
JsonHandler.write_error
|
def write_error(self, status_code, **kwargs):
"""Override `write_error` in order to output JSON errors
:param status_code: the response's status code, e.g. 500
"""
http_error = _get_http_error(kwargs)
if http_error:
self.finish(self._error_template(status_code,
http_error.errors,
http_error.source))
else:
source = kwargs.get('source', getattr(options, 'name', None))
# Slightly annoyed that have to rely on the internal self._reason
# to deal with unhandled exceptions. On the dev version of
# tornado self._reason is always set, while in the current version
# a reason kwarg is passed down from `send_error` but not set
# on the instance.
reason = kwargs.get('reason', self._reason)
self.finish(self._error_template(status_code, reason, source))
|
python
|
def write_error(self, status_code, **kwargs):
"""Override `write_error` in order to output JSON errors
:param status_code: the response's status code, e.g. 500
"""
http_error = _get_http_error(kwargs)
if http_error:
self.finish(self._error_template(status_code,
http_error.errors,
http_error.source))
else:
source = kwargs.get('source', getattr(options, 'name', None))
# Slightly annoyed that have to rely on the internal self._reason
# to deal with unhandled exceptions. On the dev version of
# tornado self._reason is always set, while in the current version
# a reason kwarg is passed down from `send_error` but not set
# on the instance.
reason = kwargs.get('reason', self._reason)
self.finish(self._error_template(status_code, reason, source))
|
[
"def",
"write_error",
"(",
"self",
",",
"status_code",
",",
"*",
"*",
"kwargs",
")",
":",
"http_error",
"=",
"_get_http_error",
"(",
"kwargs",
")",
"if",
"http_error",
":",
"self",
".",
"finish",
"(",
"self",
".",
"_error_template",
"(",
"status_code",
",",
"http_error",
".",
"errors",
",",
"http_error",
".",
"source",
")",
")",
"else",
":",
"source",
"=",
"kwargs",
".",
"get",
"(",
"'source'",
",",
"getattr",
"(",
"options",
",",
"'name'",
",",
"None",
")",
")",
"# Slightly annoyed that have to rely on the internal self._reason",
"# to deal with unhandled exceptions. On the dev version of",
"# tornado self._reason is always set, while in the current version",
"# a reason kwarg is passed down from `send_error` but not set",
"# on the instance.",
"reason",
"=",
"kwargs",
".",
"get",
"(",
"'reason'",
",",
"self",
".",
"_reason",
")",
"self",
".",
"finish",
"(",
"self",
".",
"_error_template",
"(",
"status_code",
",",
"reason",
",",
"source",
")",
")"
] |
Override `write_error` in order to output JSON errors
:param status_code: the response's status code, e.g. 500
|
[
"Override",
"write_error",
"in",
"order",
"to",
"output",
"JSON",
"errors"
] |
d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281
|
https://github.com/openpermissions/koi/blob/d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281/koi/base.py#L62-L80
|
238,051
|
openpermissions/koi
|
koi/base.py
|
JsonHandler._error_template
|
def _error_template(cls, status_code, errors, source=None):
"""Construct JSON error response
:param status_code: the http status code
:param errors: string or list of error strings
:param source: source of the error
:returns: dictionary, e.g.
{
'status': 400,
'errors': [
{
'source': 'accounts' ,
'message':'errormsg1'
},
{
'source': 'accounts',
'message':'errormsg2'
}
]
}
"""
# this handles unhandled exceptions
if isinstance(errors, basestring):
errors_out = {'errors': [{'message': errors}]}
elif isinstance(errors, (list, tuple)):
errors_out = {'errors': [{'message': e} for e in errors]}
else:
errors_out = errors
errors_out['status'] = status_code
for error in errors_out['errors']:
if not error.get('source'):
error['source'] = source
logging.error(json.dumps(errors_out))
return errors_out
|
python
|
def _error_template(cls, status_code, errors, source=None):
"""Construct JSON error response
:param status_code: the http status code
:param errors: string or list of error strings
:param source: source of the error
:returns: dictionary, e.g.
{
'status': 400,
'errors': [
{
'source': 'accounts' ,
'message':'errormsg1'
},
{
'source': 'accounts',
'message':'errormsg2'
}
]
}
"""
# this handles unhandled exceptions
if isinstance(errors, basestring):
errors_out = {'errors': [{'message': errors}]}
elif isinstance(errors, (list, tuple)):
errors_out = {'errors': [{'message': e} for e in errors]}
else:
errors_out = errors
errors_out['status'] = status_code
for error in errors_out['errors']:
if not error.get('source'):
error['source'] = source
logging.error(json.dumps(errors_out))
return errors_out
|
[
"def",
"_error_template",
"(",
"cls",
",",
"status_code",
",",
"errors",
",",
"source",
"=",
"None",
")",
":",
"# this handles unhandled exceptions",
"if",
"isinstance",
"(",
"errors",
",",
"basestring",
")",
":",
"errors_out",
"=",
"{",
"'errors'",
":",
"[",
"{",
"'message'",
":",
"errors",
"}",
"]",
"}",
"elif",
"isinstance",
"(",
"errors",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"errors_out",
"=",
"{",
"'errors'",
":",
"[",
"{",
"'message'",
":",
"e",
"}",
"for",
"e",
"in",
"errors",
"]",
"}",
"else",
":",
"errors_out",
"=",
"errors",
"errors_out",
"[",
"'status'",
"]",
"=",
"status_code",
"for",
"error",
"in",
"errors_out",
"[",
"'errors'",
"]",
":",
"if",
"not",
"error",
".",
"get",
"(",
"'source'",
")",
":",
"error",
"[",
"'source'",
"]",
"=",
"source",
"logging",
".",
"error",
"(",
"json",
".",
"dumps",
"(",
"errors_out",
")",
")",
"return",
"errors_out"
] |
Construct JSON error response
:param status_code: the http status code
:param errors: string or list of error strings
:param source: source of the error
:returns: dictionary, e.g.
{
'status': 400,
'errors': [
{
'source': 'accounts' ,
'message':'errormsg1'
},
{
'source': 'accounts',
'message':'errormsg2'
}
]
}
|
[
"Construct",
"JSON",
"error",
"response"
] |
d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281
|
https://github.com/openpermissions/koi/blob/d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281/koi/base.py#L83-L118
|
238,052
|
openpermissions/koi
|
koi/base.py
|
JsonHandler.get_json_body
|
def get_json_body(self, required=None, validators=None):
"""Get JSON from the request body
:param required: optionally provide a list of keys that should be
in the JSON body (raises a 400 HTTPError if any are missing)
:param validator: optionally provide a dictionary of items that should
be in the body with a method that validates the item.
The method must be synchronous and return a boolean, no exceptions.
:raises: HTTPError
"""
content_type = self.request.headers.get('Content-Type',
'application/json')
if 'application/json' not in content_type.split(';'):
raise HTTPError(415, 'Content-Type should be application/json')
if not self.request.body:
error = 'Request body is empty'
logging.warning(error)
raise HTTPError(400, error)
try:
body = json.loads(self.request.body)
except (ValueError, TypeError):
error = 'Error parsing JSON'
logging.warning(error)
raise HTTPError(400, error)
if required:
_check_required(body, required)
if validators:
_validate(body, validators)
return body
|
python
|
def get_json_body(self, required=None, validators=None):
"""Get JSON from the request body
:param required: optionally provide a list of keys that should be
in the JSON body (raises a 400 HTTPError if any are missing)
:param validator: optionally provide a dictionary of items that should
be in the body with a method that validates the item.
The method must be synchronous and return a boolean, no exceptions.
:raises: HTTPError
"""
content_type = self.request.headers.get('Content-Type',
'application/json')
if 'application/json' not in content_type.split(';'):
raise HTTPError(415, 'Content-Type should be application/json')
if not self.request.body:
error = 'Request body is empty'
logging.warning(error)
raise HTTPError(400, error)
try:
body = json.loads(self.request.body)
except (ValueError, TypeError):
error = 'Error parsing JSON'
logging.warning(error)
raise HTTPError(400, error)
if required:
_check_required(body, required)
if validators:
_validate(body, validators)
return body
|
[
"def",
"get_json_body",
"(",
"self",
",",
"required",
"=",
"None",
",",
"validators",
"=",
"None",
")",
":",
"content_type",
"=",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
"if",
"'application/json'",
"not",
"in",
"content_type",
".",
"split",
"(",
"';'",
")",
":",
"raise",
"HTTPError",
"(",
"415",
",",
"'Content-Type should be application/json'",
")",
"if",
"not",
"self",
".",
"request",
".",
"body",
":",
"error",
"=",
"'Request body is empty'",
"logging",
".",
"warning",
"(",
"error",
")",
"raise",
"HTTPError",
"(",
"400",
",",
"error",
")",
"try",
":",
"body",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"request",
".",
"body",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"error",
"=",
"'Error parsing JSON'",
"logging",
".",
"warning",
"(",
"error",
")",
"raise",
"HTTPError",
"(",
"400",
",",
"error",
")",
"if",
"required",
":",
"_check_required",
"(",
"body",
",",
"required",
")",
"if",
"validators",
":",
"_validate",
"(",
"body",
",",
"validators",
")",
"return",
"body"
] |
Get JSON from the request body
:param required: optionally provide a list of keys that should be
in the JSON body (raises a 400 HTTPError if any are missing)
:param validator: optionally provide a dictionary of items that should
be in the body with a method that validates the item.
The method must be synchronous and return a boolean, no exceptions.
:raises: HTTPError
|
[
"Get",
"JSON",
"from",
"the",
"request",
"body"
] |
d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281
|
https://github.com/openpermissions/koi/blob/d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281/koi/base.py#L120-L152
|
238,053
|
openpermissions/koi
|
koi/base.py
|
AuthHandler.verify_token
|
def verify_token(self, token, requested_access):
"""
Check the token bearer is permitted to access the resource
:param token: Access token
:param requested_access: the access level the client has requested
:returns: boolean
"""
client = API(options.url_auth,
auth_username=options.service_id,
auth_password=options.client_secret,
ssl_options=ssl_server_options())
headers = {'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'}
body = urllib.urlencode({'token': token, 'requested_access': requested_access})
client.auth.verify.prepare_request(headers=headers, request_timeout=180)
try:
result = yield client.auth.verify.post(body=body)
except tornado.httpclient.HTTPError as ex:
# Must be converted to a tornado.web.HTTPError for the server
# to handle it correctly
logging.exception(ex.message)
raise HTTPError(500, 'Internal Server Error')
raise Return(result['has_access'])
|
python
|
def verify_token(self, token, requested_access):
"""
Check the token bearer is permitted to access the resource
:param token: Access token
:param requested_access: the access level the client has requested
:returns: boolean
"""
client = API(options.url_auth,
auth_username=options.service_id,
auth_password=options.client_secret,
ssl_options=ssl_server_options())
headers = {'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'}
body = urllib.urlencode({'token': token, 'requested_access': requested_access})
client.auth.verify.prepare_request(headers=headers, request_timeout=180)
try:
result = yield client.auth.verify.post(body=body)
except tornado.httpclient.HTTPError as ex:
# Must be converted to a tornado.web.HTTPError for the server
# to handle it correctly
logging.exception(ex.message)
raise HTTPError(500, 'Internal Server Error')
raise Return(result['has_access'])
|
[
"def",
"verify_token",
"(",
"self",
",",
"token",
",",
"requested_access",
")",
":",
"client",
"=",
"API",
"(",
"options",
".",
"url_auth",
",",
"auth_username",
"=",
"options",
".",
"service_id",
",",
"auth_password",
"=",
"options",
".",
"client_secret",
",",
"ssl_options",
"=",
"ssl_server_options",
"(",
")",
")",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/x-www-form-urlencoded'",
",",
"'Accept'",
":",
"'application/json'",
"}",
"body",
"=",
"urllib",
".",
"urlencode",
"(",
"{",
"'token'",
":",
"token",
",",
"'requested_access'",
":",
"requested_access",
"}",
")",
"client",
".",
"auth",
".",
"verify",
".",
"prepare_request",
"(",
"headers",
"=",
"headers",
",",
"request_timeout",
"=",
"180",
")",
"try",
":",
"result",
"=",
"yield",
"client",
".",
"auth",
".",
"verify",
".",
"post",
"(",
"body",
"=",
"body",
")",
"except",
"tornado",
".",
"httpclient",
".",
"HTTPError",
"as",
"ex",
":",
"# Must be converted to a tornado.web.HTTPError for the server",
"# to handle it correctly",
"logging",
".",
"exception",
"(",
"ex",
".",
"message",
")",
"raise",
"HTTPError",
"(",
"500",
",",
"'Internal Server Error'",
")",
"raise",
"Return",
"(",
"result",
"[",
"'has_access'",
"]",
")"
] |
Check the token bearer is permitted to access the resource
:param token: Access token
:param requested_access: the access level the client has requested
:returns: boolean
|
[
"Check",
"the",
"token",
"bearer",
"is",
"permitted",
"to",
"access",
"the",
"resource"
] |
d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281
|
https://github.com/openpermissions/koi/blob/d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281/koi/base.py#L188-L214
|
238,054
|
openpermissions/koi
|
koi/base.py
|
AuthHandler.prepare
|
def prepare(self):
"""If OAuth verification is required, validate provided token
:raise: HTTPError if token does not have access
"""
requested_access = self.endpoint_access(self.request.method)
use_oauth = getattr(options, 'use_oauth', None)
if use_oauth and requested_access is not self.UNAUTHENTICATED_ACCESS:
token = self.request.headers.get('Authorization', '').split(' ')[-1]
if token:
has_access = yield self.verify_token(token, requested_access)
if not has_access:
msg = "'{}' access not granted.".format(requested_access)
raise HTTPError(403, msg)
else:
msg = 'OAuth token not provided'
raise HTTPError(401, msg)
|
python
|
def prepare(self):
"""If OAuth verification is required, validate provided token
:raise: HTTPError if token does not have access
"""
requested_access = self.endpoint_access(self.request.method)
use_oauth = getattr(options, 'use_oauth', None)
if use_oauth and requested_access is not self.UNAUTHENTICATED_ACCESS:
token = self.request.headers.get('Authorization', '').split(' ')[-1]
if token:
has_access = yield self.verify_token(token, requested_access)
if not has_access:
msg = "'{}' access not granted.".format(requested_access)
raise HTTPError(403, msg)
else:
msg = 'OAuth token not provided'
raise HTTPError(401, msg)
|
[
"def",
"prepare",
"(",
"self",
")",
":",
"requested_access",
"=",
"self",
".",
"endpoint_access",
"(",
"self",
".",
"request",
".",
"method",
")",
"use_oauth",
"=",
"getattr",
"(",
"options",
",",
"'use_oauth'",
",",
"None",
")",
"if",
"use_oauth",
"and",
"requested_access",
"is",
"not",
"self",
".",
"UNAUTHENTICATED_ACCESS",
":",
"token",
"=",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Authorization'",
",",
"''",
")",
".",
"split",
"(",
"' '",
")",
"[",
"-",
"1",
"]",
"if",
"token",
":",
"has_access",
"=",
"yield",
"self",
".",
"verify_token",
"(",
"token",
",",
"requested_access",
")",
"if",
"not",
"has_access",
":",
"msg",
"=",
"\"'{}' access not granted.\"",
".",
"format",
"(",
"requested_access",
")",
"raise",
"HTTPError",
"(",
"403",
",",
"msg",
")",
"else",
":",
"msg",
"=",
"'OAuth token not provided'",
"raise",
"HTTPError",
"(",
"401",
",",
"msg",
")"
] |
If OAuth verification is required, validate provided token
:raise: HTTPError if token does not have access
|
[
"If",
"OAuth",
"verification",
"is",
"required",
"validate",
"provided",
"token"
] |
d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281
|
https://github.com/openpermissions/koi/blob/d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281/koi/base.py#L217-L233
|
238,055
|
TrafficSenseMSD/SumoTools
|
sumolib/xml.py
|
parse_fast
|
def parse_fast(xmlfile, element_name, attrnames, warn=False, optional=False):
"""
Parses the given attrnames from all elements with element_name
@Note: The element must be on its own line and the attributes must appear in
the given order.
@Example: parse_fast('plain.edg.xml', 'edge', ['id', 'speed'])
"""
prefixedAttrnames = [_prefix_keyword(a, warn) for a in attrnames]
if optional:
pattern = ''.join(['<%s' % element_name] +
['(\\s+%s="(?P<%s>[^"]*?)")?' % a for a in zip(attrnames, prefixedAttrnames)])
else:
pattern = '.*'.join(['<%s' % element_name] +
['%s="([^"]*)"' % attr for attr in attrnames])
Record = namedtuple(element_name, prefixedAttrnames)
reprog = re.compile(pattern)
for line in open(xmlfile):
m = reprog.search(line)
if m:
if optional:
yield Record(**m.groupdict())
else:
yield Record(*m.groups())
|
python
|
def parse_fast(xmlfile, element_name, attrnames, warn=False, optional=False):
"""
Parses the given attrnames from all elements with element_name
@Note: The element must be on its own line and the attributes must appear in
the given order.
@Example: parse_fast('plain.edg.xml', 'edge', ['id', 'speed'])
"""
prefixedAttrnames = [_prefix_keyword(a, warn) for a in attrnames]
if optional:
pattern = ''.join(['<%s' % element_name] +
['(\\s+%s="(?P<%s>[^"]*?)")?' % a for a in zip(attrnames, prefixedAttrnames)])
else:
pattern = '.*'.join(['<%s' % element_name] +
['%s="([^"]*)"' % attr for attr in attrnames])
Record = namedtuple(element_name, prefixedAttrnames)
reprog = re.compile(pattern)
for line in open(xmlfile):
m = reprog.search(line)
if m:
if optional:
yield Record(**m.groupdict())
else:
yield Record(*m.groups())
|
[
"def",
"parse_fast",
"(",
"xmlfile",
",",
"element_name",
",",
"attrnames",
",",
"warn",
"=",
"False",
",",
"optional",
"=",
"False",
")",
":",
"prefixedAttrnames",
"=",
"[",
"_prefix_keyword",
"(",
"a",
",",
"warn",
")",
"for",
"a",
"in",
"attrnames",
"]",
"if",
"optional",
":",
"pattern",
"=",
"''",
".",
"join",
"(",
"[",
"'<%s'",
"%",
"element_name",
"]",
"+",
"[",
"'(\\\\s+%s=\"(?P<%s>[^\"]*?)\")?'",
"%",
"a",
"for",
"a",
"in",
"zip",
"(",
"attrnames",
",",
"prefixedAttrnames",
")",
"]",
")",
"else",
":",
"pattern",
"=",
"'.*'",
".",
"join",
"(",
"[",
"'<%s'",
"%",
"element_name",
"]",
"+",
"[",
"'%s=\"([^\"]*)\"'",
"%",
"attr",
"for",
"attr",
"in",
"attrnames",
"]",
")",
"Record",
"=",
"namedtuple",
"(",
"element_name",
",",
"prefixedAttrnames",
")",
"reprog",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"for",
"line",
"in",
"open",
"(",
"xmlfile",
")",
":",
"m",
"=",
"reprog",
".",
"search",
"(",
"line",
")",
"if",
"m",
":",
"if",
"optional",
":",
"yield",
"Record",
"(",
"*",
"*",
"m",
".",
"groupdict",
"(",
")",
")",
"else",
":",
"yield",
"Record",
"(",
"*",
"m",
".",
"groups",
"(",
")",
")"
] |
Parses the given attrnames from all elements with element_name
@Note: The element must be on its own line and the attributes must appear in
the given order.
@Example: parse_fast('plain.edg.xml', 'edge', ['id', 'speed'])
|
[
"Parses",
"the",
"given",
"attrnames",
"from",
"all",
"elements",
"with",
"element_name"
] |
8607b4f885f1d1798e43240be643efe6dccccdaa
|
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/xml.py#L227-L249
|
238,056
|
hchasestevens/tracing
|
tracing/__init__.py
|
tracing
|
def tracing(pattern=None, out=None):
"""Print executed lines to stdout."""
_trace = partial(trace_line, pattern)
if out is None:
out = sys.stdout
with redirect_stdout(out):
sys.settrace(_trace)
try:
yield
finally:
sys.settrace(None)
|
python
|
def tracing(pattern=None, out=None):
"""Print executed lines to stdout."""
_trace = partial(trace_line, pattern)
if out is None:
out = sys.stdout
with redirect_stdout(out):
sys.settrace(_trace)
try:
yield
finally:
sys.settrace(None)
|
[
"def",
"tracing",
"(",
"pattern",
"=",
"None",
",",
"out",
"=",
"None",
")",
":",
"_trace",
"=",
"partial",
"(",
"trace_line",
",",
"pattern",
")",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"sys",
".",
"stdout",
"with",
"redirect_stdout",
"(",
"out",
")",
":",
"sys",
".",
"settrace",
"(",
"_trace",
")",
"try",
":",
"yield",
"finally",
":",
"sys",
".",
"settrace",
"(",
"None",
")"
] |
Print executed lines to stdout.
|
[
"Print",
"executed",
"lines",
"to",
"stdout",
"."
] |
58600c8de6767dcd381064169a7bec3f5f37cbc7
|
https://github.com/hchasestevens/tracing/blob/58600c8de6767dcd381064169a7bec3f5f37cbc7/tracing/__init__.py#L17-L29
|
238,057
|
omederos/pyspinner
|
spinning/spinning.py
|
override_params
|
def override_params(opening_char='{', closing_char='}', separator_char='|'):
"""
Override some character settings
@type opening_char: str
@param opening_char: Opening character. Default: '{'
@type closing_char: str
@param closing_char: Closing character. Default: '}'
@type separator_char: str
@param separator_char: Separator char. Default: '|'
"""
global char_separator, char_opening, char_closing
char_separator = separator_char
char_opening = opening_char
char_closing = closing_char
|
python
|
def override_params(opening_char='{', closing_char='}', separator_char='|'):
"""
Override some character settings
@type opening_char: str
@param opening_char: Opening character. Default: '{'
@type closing_char: str
@param closing_char: Closing character. Default: '}'
@type separator_char: str
@param separator_char: Separator char. Default: '|'
"""
global char_separator, char_opening, char_closing
char_separator = separator_char
char_opening = opening_char
char_closing = closing_char
|
[
"def",
"override_params",
"(",
"opening_char",
"=",
"'{'",
",",
"closing_char",
"=",
"'}'",
",",
"separator_char",
"=",
"'|'",
")",
":",
"global",
"char_separator",
",",
"char_opening",
",",
"char_closing",
"char_separator",
"=",
"separator_char",
"char_opening",
"=",
"opening_char",
"char_closing",
"=",
"closing_char"
] |
Override some character settings
@type opening_char: str
@param opening_char: Opening character. Default: '{'
@type closing_char: str
@param closing_char: Closing character. Default: '}'
@type separator_char: str
@param separator_char: Separator char. Default: '|'
|
[
"Override",
"some",
"character",
"settings"
] |
4615d92e669942c48d5542a23ddf6d40b206d9d5
|
https://github.com/omederos/pyspinner/blob/4615d92e669942c48d5542a23ddf6d40b206d9d5/spinning/spinning.py#L10-L24
|
238,058
|
omederos/pyspinner
|
spinning/spinning.py
|
unique
|
def unique(text):
"""
Return an unique text
@type text: str
@param text: Text written used spin syntax.
@return: An unique text
# Generate an unique sentence
>>> unique('The {quick|fast} {brown|gray|red} fox jumped over the lazy dog.')
'The quick red fox jumped over the lazy dog'
"""
# check if the text is correct
correct, error = _is_correct(text)
if not correct:
raise Exception(error)
s = []
_all_unique_texts(text, s)
return s[0]
|
python
|
def unique(text):
"""
Return an unique text
@type text: str
@param text: Text written used spin syntax.
@return: An unique text
# Generate an unique sentence
>>> unique('The {quick|fast} {brown|gray|red} fox jumped over the lazy dog.')
'The quick red fox jumped over the lazy dog'
"""
# check if the text is correct
correct, error = _is_correct(text)
if not correct:
raise Exception(error)
s = []
_all_unique_texts(text, s)
return s[0]
|
[
"def",
"unique",
"(",
"text",
")",
":",
"# check if the text is correct",
"correct",
",",
"error",
"=",
"_is_correct",
"(",
"text",
")",
"if",
"not",
"correct",
":",
"raise",
"Exception",
"(",
"error",
")",
"s",
"=",
"[",
"]",
"_all_unique_texts",
"(",
"text",
",",
"s",
")",
"return",
"s",
"[",
"0",
"]"
] |
Return an unique text
@type text: str
@param text: Text written used spin syntax.
@return: An unique text
# Generate an unique sentence
>>> unique('The {quick|fast} {brown|gray|red} fox jumped over the lazy dog.')
'The quick red fox jumped over the lazy dog'
|
[
"Return",
"an",
"unique",
"text"
] |
4615d92e669942c48d5542a23ddf6d40b206d9d5
|
https://github.com/omederos/pyspinner/blob/4615d92e669942c48d5542a23ddf6d40b206d9d5/spinning/spinning.py#L27-L49
|
238,059
|
omederos/pyspinner
|
spinning/spinning.py
|
_all_unique_texts
|
def _all_unique_texts(text, final):
"""
Compute all the possible unique texts
@type text: str
@param text: Text written used spin syntax
@type final: list
@param final: An empty list where all the unique texts will be stored
@return: Nothing. The result will be in the 'final' list
"""
if not char_opening in text:
if not text in final:
final.append(text)
return
stack = []
indexes = []
for i, c in enumerate(text):
if c == char_closing:
if stack[-1] == char_opening:
start_index = indexes.pop()
substring = '' if i == start_index + 1 else text[start_index:i + 1]
# get some random combination
combination = next(_choices(substring))
new_text = text.replace(substring, combination)
_all_unique_texts(new_text, final)
return
elif c == char_opening:
stack.append(c)
indexes.append(i)
|
python
|
def _all_unique_texts(text, final):
"""
Compute all the possible unique texts
@type text: str
@param text: Text written used spin syntax
@type final: list
@param final: An empty list where all the unique texts will be stored
@return: Nothing. The result will be in the 'final' list
"""
if not char_opening in text:
if not text in final:
final.append(text)
return
stack = []
indexes = []
for i, c in enumerate(text):
if c == char_closing:
if stack[-1] == char_opening:
start_index = indexes.pop()
substring = '' if i == start_index + 1 else text[start_index:i + 1]
# get some random combination
combination = next(_choices(substring))
new_text = text.replace(substring, combination)
_all_unique_texts(new_text, final)
return
elif c == char_opening:
stack.append(c)
indexes.append(i)
|
[
"def",
"_all_unique_texts",
"(",
"text",
",",
"final",
")",
":",
"if",
"not",
"char_opening",
"in",
"text",
":",
"if",
"not",
"text",
"in",
"final",
":",
"final",
".",
"append",
"(",
"text",
")",
"return",
"stack",
"=",
"[",
"]",
"indexes",
"=",
"[",
"]",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"text",
")",
":",
"if",
"c",
"==",
"char_closing",
":",
"if",
"stack",
"[",
"-",
"1",
"]",
"==",
"char_opening",
":",
"start_index",
"=",
"indexes",
".",
"pop",
"(",
")",
"substring",
"=",
"''",
"if",
"i",
"==",
"start_index",
"+",
"1",
"else",
"text",
"[",
"start_index",
":",
"i",
"+",
"1",
"]",
"# get some random combination",
"combination",
"=",
"next",
"(",
"_choices",
"(",
"substring",
")",
")",
"new_text",
"=",
"text",
".",
"replace",
"(",
"substring",
",",
"combination",
")",
"_all_unique_texts",
"(",
"new_text",
",",
"final",
")",
"return",
"elif",
"c",
"==",
"char_opening",
":",
"stack",
".",
"append",
"(",
"c",
")",
"indexes",
".",
"append",
"(",
"i",
")"
] |
Compute all the possible unique texts
@type text: str
@param text: Text written used spin syntax
@type final: list
@param final: An empty list where all the unique texts will be stored
@return: Nothing. The result will be in the 'final' list
|
[
"Compute",
"all",
"the",
"possible",
"unique",
"texts"
] |
4615d92e669942c48d5542a23ddf6d40b206d9d5
|
https://github.com/omederos/pyspinner/blob/4615d92e669942c48d5542a23ddf6d40b206d9d5/spinning/spinning.py#L79-L109
|
238,060
|
omederos/pyspinner
|
spinning/spinning.py
|
_is_correct
|
def _is_correct(text):
"""
Check if the specified text has a correct spin syntax
@type text: str
@param text: Text written used spin syntax
@rtype: tuple
@return: A tuple: (is_correct, error). First position contains the result, and second one the error if not correct.
"""
error = ''
stack = []
for i, c in enumerate(text):
if c == char_opening:
stack.append(c)
elif c == char_closing:
if stack.count == 0:
error = 'Syntax incorrect. Found "}" before "{"'
break
last_char = stack.pop()
if last_char != char_opening:
error = 'Syntax incorrect. Found "}" before "{"'
break
if len(stack) > 0:
error = 'Syntax incorrect. Some "{" were not closed'
return not error, error
|
python
|
def _is_correct(text):
"""
Check if the specified text has a correct spin syntax
@type text: str
@param text: Text written used spin syntax
@rtype: tuple
@return: A tuple: (is_correct, error). First position contains the result, and second one the error if not correct.
"""
error = ''
stack = []
for i, c in enumerate(text):
if c == char_opening:
stack.append(c)
elif c == char_closing:
if stack.count == 0:
error = 'Syntax incorrect. Found "}" before "{"'
break
last_char = stack.pop()
if last_char != char_opening:
error = 'Syntax incorrect. Found "}" before "{"'
break
if len(stack) > 0:
error = 'Syntax incorrect. Some "{" were not closed'
return not error, error
|
[
"def",
"_is_correct",
"(",
"text",
")",
":",
"error",
"=",
"''",
"stack",
"=",
"[",
"]",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"text",
")",
":",
"if",
"c",
"==",
"char_opening",
":",
"stack",
".",
"append",
"(",
"c",
")",
"elif",
"c",
"==",
"char_closing",
":",
"if",
"stack",
".",
"count",
"==",
"0",
":",
"error",
"=",
"'Syntax incorrect. Found \"}\" before \"{\"'",
"break",
"last_char",
"=",
"stack",
".",
"pop",
"(",
")",
"if",
"last_char",
"!=",
"char_opening",
":",
"error",
"=",
"'Syntax incorrect. Found \"}\" before \"{\"'",
"break",
"if",
"len",
"(",
"stack",
")",
">",
"0",
":",
"error",
"=",
"'Syntax incorrect. Some \"{\" were not closed'",
"return",
"not",
"error",
",",
"error"
] |
Check if the specified text has a correct spin syntax
@type text: str
@param text: Text written used spin syntax
@rtype: tuple
@return: A tuple: (is_correct, error). First position contains the result, and second one the error if not correct.
|
[
"Check",
"if",
"the",
"specified",
"text",
"has",
"a",
"correct",
"spin",
"syntax"
] |
4615d92e669942c48d5542a23ddf6d40b206d9d5
|
https://github.com/omederos/pyspinner/blob/4615d92e669942c48d5542a23ddf6d40b206d9d5/spinning/spinning.py#L112-L137
|
238,061
|
matthieugouel/gibica
|
gibica/interpreter.py
|
Interpreter.visit_FunctionBody
|
def visit_FunctionBody(self, node):
"""Visitor for `FunctionBody` AST node."""
for child in node.children:
return_value = self.visit(child)
if isinstance(child, ReturnStatement):
return return_value
if isinstance(child, (IfStatement, WhileStatement)):
if return_value is not None:
return return_value
return NoneType()
|
python
|
def visit_FunctionBody(self, node):
"""Visitor for `FunctionBody` AST node."""
for child in node.children:
return_value = self.visit(child)
if isinstance(child, ReturnStatement):
return return_value
if isinstance(child, (IfStatement, WhileStatement)):
if return_value is not None:
return return_value
return NoneType()
|
[
"def",
"visit_FunctionBody",
"(",
"self",
",",
"node",
")",
":",
"for",
"child",
"in",
"node",
".",
"children",
":",
"return_value",
"=",
"self",
".",
"visit",
"(",
"child",
")",
"if",
"isinstance",
"(",
"child",
",",
"ReturnStatement",
")",
":",
"return",
"return_value",
"if",
"isinstance",
"(",
"child",
",",
"(",
"IfStatement",
",",
"WhileStatement",
")",
")",
":",
"if",
"return_value",
"is",
"not",
"None",
":",
"return",
"return_value",
"return",
"NoneType",
"(",
")"
] |
Visitor for `FunctionBody` AST node.
|
[
"Visitor",
"for",
"FunctionBody",
"AST",
"node",
"."
] |
65f937f7a6255078cc22eb7691a2897466032909
|
https://github.com/matthieugouel/gibica/blob/65f937f7a6255078cc22eb7691a2897466032909/gibica/interpreter.py#L73-L85
|
238,062
|
matthieugouel/gibica
|
gibica/interpreter.py
|
Interpreter.visit_WhileStatement
|
def visit_WhileStatement(self, node):
"""Visitor for `WhileStatement` AST node."""
while self.visit(node.condition):
result = self.visit(node.compound)
if result is not None:
return result
|
python
|
def visit_WhileStatement(self, node):
"""Visitor for `WhileStatement` AST node."""
while self.visit(node.condition):
result = self.visit(node.compound)
if result is not None:
return result
|
[
"def",
"visit_WhileStatement",
"(",
"self",
",",
"node",
")",
":",
"while",
"self",
".",
"visit",
"(",
"node",
".",
"condition",
")",
":",
"result",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"compound",
")",
"if",
"result",
"is",
"not",
"None",
":",
"return",
"result"
] |
Visitor for `WhileStatement` AST node.
|
[
"Visitor",
"for",
"WhileStatement",
"AST",
"node",
"."
] |
65f937f7a6255078cc22eb7691a2897466032909
|
https://github.com/matthieugouel/gibica/blob/65f937f7a6255078cc22eb7691a2897466032909/gibica/interpreter.py#L151-L156
|
238,063
|
matthieugouel/gibica
|
gibica/interpreter.py
|
Interpreter.visit_Compound
|
def visit_Compound(self, node):
"""Visitor for `Compound` AST node."""
self.memory.append_scope()
for child in node.children:
return_value = self.visit(child)
if isinstance(child, ReturnStatement):
return return_value
if isinstance(child, (IfStatement, WhileStatement)):
if return_value is not None:
return return_value
self.memory.pop_scope()
|
python
|
def visit_Compound(self, node):
"""Visitor for `Compound` AST node."""
self.memory.append_scope()
for child in node.children:
return_value = self.visit(child)
if isinstance(child, ReturnStatement):
return return_value
if isinstance(child, (IfStatement, WhileStatement)):
if return_value is not None:
return return_value
self.memory.pop_scope()
|
[
"def",
"visit_Compound",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"memory",
".",
"append_scope",
"(",
")",
"for",
"child",
"in",
"node",
".",
"children",
":",
"return_value",
"=",
"self",
".",
"visit",
"(",
"child",
")",
"if",
"isinstance",
"(",
"child",
",",
"ReturnStatement",
")",
":",
"return",
"return_value",
"if",
"isinstance",
"(",
"child",
",",
"(",
"IfStatement",
",",
"WhileStatement",
")",
")",
":",
"if",
"return_value",
"is",
"not",
"None",
":",
"return",
"return_value",
"self",
".",
"memory",
".",
"pop_scope",
"(",
")"
] |
Visitor for `Compound` AST node.
|
[
"Visitor",
"for",
"Compound",
"AST",
"node",
"."
] |
65f937f7a6255078cc22eb7691a2897466032909
|
https://github.com/matthieugouel/gibica/blob/65f937f7a6255078cc22eb7691a2897466032909/gibica/interpreter.py#L158-L170
|
238,064
|
matthieugouel/gibica
|
gibica/interpreter.py
|
Interpreter.visit_UnaryOperation
|
def visit_UnaryOperation(self, node):
"""Visitor for `UnaryOperation` AST node."""
if node.op.nature == Nature.PLUS:
return +self.visit(node.right)
elif node.op.nature == Nature.MINUS:
return -self.visit(node.right)
elif node.op.nature == Nature.NOT:
return Bool(not self.visit(node.right))
|
python
|
def visit_UnaryOperation(self, node):
"""Visitor for `UnaryOperation` AST node."""
if node.op.nature == Nature.PLUS:
return +self.visit(node.right)
elif node.op.nature == Nature.MINUS:
return -self.visit(node.right)
elif node.op.nature == Nature.NOT:
return Bool(not self.visit(node.right))
|
[
"def",
"visit_UnaryOperation",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"op",
".",
"nature",
"==",
"Nature",
".",
"PLUS",
":",
"return",
"+",
"self",
".",
"visit",
"(",
"node",
".",
"right",
")",
"elif",
"node",
".",
"op",
".",
"nature",
"==",
"Nature",
".",
"MINUS",
":",
"return",
"-",
"self",
".",
"visit",
"(",
"node",
".",
"right",
")",
"elif",
"node",
".",
"op",
".",
"nature",
"==",
"Nature",
".",
"NOT",
":",
"return",
"Bool",
"(",
"not",
"self",
".",
"visit",
"(",
"node",
".",
"right",
")",
")"
] |
Visitor for `UnaryOperation` AST node.
|
[
"Visitor",
"for",
"UnaryOperation",
"AST",
"node",
"."
] |
65f937f7a6255078cc22eb7691a2897466032909
|
https://github.com/matthieugouel/gibica/blob/65f937f7a6255078cc22eb7691a2897466032909/gibica/interpreter.py#L205-L212
|
238,065
|
matthieugouel/gibica
|
gibica/interpreter.py
|
Interpreter.visit_Boolean
|
def visit_Boolean(self, node):
"""Visitor for `Boolean` AST node."""
if node.value == 'true':
return Bool(True)
elif node.value == 'false':
return Bool(False)
|
python
|
def visit_Boolean(self, node):
"""Visitor for `Boolean` AST node."""
if node.value == 'true':
return Bool(True)
elif node.value == 'false':
return Bool(False)
|
[
"def",
"visit_Boolean",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"value",
"==",
"'true'",
":",
"return",
"Bool",
"(",
"True",
")",
"elif",
"node",
".",
"value",
"==",
"'false'",
":",
"return",
"Bool",
"(",
"False",
")"
] |
Visitor for `Boolean` AST node.
|
[
"Visitor",
"for",
"Boolean",
"AST",
"node",
"."
] |
65f937f7a6255078cc22eb7691a2897466032909
|
https://github.com/matthieugouel/gibica/blob/65f937f7a6255078cc22eb7691a2897466032909/gibica/interpreter.py#L226-L231
|
238,066
|
matthieugouel/gibica
|
gibica/interpreter.py
|
Interpreter.interpret
|
def interpret(self):
"""Generic entrypoint of `Interpreter` class."""
self.load_builtins()
self.load_functions(self.tree)
self.visit(self.tree)
|
python
|
def interpret(self):
"""Generic entrypoint of `Interpreter` class."""
self.load_builtins()
self.load_functions(self.tree)
self.visit(self.tree)
|
[
"def",
"interpret",
"(",
"self",
")",
":",
"self",
".",
"load_builtins",
"(",
")",
"self",
".",
"load_functions",
"(",
"self",
".",
"tree",
")",
"self",
".",
"visit",
"(",
"self",
".",
"tree",
")"
] |
Generic entrypoint of `Interpreter` class.
|
[
"Generic",
"entrypoint",
"of",
"Interpreter",
"class",
"."
] |
65f937f7a6255078cc22eb7691a2897466032909
|
https://github.com/matthieugouel/gibica/blob/65f937f7a6255078cc22eb7691a2897466032909/gibica/interpreter.py#L233-L237
|
238,067
|
andreasjansson/head-in-the-clouds
|
headintheclouds/ensemble/tasks.py
|
up
|
def up(name, debug=False):
'''
Create servers and containers as required to meet the configuration
specified in _name_.
Args:
* name: The name of the yaml config file (you can omit the .yml extension for convenience)
Example:
fab ensemble.up:wordpress
'''
if debug:
env.ensemble_debug = True
filenames_to_try = [
name,
'%s.yml' % name,
'%s.yaml' % name,
]
for filename in filenames_to_try:
if os.path.exists(filename):
with open(filename, 'r') as f:
config = yaml.load(f)
break
else:
abort('Ensemble manifest not found: %s' % name)
uncache()
try:
do_up(config)
except exceptions.ConfigException, e:
abort('Config error: ' + str(e))
|
python
|
def up(name, debug=False):
'''
Create servers and containers as required to meet the configuration
specified in _name_.
Args:
* name: The name of the yaml config file (you can omit the .yml extension for convenience)
Example:
fab ensemble.up:wordpress
'''
if debug:
env.ensemble_debug = True
filenames_to_try = [
name,
'%s.yml' % name,
'%s.yaml' % name,
]
for filename in filenames_to_try:
if os.path.exists(filename):
with open(filename, 'r') as f:
config = yaml.load(f)
break
else:
abort('Ensemble manifest not found: %s' % name)
uncache()
try:
do_up(config)
except exceptions.ConfigException, e:
abort('Config error: ' + str(e))
|
[
"def",
"up",
"(",
"name",
",",
"debug",
"=",
"False",
")",
":",
"if",
"debug",
":",
"env",
".",
"ensemble_debug",
"=",
"True",
"filenames_to_try",
"=",
"[",
"name",
",",
"'%s.yml'",
"%",
"name",
",",
"'%s.yaml'",
"%",
"name",
",",
"]",
"for",
"filename",
"in",
"filenames_to_try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"config",
"=",
"yaml",
".",
"load",
"(",
"f",
")",
"break",
"else",
":",
"abort",
"(",
"'Ensemble manifest not found: %s'",
"%",
"name",
")",
"uncache",
"(",
")",
"try",
":",
"do_up",
"(",
"config",
")",
"except",
"exceptions",
".",
"ConfigException",
",",
"e",
":",
"abort",
"(",
"'Config error: '",
"+",
"str",
"(",
"e",
")",
")"
] |
Create servers and containers as required to meet the configuration
specified in _name_.
Args:
* name: The name of the yaml config file (you can omit the .yml extension for convenience)
Example:
fab ensemble.up:wordpress
|
[
"Create",
"servers",
"and",
"containers",
"as",
"required",
"to",
"meet",
"the",
"configuration",
"specified",
"in",
"_name_",
"."
] |
32c1d00d01036834dc94368e7f38b0afd3f7a82f
|
https://github.com/andreasjansson/head-in-the-clouds/blob/32c1d00d01036834dc94368e7f38b0afd3f7a82f/headintheclouds/ensemble/tasks.py#L15-L48
|
238,068
|
ChrisCummins/labm8
|
prof.py
|
stop
|
def stop(name, file=sys.stderr):
"""
Stop a profiling timer.
Arguments:
name (str): The name of the timer to stop. If no name is given, stop
the global anonymous timer.
Returns:
bool: Whether or not profiling is enabled.
Raises:
KeyError: If the named timer does not exist.
"""
if is_enabled():
elapsed = (time() - __TIMERS[name])
if elapsed > 60:
elapsed_str = '{:.1f} m'.format(elapsed / 60)
elif elapsed > 1:
elapsed_str = '{:.1f} s'.format(elapsed)
else:
elapsed_str = '{:.1f} ms'.format(elapsed * 1000)
del __TIMERS[name]
print("[prof]", name, elapsed_str, file=file)
return is_enabled()
|
python
|
def stop(name, file=sys.stderr):
"""
Stop a profiling timer.
Arguments:
name (str): The name of the timer to stop. If no name is given, stop
the global anonymous timer.
Returns:
bool: Whether or not profiling is enabled.
Raises:
KeyError: If the named timer does not exist.
"""
if is_enabled():
elapsed = (time() - __TIMERS[name])
if elapsed > 60:
elapsed_str = '{:.1f} m'.format(elapsed / 60)
elif elapsed > 1:
elapsed_str = '{:.1f} s'.format(elapsed)
else:
elapsed_str = '{:.1f} ms'.format(elapsed * 1000)
del __TIMERS[name]
print("[prof]", name, elapsed_str, file=file)
return is_enabled()
|
[
"def",
"stop",
"(",
"name",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
":",
"if",
"is_enabled",
"(",
")",
":",
"elapsed",
"=",
"(",
"time",
"(",
")",
"-",
"__TIMERS",
"[",
"name",
"]",
")",
"if",
"elapsed",
">",
"60",
":",
"elapsed_str",
"=",
"'{:.1f} m'",
".",
"format",
"(",
"elapsed",
"/",
"60",
")",
"elif",
"elapsed",
">",
"1",
":",
"elapsed_str",
"=",
"'{:.1f} s'",
".",
"format",
"(",
"elapsed",
")",
"else",
":",
"elapsed_str",
"=",
"'{:.1f} ms'",
".",
"format",
"(",
"elapsed",
"*",
"1000",
")",
"del",
"__TIMERS",
"[",
"name",
"]",
"print",
"(",
"\"[prof]\"",
",",
"name",
",",
"elapsed_str",
",",
"file",
"=",
"file",
")",
"return",
"is_enabled",
"(",
")"
] |
Stop a profiling timer.
Arguments:
name (str): The name of the timer to stop. If no name is given, stop
the global anonymous timer.
Returns:
bool: Whether or not profiling is enabled.
Raises:
KeyError: If the named timer does not exist.
|
[
"Stop",
"a",
"profiling",
"timer",
"."
] |
dd10d67a757aefb180cb508f86696f99440c94f5
|
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/prof.py#L82-L110
|
238,069
|
ChrisCummins/labm8
|
prof.py
|
profile
|
def profile(fun, *args, **kwargs):
"""
Profile a function.
"""
timer_name = kwargs.pop("prof_name", None)
if not timer_name:
module = inspect.getmodule(fun)
c = [module.__name__]
parentclass = labtypes.get_class_that_defined_method(fun)
if parentclass:
c.append(parentclass.__name__)
c.append(fun.__name__)
timer_name = ".".join(c)
start(timer_name)
ret = fun(*args, **kwargs)
stop(timer_name)
return ret
|
python
|
def profile(fun, *args, **kwargs):
"""
Profile a function.
"""
timer_name = kwargs.pop("prof_name", None)
if not timer_name:
module = inspect.getmodule(fun)
c = [module.__name__]
parentclass = labtypes.get_class_that_defined_method(fun)
if parentclass:
c.append(parentclass.__name__)
c.append(fun.__name__)
timer_name = ".".join(c)
start(timer_name)
ret = fun(*args, **kwargs)
stop(timer_name)
return ret
|
[
"def",
"profile",
"(",
"fun",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timer_name",
"=",
"kwargs",
".",
"pop",
"(",
"\"prof_name\"",
",",
"None",
")",
"if",
"not",
"timer_name",
":",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
"fun",
")",
"c",
"=",
"[",
"module",
".",
"__name__",
"]",
"parentclass",
"=",
"labtypes",
".",
"get_class_that_defined_method",
"(",
"fun",
")",
"if",
"parentclass",
":",
"c",
".",
"append",
"(",
"parentclass",
".",
"__name__",
")",
"c",
".",
"append",
"(",
"fun",
".",
"__name__",
")",
"timer_name",
"=",
"\".\"",
".",
"join",
"(",
"c",
")",
"start",
"(",
"timer_name",
")",
"ret",
"=",
"fun",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"stop",
"(",
"timer_name",
")",
"return",
"ret"
] |
Profile a function.
|
[
"Profile",
"a",
"function",
"."
] |
dd10d67a757aefb180cb508f86696f99440c94f5
|
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/prof.py#L113-L131
|
238,070
|
TrafficSenseMSD/SumoTools
|
sumolib/miscutils.py
|
geh
|
def geh(m, c):
"""Error function for hourly traffic flow measures after Geoffrey E. Havers"""
if m + c == 0:
return 0
else:
return math.sqrt(2 * (m - c) * (m - c) / (m + c))
|
python
|
def geh(m, c):
"""Error function for hourly traffic flow measures after Geoffrey E. Havers"""
if m + c == 0:
return 0
else:
return math.sqrt(2 * (m - c) * (m - c) / (m + c))
|
[
"def",
"geh",
"(",
"m",
",",
"c",
")",
":",
"if",
"m",
"+",
"c",
"==",
"0",
":",
"return",
"0",
"else",
":",
"return",
"math",
".",
"sqrt",
"(",
"2",
"*",
"(",
"m",
"-",
"c",
")",
"*",
"(",
"m",
"-",
"c",
")",
"/",
"(",
"m",
"+",
"c",
")",
")"
] |
Error function for hourly traffic flow measures after Geoffrey E. Havers
|
[
"Error",
"function",
"for",
"hourly",
"traffic",
"flow",
"measures",
"after",
"Geoffrey",
"E",
".",
"Havers"
] |
8607b4f885f1d1798e43240be643efe6dccccdaa
|
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/miscutils.py#L225-L230
|
238,071
|
TrafficSenseMSD/SumoTools
|
sumolib/miscutils.py
|
Statistics.avg
|
def avg(self):
"""return the mean value"""
# XXX rename this method
if len(self.values) > 0:
return sum(self.values) / float(len(self.values))
else:
return None
|
python
|
def avg(self):
"""return the mean value"""
# XXX rename this method
if len(self.values) > 0:
return sum(self.values) / float(len(self.values))
else:
return None
|
[
"def",
"avg",
"(",
"self",
")",
":",
"# XXX rename this method",
"if",
"len",
"(",
"self",
".",
"values",
")",
">",
"0",
":",
"return",
"sum",
"(",
"self",
".",
"values",
")",
"/",
"float",
"(",
"len",
"(",
"self",
".",
"values",
")",
")",
"else",
":",
"return",
"None"
] |
return the mean value
|
[
"return",
"the",
"mean",
"value"
] |
8607b4f885f1d1798e43240be643efe6dccccdaa
|
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/miscutils.py#L124-L130
|
238,072
|
TrafficSenseMSD/SumoTools
|
sumolib/miscutils.py
|
Statistics.avg_abs
|
def avg_abs(self):
"""return the mean of absolute values"""
# XXX rename this method
if len(self.values) > 0:
return sum(map(abs, self.values)) / float(len(self.values))
else:
return None
|
python
|
def avg_abs(self):
"""return the mean of absolute values"""
# XXX rename this method
if len(self.values) > 0:
return sum(map(abs, self.values)) / float(len(self.values))
else:
return None
|
[
"def",
"avg_abs",
"(",
"self",
")",
":",
"# XXX rename this method",
"if",
"len",
"(",
"self",
".",
"values",
")",
">",
"0",
":",
"return",
"sum",
"(",
"map",
"(",
"abs",
",",
"self",
".",
"values",
")",
")",
"/",
"float",
"(",
"len",
"(",
"self",
".",
"values",
")",
")",
"else",
":",
"return",
"None"
] |
return the mean of absolute values
|
[
"return",
"the",
"mean",
"of",
"absolute",
"values"
] |
8607b4f885f1d1798e43240be643efe6dccccdaa
|
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/miscutils.py#L132-L138
|
238,073
|
TrafficSenseMSD/SumoTools
|
sumolib/miscutils.py
|
Statistics.meanAndStdDev
|
def meanAndStdDev(self, limit=None):
"""return the mean and the standard deviation optionally limited to the last limit values"""
if limit is None or len(self.values) < limit:
limit = len(self.values)
if limit > 0:
mean = sum(self.values[-limit:]) / float(limit)
sumSq = 0.
for v in self.values[-limit:]:
sumSq += (v - mean) * (v - mean)
return mean, math.sqrt(sumSq / limit)
else:
return None
|
python
|
def meanAndStdDev(self, limit=None):
"""return the mean and the standard deviation optionally limited to the last limit values"""
if limit is None or len(self.values) < limit:
limit = len(self.values)
if limit > 0:
mean = sum(self.values[-limit:]) / float(limit)
sumSq = 0.
for v in self.values[-limit:]:
sumSq += (v - mean) * (v - mean)
return mean, math.sqrt(sumSq / limit)
else:
return None
|
[
"def",
"meanAndStdDev",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"if",
"limit",
"is",
"None",
"or",
"len",
"(",
"self",
".",
"values",
")",
"<",
"limit",
":",
"limit",
"=",
"len",
"(",
"self",
".",
"values",
")",
"if",
"limit",
">",
"0",
":",
"mean",
"=",
"sum",
"(",
"self",
".",
"values",
"[",
"-",
"limit",
":",
"]",
")",
"/",
"float",
"(",
"limit",
")",
"sumSq",
"=",
"0.",
"for",
"v",
"in",
"self",
".",
"values",
"[",
"-",
"limit",
":",
"]",
":",
"sumSq",
"+=",
"(",
"v",
"-",
"mean",
")",
"*",
"(",
"v",
"-",
"mean",
")",
"return",
"mean",
",",
"math",
".",
"sqrt",
"(",
"sumSq",
"/",
"limit",
")",
"else",
":",
"return",
"None"
] |
return the mean and the standard deviation optionally limited to the last limit values
|
[
"return",
"the",
"mean",
"and",
"the",
"standard",
"deviation",
"optionally",
"limited",
"to",
"the",
"last",
"limit",
"values"
] |
8607b4f885f1d1798e43240be643efe6dccccdaa
|
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/miscutils.py#L140-L151
|
238,074
|
TrafficSenseMSD/SumoTools
|
sumolib/miscutils.py
|
Statistics.relStdDev
|
def relStdDev(self, limit=None):
"""return the relative standard deviation optionally limited to the last limit values"""
moments = self.meanAndStdDev(limit)
if moments is None:
return None
return moments[1] / moments[0]
|
python
|
def relStdDev(self, limit=None):
"""return the relative standard deviation optionally limited to the last limit values"""
moments = self.meanAndStdDev(limit)
if moments is None:
return None
return moments[1] / moments[0]
|
[
"def",
"relStdDev",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"moments",
"=",
"self",
".",
"meanAndStdDev",
"(",
"limit",
")",
"if",
"moments",
"is",
"None",
":",
"return",
"None",
"return",
"moments",
"[",
"1",
"]",
"/",
"moments",
"[",
"0",
"]"
] |
return the relative standard deviation optionally limited to the last limit values
|
[
"return",
"the",
"relative",
"standard",
"deviation",
"optionally",
"limited",
"to",
"the",
"last",
"limit",
"values"
] |
8607b4f885f1d1798e43240be643efe6dccccdaa
|
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/miscutils.py#L153-L158
|
238,075
|
TrafficSenseMSD/SumoTools
|
sumolib/miscutils.py
|
Statistics.mean
|
def mean(self):
"""return the median value"""
# XXX rename this method
if len(self.values) > 0:
return sorted(self.values)[len(self.values) / 2]
else:
return None
|
python
|
def mean(self):
"""return the median value"""
# XXX rename this method
if len(self.values) > 0:
return sorted(self.values)[len(self.values) / 2]
else:
return None
|
[
"def",
"mean",
"(",
"self",
")",
":",
"# XXX rename this method",
"if",
"len",
"(",
"self",
".",
"values",
")",
">",
"0",
":",
"return",
"sorted",
"(",
"self",
".",
"values",
")",
"[",
"len",
"(",
"self",
".",
"values",
")",
"/",
"2",
"]",
"else",
":",
"return",
"None"
] |
return the median value
|
[
"return",
"the",
"median",
"value"
] |
8607b4f885f1d1798e43240be643efe6dccccdaa
|
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/miscutils.py#L160-L166
|
238,076
|
TrafficSenseMSD/SumoTools
|
sumolib/miscutils.py
|
Statistics.mean_abs
|
def mean_abs(self):
"""return the median of absolute values"""
# XXX rename this method
if len(self.values) > 0:
return sorted(map(abs, self.values))[len(self.values) / 2]
else:
return None
|
python
|
def mean_abs(self):
"""return the median of absolute values"""
# XXX rename this method
if len(self.values) > 0:
return sorted(map(abs, self.values))[len(self.values) / 2]
else:
return None
|
[
"def",
"mean_abs",
"(",
"self",
")",
":",
"# XXX rename this method",
"if",
"len",
"(",
"self",
".",
"values",
")",
">",
"0",
":",
"return",
"sorted",
"(",
"map",
"(",
"abs",
",",
"self",
".",
"values",
")",
")",
"[",
"len",
"(",
"self",
".",
"values",
")",
"/",
"2",
"]",
"else",
":",
"return",
"None"
] |
return the median of absolute values
|
[
"return",
"the",
"median",
"of",
"absolute",
"values"
] |
8607b4f885f1d1798e43240be643efe6dccccdaa
|
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/miscutils.py#L168-L174
|
238,077
|
egineering-llc/egat
|
egat/loggers/html_logger.py
|
HTMLWriter.copy_resources_to_log_dir
|
def copy_resources_to_log_dir(log_dir):
"""Copies the necessary static assets to the log_dir and returns the path
of the main css file."""
css_path = resource_filename(Requirement.parse("egat"), "/egat/data/default.css")
header_path = resource_filename(Requirement.parse("egat"), "/egat/data/egat_header.png")
shutil.copyfile(css_path, log_dir + "/style.css")
shutil.copyfile(header_path, log_dir + "/egat_header.png")
return log_dir + os.sep + "style.css"
|
python
|
def copy_resources_to_log_dir(log_dir):
"""Copies the necessary static assets to the log_dir and returns the path
of the main css file."""
css_path = resource_filename(Requirement.parse("egat"), "/egat/data/default.css")
header_path = resource_filename(Requirement.parse("egat"), "/egat/data/egat_header.png")
shutil.copyfile(css_path, log_dir + "/style.css")
shutil.copyfile(header_path, log_dir + "/egat_header.png")
return log_dir + os.sep + "style.css"
|
[
"def",
"copy_resources_to_log_dir",
"(",
"log_dir",
")",
":",
"css_path",
"=",
"resource_filename",
"(",
"Requirement",
".",
"parse",
"(",
"\"egat\"",
")",
",",
"\"/egat/data/default.css\"",
")",
"header_path",
"=",
"resource_filename",
"(",
"Requirement",
".",
"parse",
"(",
"\"egat\"",
")",
",",
"\"/egat/data/egat_header.png\"",
")",
"shutil",
".",
"copyfile",
"(",
"css_path",
",",
"log_dir",
"+",
"\"/style.css\"",
")",
"shutil",
".",
"copyfile",
"(",
"header_path",
",",
"log_dir",
"+",
"\"/egat_header.png\"",
")",
"return",
"log_dir",
"+",
"os",
".",
"sep",
"+",
"\"style.css\""
] |
Copies the necessary static assets to the log_dir and returns the path
of the main css file.
|
[
"Copies",
"the",
"necessary",
"static",
"assets",
"to",
"the",
"log_dir",
"and",
"returns",
"the",
"path",
"of",
"the",
"main",
"css",
"file",
"."
] |
63a172276b554ae1c7d0f13ba305881201c49d55
|
https://github.com/egineering-llc/egat/blob/63a172276b554ae1c7d0f13ba305881201c49d55/egat/loggers/html_logger.py#L28-L36
|
238,078
|
egineering-llc/egat
|
egat/loggers/html_logger.py
|
HTMLWriter.dump_queue
|
def dump_queue(queue):
"""
Empties all pending items in a queue and returns them in a list.
"""
result = []
try:
while True:
item = queue.get_nowait()
result.append(item)
except: Empty
return result
|
python
|
def dump_queue(queue):
"""
Empties all pending items in a queue and returns them in a list.
"""
result = []
try:
while True:
item = queue.get_nowait()
result.append(item)
except: Empty
return result
|
[
"def",
"dump_queue",
"(",
"queue",
")",
":",
"result",
"=",
"[",
"]",
"try",
":",
"while",
"True",
":",
"item",
"=",
"queue",
".",
"get_nowait",
"(",
")",
"result",
".",
"append",
"(",
"item",
")",
"except",
":",
"Empty",
"return",
"result"
] |
Empties all pending items in a queue and returns them in a list.
|
[
"Empties",
"all",
"pending",
"items",
"in",
"a",
"queue",
"and",
"returns",
"them",
"in",
"a",
"list",
"."
] |
63a172276b554ae1c7d0f13ba305881201c49d55
|
https://github.com/egineering-llc/egat/blob/63a172276b554ae1c7d0f13ba305881201c49d55/egat/loggers/html_logger.py#L267-L279
|
238,079
|
jimzhan/pyx
|
rex/core/system.py
|
execute
|
def execute(command, cwd=os.path.curdir, **options):
"""
Run the system command with optional options.
Args:
* command: system command.
* cwd: current working directory.
* verbose: direct options for :func:`subprocess.Popen`.
Returns:
Opened process, standard output & error.
"""
process = subprocess.Popen(shlex.split(command), cwd=cwd, **options)
stdout, stderr = process.communicate()
return process, stdout, stderr
|
python
|
def execute(command, cwd=os.path.curdir, **options):
"""
Run the system command with optional options.
Args:
* command: system command.
* cwd: current working directory.
* verbose: direct options for :func:`subprocess.Popen`.
Returns:
Opened process, standard output & error.
"""
process = subprocess.Popen(shlex.split(command), cwd=cwd, **options)
stdout, stderr = process.communicate()
return process, stdout, stderr
|
[
"def",
"execute",
"(",
"command",
",",
"cwd",
"=",
"os",
".",
"path",
".",
"curdir",
",",
"*",
"*",
"options",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"shlex",
".",
"split",
"(",
"command",
")",
",",
"cwd",
"=",
"cwd",
",",
"*",
"*",
"options",
")",
"stdout",
",",
"stderr",
"=",
"process",
".",
"communicate",
"(",
")",
"return",
"process",
",",
"stdout",
",",
"stderr"
] |
Run the system command with optional options.
Args:
* command: system command.
* cwd: current working directory.
* verbose: direct options for :func:`subprocess.Popen`.
Returns:
Opened process, standard output & error.
|
[
"Run",
"the",
"system",
"command",
"with",
"optional",
"options",
"."
] |
819e8251323a7923e196c0c438aa8524f5aaee6e
|
https://github.com/jimzhan/pyx/blob/819e8251323a7923e196c0c438aa8524f5aaee6e/rex/core/system.py#L13-L27
|
238,080
|
Nurdok/basicstruct
|
src/basicstruct.py
|
BasicStruct.to_dict
|
def to_dict(self, copy=False):
"""Convert the struct to a dictionary.
If `copy == True`, returns a deep copy of the values.
"""
new_dict = {}
for attr, value in self:
if copy:
value = deepcopy(value)
new_dict[attr] = value
return new_dict
|
python
|
def to_dict(self, copy=False):
"""Convert the struct to a dictionary.
If `copy == True`, returns a deep copy of the values.
"""
new_dict = {}
for attr, value in self:
if copy:
value = deepcopy(value)
new_dict[attr] = value
return new_dict
|
[
"def",
"to_dict",
"(",
"self",
",",
"copy",
"=",
"False",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"attr",
",",
"value",
"in",
"self",
":",
"if",
"copy",
":",
"value",
"=",
"deepcopy",
"(",
"value",
")",
"new_dict",
"[",
"attr",
"]",
"=",
"value",
"return",
"new_dict"
] |
Convert the struct to a dictionary.
If `copy == True`, returns a deep copy of the values.
|
[
"Convert",
"the",
"struct",
"to",
"a",
"dictionary",
"."
] |
6f1104c06f3f0a1b63cf4ab620baceea5c4c8f55
|
https://github.com/Nurdok/basicstruct/blob/6f1104c06f3f0a1b63cf4ab620baceea5c4c8f55/src/basicstruct.py#L42-L54
|
238,081
|
bfrog/whizzer
|
whizzer/process.py
|
Process.start
|
def start(self):
"""Start the process, essentially forks and calls target function."""
logger.info("starting process")
process = os.fork()
time.sleep(0.01)
if process != 0:
logger.debug('starting child watcher')
self.loop.reset()
self.child_pid = process
self.watcher = pyev.Child(self.child_pid, False, self.loop, self._child)
self.watcher.start()
else:
self.loop.reset()
logger.debug('running main function')
self.run(*self.args, **self.kwargs)
logger.debug('quitting')
sys.exit(0)
|
python
|
def start(self):
"""Start the process, essentially forks and calls target function."""
logger.info("starting process")
process = os.fork()
time.sleep(0.01)
if process != 0:
logger.debug('starting child watcher')
self.loop.reset()
self.child_pid = process
self.watcher = pyev.Child(self.child_pid, False, self.loop, self._child)
self.watcher.start()
else:
self.loop.reset()
logger.debug('running main function')
self.run(*self.args, **self.kwargs)
logger.debug('quitting')
sys.exit(0)
|
[
"def",
"start",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"starting process\"",
")",
"process",
"=",
"os",
".",
"fork",
"(",
")",
"time",
".",
"sleep",
"(",
"0.01",
")",
"if",
"process",
"!=",
"0",
":",
"logger",
".",
"debug",
"(",
"'starting child watcher'",
")",
"self",
".",
"loop",
".",
"reset",
"(",
")",
"self",
".",
"child_pid",
"=",
"process",
"self",
".",
"watcher",
"=",
"pyev",
".",
"Child",
"(",
"self",
".",
"child_pid",
",",
"False",
",",
"self",
".",
"loop",
",",
"self",
".",
"_child",
")",
"self",
".",
"watcher",
".",
"start",
"(",
")",
"else",
":",
"self",
".",
"loop",
".",
"reset",
"(",
")",
"logger",
".",
"debug",
"(",
"'running main function'",
")",
"self",
".",
"run",
"(",
"*",
"self",
".",
"args",
",",
"*",
"*",
"self",
".",
"kwargs",
")",
"logger",
".",
"debug",
"(",
"'quitting'",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] |
Start the process, essentially forks and calls target function.
|
[
"Start",
"the",
"process",
"essentially",
"forks",
"and",
"calls",
"target",
"function",
"."
] |
a1e43084b3ac8c1f3fb4ada081777cdbf791fd77
|
https://github.com/bfrog/whizzer/blob/a1e43084b3ac8c1f3fb4ada081777cdbf791fd77/whizzer/process.py#L45-L61
|
238,082
|
baguette-io/baguette-messaging
|
farine/connectors/sql/__init__.py
|
setup
|
def setup(settings):
"""
Setup the database connection.
"""
connector = settings.get('db_connector')
if connector == 'postgres':
from playhouse.pool import PooledPostgresqlExtDatabase
return PooledPostgresqlExtDatabase(settings['db_name'],
user=settings['db_user'],
password=settings['db_password'],
host=settings['db_host'],
port=settings.get('db_port'),
max_connections=settings.get('db_max_conn'),
stale_timeout=settings.get('db_stale_timeout'),
timeout=settings.get('db_timeout'),
register_hstore=False)
|
python
|
def setup(settings):
"""
Setup the database connection.
"""
connector = settings.get('db_connector')
if connector == 'postgres':
from playhouse.pool import PooledPostgresqlExtDatabase
return PooledPostgresqlExtDatabase(settings['db_name'],
user=settings['db_user'],
password=settings['db_password'],
host=settings['db_host'],
port=settings.get('db_port'),
max_connections=settings.get('db_max_conn'),
stale_timeout=settings.get('db_stale_timeout'),
timeout=settings.get('db_timeout'),
register_hstore=False)
|
[
"def",
"setup",
"(",
"settings",
")",
":",
"connector",
"=",
"settings",
".",
"get",
"(",
"'db_connector'",
")",
"if",
"connector",
"==",
"'postgres'",
":",
"from",
"playhouse",
".",
"pool",
"import",
"PooledPostgresqlExtDatabase",
"return",
"PooledPostgresqlExtDatabase",
"(",
"settings",
"[",
"'db_name'",
"]",
",",
"user",
"=",
"settings",
"[",
"'db_user'",
"]",
",",
"password",
"=",
"settings",
"[",
"'db_password'",
"]",
",",
"host",
"=",
"settings",
"[",
"'db_host'",
"]",
",",
"port",
"=",
"settings",
".",
"get",
"(",
"'db_port'",
")",
",",
"max_connections",
"=",
"settings",
".",
"get",
"(",
"'db_max_conn'",
")",
",",
"stale_timeout",
"=",
"settings",
".",
"get",
"(",
"'db_stale_timeout'",
")",
",",
"timeout",
"=",
"settings",
".",
"get",
"(",
"'db_timeout'",
")",
",",
"register_hstore",
"=",
"False",
")"
] |
Setup the database connection.
|
[
"Setup",
"the",
"database",
"connection",
"."
] |
8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1
|
https://github.com/baguette-io/baguette-messaging/blob/8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1/farine/connectors/sql/__init__.py#L31-L46
|
238,083
|
baguette-io/baguette-messaging
|
farine/connectors/sql/__init__.py
|
init
|
def init(module, db):
"""
Initialize the models.
"""
for model in farine.discovery.import_models(module):
model._meta.database = db
|
python
|
def init(module, db):
"""
Initialize the models.
"""
for model in farine.discovery.import_models(module):
model._meta.database = db
|
[
"def",
"init",
"(",
"module",
",",
"db",
")",
":",
"for",
"model",
"in",
"farine",
".",
"discovery",
".",
"import_models",
"(",
"module",
")",
":",
"model",
".",
"_meta",
".",
"database",
"=",
"db"
] |
Initialize the models.
|
[
"Initialize",
"the",
"models",
"."
] |
8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1
|
https://github.com/baguette-io/baguette-messaging/blob/8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1/farine/connectors/sql/__init__.py#L48-L53
|
238,084
|
baguette-io/baguette-messaging
|
farine/connectors/sql/__init__.py
|
Model.to_json
|
def to_json(self, extras=None):
"""
Convert a model into a json using the playhouse shortcut.
"""
extras = extras or {}
to_dict = model_to_dict(self)
to_dict.update(extras)
return json.dumps(to_dict, cls=sel.serializers.JsonEncoder)
|
python
|
def to_json(self, extras=None):
"""
Convert a model into a json using the playhouse shortcut.
"""
extras = extras or {}
to_dict = model_to_dict(self)
to_dict.update(extras)
return json.dumps(to_dict, cls=sel.serializers.JsonEncoder)
|
[
"def",
"to_json",
"(",
"self",
",",
"extras",
"=",
"None",
")",
":",
"extras",
"=",
"extras",
"or",
"{",
"}",
"to_dict",
"=",
"model_to_dict",
"(",
"self",
")",
"to_dict",
".",
"update",
"(",
"extras",
")",
"return",
"json",
".",
"dumps",
"(",
"to_dict",
",",
"cls",
"=",
"sel",
".",
"serializers",
".",
"JsonEncoder",
")"
] |
Convert a model into a json using the playhouse shortcut.
|
[
"Convert",
"a",
"model",
"into",
"a",
"json",
"using",
"the",
"playhouse",
"shortcut",
"."
] |
8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1
|
https://github.com/baguette-io/baguette-messaging/blob/8d1c4707ea7eace8617fed2d97df2fcc9d0cdee1/farine/connectors/sql/__init__.py#L19-L26
|
238,085
|
bwesterb/sarah
|
src/lazy.py
|
lazy
|
def lazy(func):
""" Decorator, which can be used for lazy imports
@lazy
def yaml():
import yaml
return yaml """
try:
frame = sys._getframe(1)
except Exception:
_locals = None
else:
_locals = frame.f_locals
func_name = func.func_name if six.PY2 else func.__name__
return LazyStub(func_name, func, _locals)
|
python
|
def lazy(func):
""" Decorator, which can be used for lazy imports
@lazy
def yaml():
import yaml
return yaml """
try:
frame = sys._getframe(1)
except Exception:
_locals = None
else:
_locals = frame.f_locals
func_name = func.func_name if six.PY2 else func.__name__
return LazyStub(func_name, func, _locals)
|
[
"def",
"lazy",
"(",
"func",
")",
":",
"try",
":",
"frame",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
"except",
"Exception",
":",
"_locals",
"=",
"None",
"else",
":",
"_locals",
"=",
"frame",
".",
"f_locals",
"func_name",
"=",
"func",
".",
"func_name",
"if",
"six",
".",
"PY2",
"else",
"func",
".",
"__name__",
"return",
"LazyStub",
"(",
"func_name",
",",
"func",
",",
"_locals",
")"
] |
Decorator, which can be used for lazy imports
@lazy
def yaml():
import yaml
return yaml
|
[
"Decorator",
"which",
"can",
"be",
"used",
"for",
"lazy",
"imports"
] |
a9e46e875dfff1dc11255d714bb736e5eb697809
|
https://github.com/bwesterb/sarah/blob/a9e46e875dfff1dc11255d714bb736e5eb697809/src/lazy.py#L8-L22
|
238,086
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
ReftrackRoot.add_reftrack
|
def add_reftrack(self, reftrack):
"""Add a reftrack object to the root.
This will not handle row insertion in the model!
It is automatically done when setting the parent of the :class:`Reftrack` object.
:param reftrack: the reftrack object to add
:type reftrack: :class:`Reftrack`
:returns: None
:rtype: None
:raises: None
"""
self._reftracks.add(reftrack)
refobj = reftrack.get_refobj()
if refobj:
self._parentsearchdict[refobj] = reftrack
|
python
|
def add_reftrack(self, reftrack):
"""Add a reftrack object to the root.
This will not handle row insertion in the model!
It is automatically done when setting the parent of the :class:`Reftrack` object.
:param reftrack: the reftrack object to add
:type reftrack: :class:`Reftrack`
:returns: None
:rtype: None
:raises: None
"""
self._reftracks.add(reftrack)
refobj = reftrack.get_refobj()
if refobj:
self._parentsearchdict[refobj] = reftrack
|
[
"def",
"add_reftrack",
"(",
"self",
",",
"reftrack",
")",
":",
"self",
".",
"_reftracks",
".",
"add",
"(",
"reftrack",
")",
"refobj",
"=",
"reftrack",
".",
"get_refobj",
"(",
")",
"if",
"refobj",
":",
"self",
".",
"_parentsearchdict",
"[",
"refobj",
"]",
"=",
"reftrack"
] |
Add a reftrack object to the root.
This will not handle row insertion in the model!
It is automatically done when setting the parent of the :class:`Reftrack` object.
:param reftrack: the reftrack object to add
:type reftrack: :class:`Reftrack`
:returns: None
:rtype: None
:raises: None
|
[
"Add",
"a",
"reftrack",
"object",
"to",
"the",
"root",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L293-L308
|
238,087
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
ReftrackRoot.remove_reftrack
|
def remove_reftrack(self, reftrack):
"""Remove the reftrack from the root.
This will not handle row deletion in the model!
It is automatically done when calling :meth:`Reftrack.delete`.
:param reftrack: the reftrack object to remove
:type reftrack: :class:`Reftrack`
:returns: None
:rtype: None
:raises: None
"""
self._reftracks.remove(reftrack)
refobj = reftrack.get_refobj()
if refobj and refobj in self._parentsearchdict:
del self._parentsearchdict[refobj]
|
python
|
def remove_reftrack(self, reftrack):
"""Remove the reftrack from the root.
This will not handle row deletion in the model!
It is automatically done when calling :meth:`Reftrack.delete`.
:param reftrack: the reftrack object to remove
:type reftrack: :class:`Reftrack`
:returns: None
:rtype: None
:raises: None
"""
self._reftracks.remove(reftrack)
refobj = reftrack.get_refobj()
if refobj and refobj in self._parentsearchdict:
del self._parentsearchdict[refobj]
|
[
"def",
"remove_reftrack",
"(",
"self",
",",
"reftrack",
")",
":",
"self",
".",
"_reftracks",
".",
"remove",
"(",
"reftrack",
")",
"refobj",
"=",
"reftrack",
".",
"get_refobj",
"(",
")",
"if",
"refobj",
"and",
"refobj",
"in",
"self",
".",
"_parentsearchdict",
":",
"del",
"self",
".",
"_parentsearchdict",
"[",
"refobj",
"]"
] |
Remove the reftrack from the root.
This will not handle row deletion in the model!
It is automatically done when calling :meth:`Reftrack.delete`.
:param reftrack: the reftrack object to remove
:type reftrack: :class:`Reftrack`
:returns: None
:rtype: None
:raises: None
|
[
"Remove",
"the",
"reftrack",
"from",
"the",
"root",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L310-L325
|
238,088
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
ReftrackRoot.update_refobj
|
def update_refobj(self, old, new, reftrack):
"""Update the parent search dict so that the reftrack can be found
with the new refobj and delete the entry for the old refobj.
Old or new can also be None.
:param old: the old refobj of reftrack
:param new: the new refobj of reftrack
:param reftrack: The reftrack, which refobj was updated
:type reftrack: :class:`Reftrack`
:returns: None
:rtype: None
:raises: None
"""
if old:
del self._parentsearchdict[old]
if new:
self._parentsearchdict[new] = reftrack
|
python
|
def update_refobj(self, old, new, reftrack):
"""Update the parent search dict so that the reftrack can be found
with the new refobj and delete the entry for the old refobj.
Old or new can also be None.
:param old: the old refobj of reftrack
:param new: the new refobj of reftrack
:param reftrack: The reftrack, which refobj was updated
:type reftrack: :class:`Reftrack`
:returns: None
:rtype: None
:raises: None
"""
if old:
del self._parentsearchdict[old]
if new:
self._parentsearchdict[new] = reftrack
|
[
"def",
"update_refobj",
"(",
"self",
",",
"old",
",",
"new",
",",
"reftrack",
")",
":",
"if",
"old",
":",
"del",
"self",
".",
"_parentsearchdict",
"[",
"old",
"]",
"if",
"new",
":",
"self",
".",
"_parentsearchdict",
"[",
"new",
"]",
"=",
"reftrack"
] |
Update the parent search dict so that the reftrack can be found
with the new refobj and delete the entry for the old refobj.
Old or new can also be None.
:param old: the old refobj of reftrack
:param new: the new refobj of reftrack
:param reftrack: The reftrack, which refobj was updated
:type reftrack: :class:`Reftrack`
:returns: None
:rtype: None
:raises: None
|
[
"Update",
"the",
"parent",
"search",
"dict",
"so",
"that",
"the",
"reftrack",
"can",
"be",
"found",
"with",
"the",
"new",
"refobj",
"and",
"delete",
"the",
"entry",
"for",
"the",
"old",
"refobj",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L327-L344
|
238,089
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
ReftrackRoot.get_scene_suggestions
|
def get_scene_suggestions(self, refobjinter):
"""Return a list of suggested Reftracks for the current scene, that are not already
in this root.
A suggestion is a combination of type and element.
:param refobjinter: a programm specific reftrack object interface
:type refobjinter: :class:`RefobjInterface`
:returns: A list of suggestions
:rtype: :class:`list`
:raises: None
"""
sugs = []
cur = refobjinter.get_current_element()
if not cur:
return sugs
for typ in refobjinter.types:
inter = refobjinter.get_typ_interface(typ)
elements = inter.get_scene_suggestions(cur)
for e in elements:
for r in self._reftracks:
if not r.get_parent() and typ == r.get_typ() and e == r.get_element():
break
else:
sugs.append((typ, e))
return sugs
|
python
|
def get_scene_suggestions(self, refobjinter):
"""Return a list of suggested Reftracks for the current scene, that are not already
in this root.
A suggestion is a combination of type and element.
:param refobjinter: a programm specific reftrack object interface
:type refobjinter: :class:`RefobjInterface`
:returns: A list of suggestions
:rtype: :class:`list`
:raises: None
"""
sugs = []
cur = refobjinter.get_current_element()
if not cur:
return sugs
for typ in refobjinter.types:
inter = refobjinter.get_typ_interface(typ)
elements = inter.get_scene_suggestions(cur)
for e in elements:
for r in self._reftracks:
if not r.get_parent() and typ == r.get_typ() and e == r.get_element():
break
else:
sugs.append((typ, e))
return sugs
|
[
"def",
"get_scene_suggestions",
"(",
"self",
",",
"refobjinter",
")",
":",
"sugs",
"=",
"[",
"]",
"cur",
"=",
"refobjinter",
".",
"get_current_element",
"(",
")",
"if",
"not",
"cur",
":",
"return",
"sugs",
"for",
"typ",
"in",
"refobjinter",
".",
"types",
":",
"inter",
"=",
"refobjinter",
".",
"get_typ_interface",
"(",
"typ",
")",
"elements",
"=",
"inter",
".",
"get_scene_suggestions",
"(",
"cur",
")",
"for",
"e",
"in",
"elements",
":",
"for",
"r",
"in",
"self",
".",
"_reftracks",
":",
"if",
"not",
"r",
".",
"get_parent",
"(",
")",
"and",
"typ",
"==",
"r",
".",
"get_typ",
"(",
")",
"and",
"e",
"==",
"r",
".",
"get_element",
"(",
")",
":",
"break",
"else",
":",
"sugs",
".",
"append",
"(",
"(",
"typ",
",",
"e",
")",
")",
"return",
"sugs"
] |
Return a list of suggested Reftracks for the current scene, that are not already
in this root.
A suggestion is a combination of type and element.
:param refobjinter: a programm specific reftrack object interface
:type refobjinter: :class:`RefobjInterface`
:returns: A list of suggestions
:rtype: :class:`list`
:raises: None
|
[
"Return",
"a",
"list",
"of",
"suggested",
"Reftracks",
"for",
"the",
"current",
"scene",
"that",
"are",
"not",
"already",
"in",
"this",
"root",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L374-L399
|
238,090
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
Reftrack.get_unwrapped
|
def get_unwrapped(self, root, refobjinter):
"""Return a set with all refobjects in the scene that are not in already
wrapped in root.
:param root: the root that groups all reftracks and makes it possible to search for parents
:type root: :class:`ReftrackRoot`
:param refobjinter: a programm specific reftrack object interface
:type refobjinter: :class:`RefobjInterface`
:returns: a set with unwrapped refobjects
:rtype: set
:raises: None
"""
all_refobjs = set(refobjinter.get_all_refobjs())
wrapped = set(root._parentsearchdict.keys())
return all_refobjs - wrapped
|
python
|
def get_unwrapped(self, root, refobjinter):
"""Return a set with all refobjects in the scene that are not in already
wrapped in root.
:param root: the root that groups all reftracks and makes it possible to search for parents
:type root: :class:`ReftrackRoot`
:param refobjinter: a programm specific reftrack object interface
:type refobjinter: :class:`RefobjInterface`
:returns: a set with unwrapped refobjects
:rtype: set
:raises: None
"""
all_refobjs = set(refobjinter.get_all_refobjs())
wrapped = set(root._parentsearchdict.keys())
return all_refobjs - wrapped
|
[
"def",
"get_unwrapped",
"(",
"self",
",",
"root",
",",
"refobjinter",
")",
":",
"all_refobjs",
"=",
"set",
"(",
"refobjinter",
".",
"get_all_refobjs",
"(",
")",
")",
"wrapped",
"=",
"set",
"(",
"root",
".",
"_parentsearchdict",
".",
"keys",
"(",
")",
")",
"return",
"all_refobjs",
"-",
"wrapped"
] |
Return a set with all refobjects in the scene that are not in already
wrapped in root.
:param root: the root that groups all reftracks and makes it possible to search for parents
:type root: :class:`ReftrackRoot`
:param refobjinter: a programm specific reftrack object interface
:type refobjinter: :class:`RefobjInterface`
:returns: a set with unwrapped refobjects
:rtype: set
:raises: None
|
[
"Return",
"a",
"set",
"with",
"all",
"refobjects",
"in",
"the",
"scene",
"that",
"are",
"not",
"in",
"already",
"wrapped",
"in",
"root",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L592-L606
|
238,091
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
Reftrack.set_refobj
|
def set_refobj(self, refobj, setParent=True):
"""Set the reftrack object.
The reftrack object interface will determine typ, element, taskfileinfo, status and parent and set these values.
If the reftrack object is None, the :class:`Reftrack` object will keep the initial typ,
element but will loose it\'s parent, status and taskfileinfo
:param refobj: a reftrack object or None
:type refobj: None | reftrack object
:param setParent: If True, set also the parent
:type setParent: :class:`bool`
:returns: None
:rtype: None
:raises: None
"""
root = self.get_root()
old = self._refobj
self._refobj = refobj
refobjinter = self.get_refobjinter()
if self._refobj:
self.set_typ(refobjinter.get_typ(self._refobj))
self.set_taskfileinfo(refobjinter.get_taskfileinfo(self._refobj))
self.set_element(refobjinter.get_element(self._refobj))
if setParent:
parentrefobj = refobjinter.get_parent(self._refobj)
parentreftrack = root.get_reftrack(parentrefobj)
self.set_parent(parentreftrack)
self.set_status(refobjinter.get_status(self._refobj))
else:
self.set_taskfileinfo(None)
if setParent:
self.set_parent(None)
self.set_status(None)
root.update_refobj(old, refobj, self)
self.fetch_uptodate()
|
python
|
def set_refobj(self, refobj, setParent=True):
"""Set the reftrack object.
The reftrack object interface will determine typ, element, taskfileinfo, status and parent and set these values.
If the reftrack object is None, the :class:`Reftrack` object will keep the initial typ,
element but will loose it\'s parent, status and taskfileinfo
:param refobj: a reftrack object or None
:type refobj: None | reftrack object
:param setParent: If True, set also the parent
:type setParent: :class:`bool`
:returns: None
:rtype: None
:raises: None
"""
root = self.get_root()
old = self._refobj
self._refobj = refobj
refobjinter = self.get_refobjinter()
if self._refobj:
self.set_typ(refobjinter.get_typ(self._refobj))
self.set_taskfileinfo(refobjinter.get_taskfileinfo(self._refobj))
self.set_element(refobjinter.get_element(self._refobj))
if setParent:
parentrefobj = refobjinter.get_parent(self._refobj)
parentreftrack = root.get_reftrack(parentrefobj)
self.set_parent(parentreftrack)
self.set_status(refobjinter.get_status(self._refobj))
else:
self.set_taskfileinfo(None)
if setParent:
self.set_parent(None)
self.set_status(None)
root.update_refobj(old, refobj, self)
self.fetch_uptodate()
|
[
"def",
"set_refobj",
"(",
"self",
",",
"refobj",
",",
"setParent",
"=",
"True",
")",
":",
"root",
"=",
"self",
".",
"get_root",
"(",
")",
"old",
"=",
"self",
".",
"_refobj",
"self",
".",
"_refobj",
"=",
"refobj",
"refobjinter",
"=",
"self",
".",
"get_refobjinter",
"(",
")",
"if",
"self",
".",
"_refobj",
":",
"self",
".",
"set_typ",
"(",
"refobjinter",
".",
"get_typ",
"(",
"self",
".",
"_refobj",
")",
")",
"self",
".",
"set_taskfileinfo",
"(",
"refobjinter",
".",
"get_taskfileinfo",
"(",
"self",
".",
"_refobj",
")",
")",
"self",
".",
"set_element",
"(",
"refobjinter",
".",
"get_element",
"(",
"self",
".",
"_refobj",
")",
")",
"if",
"setParent",
":",
"parentrefobj",
"=",
"refobjinter",
".",
"get_parent",
"(",
"self",
".",
"_refobj",
")",
"parentreftrack",
"=",
"root",
".",
"get_reftrack",
"(",
"parentrefobj",
")",
"self",
".",
"set_parent",
"(",
"parentreftrack",
")",
"self",
".",
"set_status",
"(",
"refobjinter",
".",
"get_status",
"(",
"self",
".",
"_refobj",
")",
")",
"else",
":",
"self",
".",
"set_taskfileinfo",
"(",
"None",
")",
"if",
"setParent",
":",
"self",
".",
"set_parent",
"(",
"None",
")",
"self",
".",
"set_status",
"(",
"None",
")",
"root",
".",
"update_refobj",
"(",
"old",
",",
"refobj",
",",
"self",
")",
"self",
".",
"fetch_uptodate",
"(",
")"
] |
Set the reftrack object.
The reftrack object interface will determine typ, element, taskfileinfo, status and parent and set these values.
If the reftrack object is None, the :class:`Reftrack` object will keep the initial typ,
element but will loose it\'s parent, status and taskfileinfo
:param refobj: a reftrack object or None
:type refobj: None | reftrack object
:param setParent: If True, set also the parent
:type setParent: :class:`bool`
:returns: None
:rtype: None
:raises: None
|
[
"Set",
"the",
"reftrack",
"object",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L627-L661
|
238,092
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
Reftrack.set_typ
|
def set_typ(self, typ):
"""Set the type of the entity
Make sure the type is registered in the :class:`RefobjInterface`.
:param typ: the type of the entity
:type typ: str
:returns: None
:rtype: None
:raises: ValueError
"""
if typ not in self._refobjinter.types:
raise ValueError("The given typ is not supported by RefobjInterface. Given %s, supported: %s" %
(typ, self._refobjinter.types.keys()))
self._typ = typ
self._typicon = self.get_refobjinter().get_typ_icon(typ)
|
python
|
def set_typ(self, typ):
"""Set the type of the entity
Make sure the type is registered in the :class:`RefobjInterface`.
:param typ: the type of the entity
:type typ: str
:returns: None
:rtype: None
:raises: ValueError
"""
if typ not in self._refobjinter.types:
raise ValueError("The given typ is not supported by RefobjInterface. Given %s, supported: %s" %
(typ, self._refobjinter.types.keys()))
self._typ = typ
self._typicon = self.get_refobjinter().get_typ_icon(typ)
|
[
"def",
"set_typ",
"(",
"self",
",",
"typ",
")",
":",
"if",
"typ",
"not",
"in",
"self",
".",
"_refobjinter",
".",
"types",
":",
"raise",
"ValueError",
"(",
"\"The given typ is not supported by RefobjInterface. Given %s, supported: %s\"",
"%",
"(",
"typ",
",",
"self",
".",
"_refobjinter",
".",
"types",
".",
"keys",
"(",
")",
")",
")",
"self",
".",
"_typ",
"=",
"typ",
"self",
".",
"_typicon",
"=",
"self",
".",
"get_refobjinter",
"(",
")",
".",
"get_typ_icon",
"(",
"typ",
")"
] |
Set the type of the entity
Make sure the type is registered in the :class:`RefobjInterface`.
:param typ: the type of the entity
:type typ: str
:returns: None
:rtype: None
:raises: ValueError
|
[
"Set",
"the",
"type",
"of",
"the",
"entity"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L675-L690
|
238,093
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
Reftrack.set_parent
|
def set_parent(self, parent):
"""Set the parent reftrack object
If a parent gets deleted, the children will be deleted too.
.. Note:: Once the parent is set, it cannot be set again!
:param parent: the parent reftrack object
:type parent: :class:`Reftrack` | None
:returns: None
:rtype: None
:raises: AssertionError
"""
assert self._parent is None or self._parent is parent,\
"Cannot change the parent. Can only set from None."
if parent and self._parent is parent:
return
self._parent = parent
if parent:
refobjinter = self.get_refobjinter()
refobj = self.get_refobj()
# set the parent of the refobj only if it is not already set
# and only if there is one! oO
if refobj and not refobjinter.get_parent(refobj):
refobjinter.set_parent(refobj, parent.get_refobj())
# add to parent
self._parent.add_child(self)
if not self.get_refobj():
self.set_id(self.fetch_new_id())
pitem = self._parent._treeitem if self._parent else self.get_root().get_rootitem()
self._treeitem.set_parent(pitem)
self.fetch_alien()
|
python
|
def set_parent(self, parent):
"""Set the parent reftrack object
If a parent gets deleted, the children will be deleted too.
.. Note:: Once the parent is set, it cannot be set again!
:param parent: the parent reftrack object
:type parent: :class:`Reftrack` | None
:returns: None
:rtype: None
:raises: AssertionError
"""
assert self._parent is None or self._parent is parent,\
"Cannot change the parent. Can only set from None."
if parent and self._parent is parent:
return
self._parent = parent
if parent:
refobjinter = self.get_refobjinter()
refobj = self.get_refobj()
# set the parent of the refobj only if it is not already set
# and only if there is one! oO
if refobj and not refobjinter.get_parent(refobj):
refobjinter.set_parent(refobj, parent.get_refobj())
# add to parent
self._parent.add_child(self)
if not self.get_refobj():
self.set_id(self.fetch_new_id())
pitem = self._parent._treeitem if self._parent else self.get_root().get_rootitem()
self._treeitem.set_parent(pitem)
self.fetch_alien()
|
[
"def",
"set_parent",
"(",
"self",
",",
"parent",
")",
":",
"assert",
"self",
".",
"_parent",
"is",
"None",
"or",
"self",
".",
"_parent",
"is",
"parent",
",",
"\"Cannot change the parent. Can only set from None.\"",
"if",
"parent",
"and",
"self",
".",
"_parent",
"is",
"parent",
":",
"return",
"self",
".",
"_parent",
"=",
"parent",
"if",
"parent",
":",
"refobjinter",
"=",
"self",
".",
"get_refobjinter",
"(",
")",
"refobj",
"=",
"self",
".",
"get_refobj",
"(",
")",
"# set the parent of the refobj only if it is not already set",
"# and only if there is one! oO",
"if",
"refobj",
"and",
"not",
"refobjinter",
".",
"get_parent",
"(",
"refobj",
")",
":",
"refobjinter",
".",
"set_parent",
"(",
"refobj",
",",
"parent",
".",
"get_refobj",
"(",
")",
")",
"# add to parent",
"self",
".",
"_parent",
".",
"add_child",
"(",
"self",
")",
"if",
"not",
"self",
".",
"get_refobj",
"(",
")",
":",
"self",
".",
"set_id",
"(",
"self",
".",
"fetch_new_id",
"(",
")",
")",
"pitem",
"=",
"self",
".",
"_parent",
".",
"_treeitem",
"if",
"self",
".",
"_parent",
"else",
"self",
".",
"get_root",
"(",
")",
".",
"get_rootitem",
"(",
")",
"self",
".",
"_treeitem",
".",
"set_parent",
"(",
"pitem",
")",
"self",
".",
"fetch_alien",
"(",
")"
] |
Set the parent reftrack object
If a parent gets deleted, the children will be deleted too.
.. Note:: Once the parent is set, it cannot be set again!
:param parent: the parent reftrack object
:type parent: :class:`Reftrack` | None
:returns: None
:rtype: None
:raises: AssertionError
|
[
"Set",
"the",
"parent",
"reftrack",
"object"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L782-L814
|
238,094
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
Reftrack.set_id
|
def set_id(self, identifier):
"""Set the id of the given reftrack
This will set the id on the refobject
:param identifier: the identifier number
:type identifier: int
:returns: None
:rtype: None
:raises: None
"""
self._id = identifier
refobj = self.get_refobj()
if refobj:
self.get_refobjinter().set_id(refobj, identifier)
|
python
|
def set_id(self, identifier):
"""Set the id of the given reftrack
This will set the id on the refobject
:param identifier: the identifier number
:type identifier: int
:returns: None
:rtype: None
:raises: None
"""
self._id = identifier
refobj = self.get_refobj()
if refobj:
self.get_refobjinter().set_id(refobj, identifier)
|
[
"def",
"set_id",
"(",
"self",
",",
"identifier",
")",
":",
"self",
".",
"_id",
"=",
"identifier",
"refobj",
"=",
"self",
".",
"get_refobj",
"(",
")",
"if",
"refobj",
":",
"self",
".",
"get_refobjinter",
"(",
")",
".",
"set_id",
"(",
"refobj",
",",
"identifier",
")"
] |
Set the id of the given reftrack
This will set the id on the refobject
:param identifier: the identifier number
:type identifier: int
:returns: None
:rtype: None
:raises: None
|
[
"Set",
"the",
"id",
"of",
"the",
"given",
"reftrack"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L829-L843
|
238,095
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
Reftrack.fetch_new_id
|
def fetch_new_id(self, ):
"""Return a new id for the given reftrack to be set on the refobject
The id can identify reftracks that share the same parent, type and element.
:returns: A new id
:rtype: int
:raises: None
"""
parent = self.get_parent()
if parent:
others = parent._children
else:
others = [r for r in self.get_root()._reftracks if r.get_parent() is None]
others = [r for r in others
if r != self
and r.get_typ() == self.get_typ()
and r.get_element() == self.get_element()]
highest = -1
for r in others:
identifier = r.get_id()
if identifier > highest:
highest = identifier
return highest + 1
|
python
|
def fetch_new_id(self, ):
"""Return a new id for the given reftrack to be set on the refobject
The id can identify reftracks that share the same parent, type and element.
:returns: A new id
:rtype: int
:raises: None
"""
parent = self.get_parent()
if parent:
others = parent._children
else:
others = [r for r in self.get_root()._reftracks if r.get_parent() is None]
others = [r for r in others
if r != self
and r.get_typ() == self.get_typ()
and r.get_element() == self.get_element()]
highest = -1
for r in others:
identifier = r.get_id()
if identifier > highest:
highest = identifier
return highest + 1
|
[
"def",
"fetch_new_id",
"(",
"self",
",",
")",
":",
"parent",
"=",
"self",
".",
"get_parent",
"(",
")",
"if",
"parent",
":",
"others",
"=",
"parent",
".",
"_children",
"else",
":",
"others",
"=",
"[",
"r",
"for",
"r",
"in",
"self",
".",
"get_root",
"(",
")",
".",
"_reftracks",
"if",
"r",
".",
"get_parent",
"(",
")",
"is",
"None",
"]",
"others",
"=",
"[",
"r",
"for",
"r",
"in",
"others",
"if",
"r",
"!=",
"self",
"and",
"r",
".",
"get_typ",
"(",
")",
"==",
"self",
".",
"get_typ",
"(",
")",
"and",
"r",
".",
"get_element",
"(",
")",
"==",
"self",
".",
"get_element",
"(",
")",
"]",
"highest",
"=",
"-",
"1",
"for",
"r",
"in",
"others",
":",
"identifier",
"=",
"r",
".",
"get_id",
"(",
")",
"if",
"identifier",
">",
"highest",
":",
"highest",
"=",
"identifier",
"return",
"highest",
"+",
"1"
] |
Return a new id for the given reftrack to be set on the refobject
The id can identify reftracks that share the same parent, type and element.
:returns: A new id
:rtype: int
:raises: None
|
[
"Return",
"a",
"new",
"id",
"for",
"the",
"given",
"reftrack",
"to",
"be",
"set",
"on",
"the",
"refobject"
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L845-L868
|
238,096
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
Reftrack.create_treeitem
|
def create_treeitem(self, ):
"""Create a new treeitem for this reftrack instance.
.. Note:: Parent should be set, Parent should already have a treeitem.
If there is no parent, the root tree item is used as parent for the treeitem.
:returns: a new treeitem that contains a itemdata with the reftrack instanec.
:rtype: :class:`TreeItem`
:raises: None
"""
p = self.get_parent()
root = self.get_root()
if p:
pitem = p.get_treeitem()
else:
pitem = root.get_rootitem()
idata = root.create_itemdata(self)
item = TreeItem(idata, parent=pitem)
return item
|
python
|
def create_treeitem(self, ):
"""Create a new treeitem for this reftrack instance.
.. Note:: Parent should be set, Parent should already have a treeitem.
If there is no parent, the root tree item is used as parent for the treeitem.
:returns: a new treeitem that contains a itemdata with the reftrack instanec.
:rtype: :class:`TreeItem`
:raises: None
"""
p = self.get_parent()
root = self.get_root()
if p:
pitem = p.get_treeitem()
else:
pitem = root.get_rootitem()
idata = root.create_itemdata(self)
item = TreeItem(idata, parent=pitem)
return item
|
[
"def",
"create_treeitem",
"(",
"self",
",",
")",
":",
"p",
"=",
"self",
".",
"get_parent",
"(",
")",
"root",
"=",
"self",
".",
"get_root",
"(",
")",
"if",
"p",
":",
"pitem",
"=",
"p",
".",
"get_treeitem",
"(",
")",
"else",
":",
"pitem",
"=",
"root",
".",
"get_rootitem",
"(",
")",
"idata",
"=",
"root",
".",
"create_itemdata",
"(",
"self",
")",
"item",
"=",
"TreeItem",
"(",
"idata",
",",
"parent",
"=",
"pitem",
")",
"return",
"item"
] |
Create a new treeitem for this reftrack instance.
.. Note:: Parent should be set, Parent should already have a treeitem.
If there is no parent, the root tree item is used as parent for the treeitem.
:returns: a new treeitem that contains a itemdata with the reftrack instanec.
:rtype: :class:`TreeItem`
:raises: None
|
[
"Create",
"a",
"new",
"treeitem",
"for",
"this",
"reftrack",
"instance",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L870-L888
|
238,097
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
Reftrack.fetch_options
|
def fetch_options(self, ):
"""Set and return the options for possible files to
load, replace etc. The stored element will determine the options.
The refobjinterface and typinterface are responsible for providing the options
:returns: the options
:rtype: :class:`jukeboxcore.gui.treemodel.TreeModel`
:raises: None
"""
self._options, self._taskfileinfo_options = self.get_refobjinter().fetch_options(self.get_typ(), self.get_element())
return self._options
|
python
|
def fetch_options(self, ):
"""Set and return the options for possible files to
load, replace etc. The stored element will determine the options.
The refobjinterface and typinterface are responsible for providing the options
:returns: the options
:rtype: :class:`jukeboxcore.gui.treemodel.TreeModel`
:raises: None
"""
self._options, self._taskfileinfo_options = self.get_refobjinter().fetch_options(self.get_typ(), self.get_element())
return self._options
|
[
"def",
"fetch_options",
"(",
"self",
",",
")",
":",
"self",
".",
"_options",
",",
"self",
".",
"_taskfileinfo_options",
"=",
"self",
".",
"get_refobjinter",
"(",
")",
".",
"fetch_options",
"(",
"self",
".",
"get_typ",
"(",
")",
",",
"self",
".",
"get_element",
"(",
")",
")",
"return",
"self",
".",
"_options"
] |
Set and return the options for possible files to
load, replace etc. The stored element will determine the options.
The refobjinterface and typinterface are responsible for providing the options
:returns: the options
:rtype: :class:`jukeboxcore.gui.treemodel.TreeModel`
:raises: None
|
[
"Set",
"and",
"return",
"the",
"options",
"for",
"possible",
"files",
"to",
"load",
"replace",
"etc",
".",
"The",
"stored",
"element",
"will",
"determine",
"the",
"options",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L946-L957
|
238,098
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
Reftrack.fetch_uptodate
|
def fetch_uptodate(self, ):
"""Set and return whether the currently loaded entity is
the newest version in the department.
:returns: True, if newest version. False, if there is a newer version.
None, if there is nothing loaded yet.
:rtype: bool | None
:raises: None
"""
tfi = self.get_taskfileinfo()
if tfi:
self._uptodate = tfi.is_latest()
else:
self._uptodate = None
return self._uptodate
|
python
|
def fetch_uptodate(self, ):
"""Set and return whether the currently loaded entity is
the newest version in the department.
:returns: True, if newest version. False, if there is a newer version.
None, if there is nothing loaded yet.
:rtype: bool | None
:raises: None
"""
tfi = self.get_taskfileinfo()
if tfi:
self._uptodate = tfi.is_latest()
else:
self._uptodate = None
return self._uptodate
|
[
"def",
"fetch_uptodate",
"(",
"self",
",",
")",
":",
"tfi",
"=",
"self",
".",
"get_taskfileinfo",
"(",
")",
"if",
"tfi",
":",
"self",
".",
"_uptodate",
"=",
"tfi",
".",
"is_latest",
"(",
")",
"else",
":",
"self",
".",
"_uptodate",
"=",
"None",
"return",
"self",
".",
"_uptodate"
] |
Set and return whether the currently loaded entity is
the newest version in the department.
:returns: True, if newest version. False, if there is a newer version.
None, if there is nothing loaded yet.
:rtype: bool | None
:raises: None
|
[
"Set",
"and",
"return",
"whether",
"the",
"currently",
"loaded",
"entity",
"is",
"the",
"newest",
"version",
"in",
"the",
"department",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1008-L1022
|
238,099
|
JukeboxPipeline/jukebox-core
|
src/jukeboxcore/reftrack.py
|
Reftrack.fetch_alien
|
def fetch_alien(self, ):
"""Set and return, if the reftrack element is linked to the current scene.
Askes the refobj interface for the current scene.
If there is no current scene then True is returned.
:returns: whether the element is linked to the current scene
:rtype: bool
:raises: None
"""
parent = self.get_parent()
if parent:
parentelement = parent.get_element()
else:
parentelement = self.get_refobjinter().get_current_element()
if not parentelement:
self._alien = True
return self._alien
element = self.get_element()
if element == parentelement:
self._alien = False
# test if it is the element is a global shot
# first test if we have a shot
# then test if it is in a global sequence. then the shot is global too.
# test if the parent element is a shot, if they share the sequence, and element is global
elif isinstance(element, djadapter.models.Shot)\
and (element.sequence.name == djadapter.GLOBAL_NAME\
or (isinstance(parentelement, djadapter.models.Shot)\
and parentelement.sequence == element.sequence and element.name == djadapter.GLOBAL_NAME)):
self._alien = False
else:
assets = parentelement.assets.all()
self._alien = element not in assets
return self._alien
|
python
|
def fetch_alien(self, ):
"""Set and return, if the reftrack element is linked to the current scene.
Askes the refobj interface for the current scene.
If there is no current scene then True is returned.
:returns: whether the element is linked to the current scene
:rtype: bool
:raises: None
"""
parent = self.get_parent()
if parent:
parentelement = parent.get_element()
else:
parentelement = self.get_refobjinter().get_current_element()
if not parentelement:
self._alien = True
return self._alien
element = self.get_element()
if element == parentelement:
self._alien = False
# test if it is the element is a global shot
# first test if we have a shot
# then test if it is in a global sequence. then the shot is global too.
# test if the parent element is a shot, if they share the sequence, and element is global
elif isinstance(element, djadapter.models.Shot)\
and (element.sequence.name == djadapter.GLOBAL_NAME\
or (isinstance(parentelement, djadapter.models.Shot)\
and parentelement.sequence == element.sequence and element.name == djadapter.GLOBAL_NAME)):
self._alien = False
else:
assets = parentelement.assets.all()
self._alien = element not in assets
return self._alien
|
[
"def",
"fetch_alien",
"(",
"self",
",",
")",
":",
"parent",
"=",
"self",
".",
"get_parent",
"(",
")",
"if",
"parent",
":",
"parentelement",
"=",
"parent",
".",
"get_element",
"(",
")",
"else",
":",
"parentelement",
"=",
"self",
".",
"get_refobjinter",
"(",
")",
".",
"get_current_element",
"(",
")",
"if",
"not",
"parentelement",
":",
"self",
".",
"_alien",
"=",
"True",
"return",
"self",
".",
"_alien",
"element",
"=",
"self",
".",
"get_element",
"(",
")",
"if",
"element",
"==",
"parentelement",
":",
"self",
".",
"_alien",
"=",
"False",
"# test if it is the element is a global shot",
"# first test if we have a shot",
"# then test if it is in a global sequence. then the shot is global too.",
"# test if the parent element is a shot, if they share the sequence, and element is global",
"elif",
"isinstance",
"(",
"element",
",",
"djadapter",
".",
"models",
".",
"Shot",
")",
"and",
"(",
"element",
".",
"sequence",
".",
"name",
"==",
"djadapter",
".",
"GLOBAL_NAME",
"or",
"(",
"isinstance",
"(",
"parentelement",
",",
"djadapter",
".",
"models",
".",
"Shot",
")",
"and",
"parentelement",
".",
"sequence",
"==",
"element",
".",
"sequence",
"and",
"element",
".",
"name",
"==",
"djadapter",
".",
"GLOBAL_NAME",
")",
")",
":",
"self",
".",
"_alien",
"=",
"False",
"else",
":",
"assets",
"=",
"parentelement",
".",
"assets",
".",
"all",
"(",
")",
"self",
".",
"_alien",
"=",
"element",
"not",
"in",
"assets",
"return",
"self",
".",
"_alien"
] |
Set and return, if the reftrack element is linked to the current scene.
Askes the refobj interface for the current scene.
If there is no current scene then True is returned.
:returns: whether the element is linked to the current scene
:rtype: bool
:raises: None
|
[
"Set",
"and",
"return",
"if",
"the",
"reftrack",
"element",
"is",
"linked",
"to",
"the",
"current",
"scene",
"."
] |
bac2280ca49940355270e4b69400ce9976ab2e6f
|
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/reftrack.py#L1033-L1066
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.