repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
selenol/selenol-python | selenol_python/params.py | get_value_from_content | def get_value_from_content(key):
"""Get a value from the path specifed.
:param key: Array that defines the path of the value inside the message.
"""
def value_from_content_function(service, message):
"""Actual implementation of get_value_from_content function.
:param service: SelenolSe... | python | def get_value_from_content(key):
"""Get a value from the path specifed.
:param key: Array that defines the path of the value inside the message.
"""
def value_from_content_function(service, message):
"""Actual implementation of get_value_from_content function.
:param service: SelenolSe... | [
"def",
"get_value_from_content",
"(",
"key",
")",
":",
"def",
"value_from_content_function",
"(",
"service",
",",
"message",
")",
":",
"\"\"\"Actual implementation of get_value_from_content function.\n\n :param service: SelenolService object.\n :param message: SelenolMessag... | Get a value from the path specifed.
:param key: Array that defines the path of the value inside the message. | [
"Get",
"a",
"value",
"from",
"the",
"path",
"specifed",
"."
] | train | https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L69-L81 |
selenol/selenol-python | selenol_python/params.py | get_object_from_content | def get_object_from_content(entity, key):
"""Get an object from the database given an entity and the content key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message.
"""
def object_from_content_function(service, message):
... | python | def get_object_from_content(entity, key):
"""Get an object from the database given an entity and the content key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message.
"""
def object_from_content_function(service, message):
... | [
"def",
"get_object_from_content",
"(",
"entity",
",",
"key",
")",
":",
"def",
"object_from_content_function",
"(",
"service",
",",
"message",
")",
":",
"\"\"\"Actual implementation of get_object_from_content function.\n\n :param service: SelenolService object.\n :param ... | Get an object from the database given an entity and the content key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message. | [
"Get",
"an",
"object",
"from",
"the",
"database",
"given",
"an",
"entity",
"and",
"the",
"content",
"key",
"."
] | train | https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L84-L101 |
selenol/selenol-python | selenol_python/params.py | get_object_from_session | def get_object_from_session(entity, key):
"""Get an object from the database given an entity and the session key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message.
"""
def object_from_session_function(service, message):
... | python | def get_object_from_session(entity, key):
"""Get an object from the database given an entity and the session key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message.
"""
def object_from_session_function(service, message):
... | [
"def",
"get_object_from_session",
"(",
"entity",
",",
"key",
")",
":",
"def",
"object_from_session_function",
"(",
"service",
",",
"message",
")",
":",
"\"\"\"Actual implementation of get_object_from_session function.\n\n :param service: SelenolService object.\n :param ... | Get an object from the database given an entity and the session key.
:param entity: Class type of the object to retrieve.
:param key: Array that defines the path of the value inside the message. | [
"Get",
"an",
"object",
"from",
"the",
"database",
"given",
"an",
"entity",
"and",
"the",
"session",
"key",
"."
] | train | https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/params.py#L104-L121 |
CitrineInformatics/dftparse | dftparse/pwscf/stdout_parser.py | _parse_forces | def _parse_forces(line, lines):
"""Parse the forces block, including individual terms (e.g. Hubbard)"""
units = line.split()[4].rstrip(":")
next(lines)
newline = next(lines)
total = []; non_local = []; ionic = []; local = []; core_correction = []
hubbard = []; scf = []; types = []
while (not... | python | def _parse_forces(line, lines):
"""Parse the forces block, including individual terms (e.g. Hubbard)"""
units = line.split()[4].rstrip(":")
next(lines)
newline = next(lines)
total = []; non_local = []; ionic = []; local = []; core_correction = []
hubbard = []; scf = []; types = []
while (not... | [
"def",
"_parse_forces",
"(",
"line",
",",
"lines",
")",
":",
"units",
"=",
"line",
".",
"split",
"(",
")",
"[",
"4",
"]",
".",
"rstrip",
"(",
"\":\"",
")",
"next",
"(",
"lines",
")",
"newline",
"=",
"next",
"(",
"lines",
")",
"total",
"=",
"[",
... | Parse the forces block, including individual terms (e.g. Hubbard) | [
"Parse",
"the",
"forces",
"block",
"including",
"individual",
"terms",
"(",
"e",
".",
"g",
".",
"Hubbard",
")"
] | train | https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/pwscf/stdout_parser.py#L92-L145 |
uw-it-aca/uw-restclients-grad | uw_grad/petition.py | _process_json | def _process_json(data):
"""
return a list of GradPetition objects.
"""
requests = []
for item in data:
petition = GradPetition()
petition.description = item.get('description')
petition.submit_date = parse_datetime(item.get('submitDate'))
petition.decision_date = pars... | python | def _process_json(data):
"""
return a list of GradPetition objects.
"""
requests = []
for item in data:
petition = GradPetition()
petition.description = item.get('description')
petition.submit_date = parse_datetime(item.get('submitDate'))
petition.decision_date = pars... | [
"def",
"_process_json",
"(",
"data",
")",
":",
"requests",
"=",
"[",
"]",
"for",
"item",
"in",
"data",
":",
"petition",
"=",
"GradPetition",
"(",
")",
"petition",
".",
"description",
"=",
"item",
".",
"get",
"(",
"'description'",
")",
"petition",
".",
... | return a list of GradPetition objects. | [
"return",
"a",
"list",
"of",
"GradPetition",
"objects",
"."
] | train | https://github.com/uw-it-aca/uw-restclients-grad/blob/ca06ed2f24f3683314a5690f6078e97d37fc8e52/uw_grad/petition.py#L20-L39 |
jhazelwo/python-fileasobj | docs/examples.py | example_add_line_to_file | def example_add_line_to_file():
""" Different methods to append a given line to the file, all work the same. """
my_file = FileAsObj('/tmp/example_file.txt')
my_file.add('foo')
my_file.append('bar')
# Add a new line to my_file that contains the word 'lol' and print True|False if my_file was changed.... | python | def example_add_line_to_file():
""" Different methods to append a given line to the file, all work the same. """
my_file = FileAsObj('/tmp/example_file.txt')
my_file.add('foo')
my_file.append('bar')
# Add a new line to my_file that contains the word 'lol' and print True|False if my_file was changed.... | [
"def",
"example_add_line_to_file",
"(",
")",
":",
"my_file",
"=",
"FileAsObj",
"(",
"'/tmp/example_file.txt'",
")",
"my_file",
".",
"add",
"(",
"'foo'",
")",
"my_file",
".",
"append",
"(",
"'bar'",
")",
"# Add a new line to my_file that contains the word 'lol' and print... | Different methods to append a given line to the file, all work the same. | [
"Different",
"methods",
"to",
"append",
"a",
"given",
"line",
"to",
"the",
"file",
"all",
"work",
"the",
"same",
"."
] | train | https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/docs/examples.py#L63-L72 |
jhazelwo/python-fileasobj | docs/examples.py | example_write_file_to_disk_if_changed | def example_write_file_to_disk_if_changed():
""" Try to remove all comments from a file, and save it if changes were made. """
my_file = FileAsObj('/tmp/example_file.txt')
my_file.rm(my_file.egrep('^#'))
if my_file.changed:
my_file.save() | python | def example_write_file_to_disk_if_changed():
""" Try to remove all comments from a file, and save it if changes were made. """
my_file = FileAsObj('/tmp/example_file.txt')
my_file.rm(my_file.egrep('^#'))
if my_file.changed:
my_file.save() | [
"def",
"example_write_file_to_disk_if_changed",
"(",
")",
":",
"my_file",
"=",
"FileAsObj",
"(",
"'/tmp/example_file.txt'",
")",
"my_file",
".",
"rm",
"(",
"my_file",
".",
"egrep",
"(",
"'^#'",
")",
")",
"if",
"my_file",
".",
"changed",
":",
"my_file",
".",
... | Try to remove all comments from a file, and save it if changes were made. | [
"Try",
"to",
"remove",
"all",
"comments",
"from",
"a",
"file",
"and",
"save",
"it",
"if",
"changes",
"were",
"made",
"."
] | train | https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/docs/examples.py#L132-L137 |
jhazelwo/python-fileasobj | docs/examples.py | example_all | def example_all():
"""
Use a bunch of methods on a file.
"""
my_file = FileAsObj()
my_file.filename = '/tmp/example_file.txt'
my_file.add('# First change!')
my_file.save()
my_file = FileAsObj('/tmp/example_file.txt')
my_file.unique = True
my_file.sorted = True
my_file.add('1'... | python | def example_all():
"""
Use a bunch of methods on a file.
"""
my_file = FileAsObj()
my_file.filename = '/tmp/example_file.txt'
my_file.add('# First change!')
my_file.save()
my_file = FileAsObj('/tmp/example_file.txt')
my_file.unique = True
my_file.sorted = True
my_file.add('1'... | [
"def",
"example_all",
"(",
")",
":",
"my_file",
"=",
"FileAsObj",
"(",
")",
"my_file",
".",
"filename",
"=",
"'/tmp/example_file.txt'",
"my_file",
".",
"add",
"(",
"'# First change!'",
")",
"my_file",
".",
"save",
"(",
")",
"my_file",
"=",
"FileAsObj",
"(",
... | Use a bunch of methods on a file. | [
"Use",
"a",
"bunch",
"of",
"methods",
"on",
"a",
"file",
"."
] | train | https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/docs/examples.py#L173-L198 |
ryanjdillon/pylleo | pylleo/lleocal.py | get_cal_data | def get_cal_data(data_df, cal_dict, param):
'''Get data along specified axis during calibration intervals
Args
----
data_df: pandas.DataFrame
Pandas dataframe with lleo data
cal_dict: dict
Calibration dictionary
Returns
-------
lower: pandas dataframe
slice of l... | python | def get_cal_data(data_df, cal_dict, param):
'''Get data along specified axis during calibration intervals
Args
----
data_df: pandas.DataFrame
Pandas dataframe with lleo data
cal_dict: dict
Calibration dictionary
Returns
-------
lower: pandas dataframe
slice of l... | [
"def",
"get_cal_data",
"(",
"data_df",
",",
"cal_dict",
",",
"param",
")",
":",
"param",
"=",
"param",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"idx_lower_start",
"=",
"cal_dict... | Get data along specified axis during calibration intervals
Args
----
data_df: pandas.DataFrame
Pandas dataframe with lleo data
cal_dict: dict
Calibration dictionary
Returns
-------
lower: pandas dataframe
slice of lleo datafram containing points at -1g calibration p... | [
"Get",
"data",
"along",
"specified",
"axis",
"during",
"calibration",
"intervals"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/lleocal.py#L2-L38 |
ryanjdillon/pylleo | pylleo/lleocal.py | read_cal | def read_cal(cal_yaml_path):
'''Load calibration file if exists, else create
Args
----
cal_yaml_path: str
Path to calibration YAML file
Returns
-------
cal_dict: dict
Key value pairs of calibration meta data
'''
from collections import OrderedDict
import datetim... | python | def read_cal(cal_yaml_path):
'''Load calibration file if exists, else create
Args
----
cal_yaml_path: str
Path to calibration YAML file
Returns
-------
cal_dict: dict
Key value pairs of calibration meta data
'''
from collections import OrderedDict
import datetim... | [
"def",
"read_cal",
"(",
"cal_yaml_path",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"import",
"datetime",
"import",
"os",
"import",
"warnings",
"import",
"yamlord",
"from",
".",
"import",
"utils",
"def",
"__create_cal",
"(",
"cal_yaml_path",
")",
... | Load calibration file if exists, else create
Args
----
cal_yaml_path: str
Path to calibration YAML file
Returns
-------
cal_dict: dict
Key value pairs of calibration meta data | [
"Load",
"calibration",
"file",
"if",
"exists",
"else",
"create"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/lleocal.py#L41-L85 |
ryanjdillon/pylleo | pylleo/lleocal.py | update | def update(data_df, cal_dict, param, bound, start, end):
'''Update calibration times for give parameter and boundary'''
from collections import OrderedDict
if param not in cal_dict['parameters']:
cal_dict['parameters'][param] = OrderedDict()
if bound not in cal_dict['parameters'][param]:
... | python | def update(data_df, cal_dict, param, bound, start, end):
'''Update calibration times for give parameter and boundary'''
from collections import OrderedDict
if param not in cal_dict['parameters']:
cal_dict['parameters'][param] = OrderedDict()
if bound not in cal_dict['parameters'][param]:
... | [
"def",
"update",
"(",
"data_df",
",",
"cal_dict",
",",
"param",
",",
"bound",
",",
"start",
",",
"end",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"if",
"param",
"not",
"in",
"cal_dict",
"[",
"'parameters'",
"]",
":",
"cal_dict",
"[",
"'pa... | Update calibration times for give parameter and boundary | [
"Update",
"calibration",
"times",
"for",
"give",
"parameter",
"and",
"boundary"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/lleocal.py#L88-L100 |
ryanjdillon/pylleo | pylleo/lleocal.py | fit1d | def fit1d(lower, upper):
'''Fit acceleration data at lower and upper boundaries of gravity
Args
----
lower: pandas dataframe
slice of lleo datafram containing points at -1g calibration position
upper: pandas dataframe
slice of lleo datafram containing points at -1g calibration posit... | python | def fit1d(lower, upper):
'''Fit acceleration data at lower and upper boundaries of gravity
Args
----
lower: pandas dataframe
slice of lleo datafram containing points at -1g calibration position
upper: pandas dataframe
slice of lleo datafram containing points at -1g calibration posit... | [
"def",
"fit1d",
"(",
"lower",
",",
"upper",
")",
":",
"import",
"numpy",
"# Get smallest size as index position for slicing",
"idx",
"=",
"min",
"(",
"len",
"(",
"lower",
")",
",",
"len",
"(",
"upper",
")",
")",
"# Stack accelerometer count values for upper and lowe... | Fit acceleration data at lower and upper boundaries of gravity
Args
----
lower: pandas dataframe
slice of lleo datafram containing points at -1g calibration position
upper: pandas dataframe
slice of lleo datafram containing points at -1g calibration position
Returns
-------
... | [
"Fit",
"acceleration",
"data",
"at",
"lower",
"and",
"upper",
"boundaries",
"of",
"gravity"
] | train | https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/lleocal.py#L103-L143 |
robertchase/ergaleia | ergaleia/un_comment.py | un_comment | def un_comment(s, comment='#', strip=True):
"""Uncomment a string or list of strings
truncate s at first occurrence of a non-escaped comment character
remove escapes from escaped comment characters
Parameters:
s - string to uncomment
comment - comment character (de... | python | def un_comment(s, comment='#', strip=True):
"""Uncomment a string or list of strings
truncate s at first occurrence of a non-escaped comment character
remove escapes from escaped comment characters
Parameters:
s - string to uncomment
comment - comment character (de... | [
"def",
"un_comment",
"(",
"s",
",",
"comment",
"=",
"'#'",
",",
"strip",
"=",
"True",
")",
":",
"def",
"_un_comment",
"(",
"string",
")",
":",
"result",
"=",
"re",
".",
"split",
"(",
"r'(?<!\\\\)'",
"+",
"comment",
",",
"string",
",",
"maxsplit",
"="... | Uncomment a string or list of strings
truncate s at first occurrence of a non-escaped comment character
remove escapes from escaped comment characters
Parameters:
s - string to uncomment
comment - comment character (default=#) (see Note 1)
strip - strip li... | [
"Uncomment",
"a",
"string",
"or",
"list",
"of",
"strings"
] | train | https://github.com/robertchase/ergaleia/blob/df8e9a4b18c563022a503faa27e822c9a5755490/ergaleia/un_comment.py#L9-L36 |
clearclaw/logtool | versioneer.py | render_pep440_bare | def render_pep440_bare(pieces):
"""TAG[.DISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.DISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".%d" % pieces["distan... | python | def render_pep440_bare(pieces):
"""TAG[.DISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.DISTANCE[.dev0]
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".%d" % pieces["distan... | [
"def",
"render_pep440_bare",
"(",
"pieces",
")",
":",
"if",
"pieces",
"[",
"\"closest-tag\"",
"]",
":",
"rendered",
"=",
"pieces",
"[",
"\"closest-tag\"",
"]",
"if",
"pieces",
"[",
"\"distance\"",
"]",
"or",
"pieces",
"[",
"\"dirty\"",
"]",
":",
"rendered",
... | TAG[.DISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.DISTANCE[.dev0] | [
"TAG",
"[",
".",
"DISTANCE",
"[",
".",
"dev0",
"]]",
"."
] | train | https://github.com/clearclaw/logtool/blob/e34c9a580538a9a14fec9b4bbab8b8df92ad36e7/versioneer.py#L1343-L1362 |
shaypal5/comath | comath/func/func.py | get_smooth_step_function | def get_smooth_step_function(min_val, max_val, switch_point, smooth_factor):
"""Returns a function that moves smoothly between a minimal value and a
maximal one when its value increases from a given witch point to infinity.
Arguments
---------
min_val: float
max_val value the function will ... | python | def get_smooth_step_function(min_val, max_val, switch_point, smooth_factor):
"""Returns a function that moves smoothly between a minimal value and a
maximal one when its value increases from a given witch point to infinity.
Arguments
---------
min_val: float
max_val value the function will ... | [
"def",
"get_smooth_step_function",
"(",
"min_val",
",",
"max_val",
",",
"switch_point",
",",
"smooth_factor",
")",
":",
"dif",
"=",
"max_val",
"-",
"min_val",
"def",
"_smooth_step",
"(",
"x",
")",
":",
"return",
"min_val",
"+",
"dif",
"*",
"tanh",
"(",
"("... | Returns a function that moves smoothly between a minimal value and a
maximal one when its value increases from a given witch point to infinity.
Arguments
---------
min_val: float
max_val value the function will return when x=switch_point.
min_val: float
The value the function will c... | [
"Returns",
"a",
"function",
"that",
"moves",
"smoothly",
"between",
"a",
"minimal",
"value",
"and",
"a",
"maximal",
"one",
"when",
"its",
"value",
"increases",
"from",
"a",
"given",
"witch",
"point",
"to",
"infinity",
"."
] | train | https://github.com/shaypal5/comath/blob/1333e3b96242a5bad9d3e699ffd58a1597fdc89f/comath/func/func.py#L10-L34 |
jalanb/pysyte | pysyte/debuggers.py | stack_sources | def stack_sources():
"""A list of sources for frames above this"""
# lazy imports
import linecache
result = []
for frame_info in reversed(inspect.stack()):
_frame, filename, line_number, _function, _context, _index = frame_info
linecache.lazycache(filename, {})
_line = lineca... | python | def stack_sources():
"""A list of sources for frames above this"""
# lazy imports
import linecache
result = []
for frame_info in reversed(inspect.stack()):
_frame, filename, line_number, _function, _context, _index = frame_info
linecache.lazycache(filename, {})
_line = lineca... | [
"def",
"stack_sources",
"(",
")",
":",
"# lazy imports",
"import",
"linecache",
"result",
"=",
"[",
"]",
"for",
"frame_info",
"in",
"reversed",
"(",
"inspect",
".",
"stack",
"(",
")",
")",
":",
"_frame",
",",
"filename",
",",
"line_number",
",",
"_function... | A list of sources for frames above this | [
"A",
"list",
"of",
"sources",
"for",
"frames",
"above",
"this"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/debuggers.py#L151-L164 |
KyleWpppd/css-audit | cssaudit/parser.py | extract_leftmost_selector | def extract_leftmost_selector(selector_list):
"""
Because we aren't building a DOM tree to transverse, the only way
to get the most general selectors is to take the leftmost.
For example with `div.outer div.inner`, we can't tell if `div.inner`
has been used in context without building a tree.
"... | python | def extract_leftmost_selector(selector_list):
"""
Because we aren't building a DOM tree to transverse, the only way
to get the most general selectors is to take the leftmost.
For example with `div.outer div.inner`, we can't tell if `div.inner`
has been used in context without building a tree.
"... | [
"def",
"extract_leftmost_selector",
"(",
"selector_list",
")",
":",
"classes",
"=",
"set",
"(",
")",
"ids",
"=",
"set",
"(",
")",
"elements",
"=",
"set",
"(",
")",
"# print \"Selector list: %s \\n\\n\\n\\n\\n\\n\" % selector_list",
"for",
"selector",
"in",
"selec... | Because we aren't building a DOM tree to transverse, the only way
to get the most general selectors is to take the leftmost.
For example with `div.outer div.inner`, we can't tell if `div.inner`
has been used in context without building a tree. | [
"Because",
"we",
"aren",
"t",
"building",
"a",
"DOM",
"tree",
"to",
"transverse",
"the",
"only",
"way",
"to",
"get",
"the",
"most",
"general",
"selectors",
"is",
"to",
"take",
"the",
"leftmost",
".",
"For",
"example",
"with",
"div",
".",
"outer",
"div",
... | train | https://github.com/KyleWpppd/css-audit/blob/cab4d4204cf30d54bc1881deee6ad92ae6aacc56/cssaudit/parser.py#L213-L236 |
KyleWpppd/css-audit | cssaudit/parser.py | Cssparser.handle_starttag | def handle_starttag(self, tag, attrs):
"""
This method handles any HTML tags that have a matching
closing tag. So elements like <p> and <div> are handled
by this method.
@param <string> tag
An html tag that has a separate closing tag such as <p>
<div> or <b... | python | def handle_starttag(self, tag, attrs):
"""
This method handles any HTML tags that have a matching
closing tag. So elements like <p> and <div> are handled
by this method.
@param <string> tag
An html tag that has a separate closing tag such as <p>
<div> or <b... | [
"def",
"handle_starttag",
"(",
"self",
",",
"tag",
",",
"attrs",
")",
":",
"dattrs",
"=",
"dict",
"(",
"attrs",
")",
"# look for '<link type='text/css' rel='stylesheet' href='...' > tags",
"# to see if looking for link tags makes sense here, we need to know",
"# a little more abo... | This method handles any HTML tags that have a matching
closing tag. So elements like <p> and <div> are handled
by this method.
@param <string> tag
An html tag that has a separate closing tag such as <p>
<div> or <body>
@param <tuple> attrs
A tuple of HTM... | [
"This",
"method",
"handles",
"any",
"HTML",
"tags",
"that",
"have",
"a",
"matching",
"closing",
"tag",
".",
"So",
"elements",
"like",
"<p",
">",
"and",
"<div",
">",
"are",
"handled",
"by",
"this",
"method",
"."
] | train | https://github.com/KyleWpppd/css-audit/blob/cab4d4204cf30d54bc1881deee6ad92ae6aacc56/cssaudit/parser.py#L44-L82 |
KyleWpppd/css-audit | cssaudit/parser.py | Cssparser.handle_data | def handle_data(self, data):
"""
Called only for certain start tags where the data
in the body of the tag is of interest. In this case,
the data is for <style> tags and <link> tags to css
documents.
@param <string> data
The data lying between an opening and ... | python | def handle_data(self, data):
"""
Called only for certain start tags where the data
in the body of the tag is of interest. In this case,
the data is for <style> tags and <link> tags to css
documents.
@param <string> data
The data lying between an opening and ... | [
"def",
"handle_data",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"get_data",
"==",
"True",
":",
"self",
".",
"inline_css_data",
".",
"append",
"(",
"data",
")",
"#print self.inline_css_data",
"#print \"Sending to parser\"",
"self",
".",
"parse_inline... | Called only for certain start tags where the data
in the body of the tag is of interest. In this case,
the data is for <style> tags and <link> tags to css
documents.
@param <string> data
The data lying between an opening and closing HTML
tag. For instance in <di... | [
"Called",
"only",
"for",
"certain",
"start",
"tags",
"where",
"the",
"data",
"in",
"the",
"body",
"of",
"the",
"tag",
"is",
"of",
"interest",
".",
"In",
"this",
"case",
"the",
"data",
"is",
"for",
"<style",
">",
"tags",
"and",
"<link",
">",
"tags",
"... | train | https://github.com/KyleWpppd/css-audit/blob/cab4d4204cf30d54bc1881deee6ad92ae6aacc56/cssaudit/parser.py#L84-L100 |
KyleWpppd/css-audit | cssaudit/parser.py | Cssparser.handle_startendtag | def handle_startendtag(self, tag, attrs):
"""
Called when Cssparser finds a tag that does not have a
closing tag, such as <meta>, or <link>. These tags have
no data, so we just pass them forward.
@param <string> tag
The HTML tag we're currently parsing
@param ... | python | def handle_startendtag(self, tag, attrs):
"""
Called when Cssparser finds a tag that does not have a
closing tag, such as <meta>, or <link>. These tags have
no data, so we just pass them forward.
@param <string> tag
The HTML tag we're currently parsing
@param ... | [
"def",
"handle_startendtag",
"(",
"self",
",",
"tag",
",",
"attrs",
")",
":",
"dattrs",
"=",
"dict",
"(",
"attrs",
")",
"if",
"tag",
".",
"lower",
"(",
")",
"==",
"'link'",
":",
"#print \"Found link\"",
"if",
"all",
"(",
"k",
"in",
"dattrs",
"for",
"... | Called when Cssparser finds a tag that does not have a
closing tag, such as <meta>, or <link>. These tags have
no data, so we just pass them forward.
@param <string> tag
The HTML tag we're currently parsing
@param <tuple> attrs
A tuple of HTML element attributes su... | [
"Called",
"when",
"Cssparser",
"finds",
"a",
"tag",
"that",
"does",
"not",
"have",
"a",
"closing",
"tag",
"such",
"as",
"<meta",
">",
"or",
"<link",
">",
".",
"These",
"tags",
"have",
"no",
"data",
"so",
"we",
"just",
"pass",
"them",
"forward",
"."
] | train | https://github.com/KyleWpppd/css-audit/blob/cab4d4204cf30d54bc1881deee6ad92ae6aacc56/cssaudit/parser.py#L102-L127 |
KyleWpppd/css-audit | cssaudit/parser.py | Cssparser.append_styles | def append_styles(self, tag, attrs):
"""
Append classes found in HTML elements to the list of styles used.
Because we haven't built the tree, we aren't using the `tag` parameter
for now.
@param <string> tag
The HTML tag we're parsing
@param <tuple> attrs
... | python | def append_styles(self, tag, attrs):
"""
Append classes found in HTML elements to the list of styles used.
Because we haven't built the tree, we aren't using the `tag` parameter
for now.
@param <string> tag
The HTML tag we're parsing
@param <tuple> attrs
... | [
"def",
"append_styles",
"(",
"self",
",",
"tag",
",",
"attrs",
")",
":",
"dattrs",
"=",
"dict",
"(",
"attrs",
")",
"if",
"'class'",
"in",
"dattrs",
":",
"#print \"Found classes '%s'\" % dattrs['class']",
"class_names",
"=",
"dattrs",
"[",
"'class'",
"]",
".",
... | Append classes found in HTML elements to the list of styles used.
Because we haven't built the tree, we aren't using the `tag` parameter
for now.
@param <string> tag
The HTML tag we're parsing
@param <tuple> attrs
A tuple of HTML element attributes such as 'class'... | [
"Append",
"classes",
"found",
"in",
"HTML",
"elements",
"to",
"the",
"list",
"of",
"styles",
"used",
".",
"Because",
"we",
"haven",
"t",
"built",
"the",
"tree",
"we",
"aren",
"t",
"using",
"the",
"tag",
"parameter",
"for",
"now",
"."
] | train | https://github.com/KyleWpppd/css-audit/blob/cab4d4204cf30d54bc1881deee6ad92ae6aacc56/cssaudit/parser.py#L129-L151 |
KyleWpppd/css-audit | cssaudit/parser.py | Cssparser.parse_inline_styles | def parse_inline_styles(self, data=None, import_type ='string'):
"""
Function for parsing styles defined in the body of the document.
This only includes data inside of HTML <style> tags, a URL, or file to open.
"""
if data is None:
raise
parser = cssutils.CSS... | python | def parse_inline_styles(self, data=None, import_type ='string'):
"""
Function for parsing styles defined in the body of the document.
This only includes data inside of HTML <style> tags, a URL, or file to open.
"""
if data is None:
raise
parser = cssutils.CSS... | [
"def",
"parse_inline_styles",
"(",
"self",
",",
"data",
"=",
"None",
",",
"import_type",
"=",
"'string'",
")",
":",
"if",
"data",
"is",
"None",
":",
"raise",
"parser",
"=",
"cssutils",
".",
"CSSParser",
"(",
")",
"if",
"import_type",
"==",
"'string'",
":... | Function for parsing styles defined in the body of the document.
This only includes data inside of HTML <style> tags, a URL, or file to open. | [
"Function",
"for",
"parsing",
"styles",
"defined",
"in",
"the",
"body",
"of",
"the",
"document",
".",
"This",
"only",
"includes",
"data",
"inside",
"of",
"HTML",
"<style",
">",
"tags",
"a",
"URL",
"or",
"file",
"to",
"open",
"."
] | train | https://github.com/KyleWpppd/css-audit/blob/cab4d4204cf30d54bc1881deee6ad92ae6aacc56/cssaudit/parser.py#L154-L200 |
marcosgabarda/django-belt | belt/decorators.py | delete_after | def delete_after(filename):
"""Decorator to be sure the file given by parameter is deleted after the
execution of the method.
"""
def delete_after_decorator(function):
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
finally:
... | python | def delete_after(filename):
"""Decorator to be sure the file given by parameter is deleted after the
execution of the method.
"""
def delete_after_decorator(function):
def wrapper(*args, **kwargs):
try:
return function(*args, **kwargs)
finally:
... | [
"def",
"delete_after",
"(",
"filename",
")",
":",
"def",
"delete_after_decorator",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"k... | Decorator to be sure the file given by parameter is deleted after the
execution of the method. | [
"Decorator",
"to",
"be",
"sure",
"the",
"file",
"given",
"by",
"parameter",
"is",
"deleted",
"after",
"the",
"execution",
"of",
"the",
"method",
"."
] | train | https://github.com/marcosgabarda/django-belt/blob/81404604c4dff664b1520b01e1f638c9c6bab41b/belt/decorators.py#L8-L22 |
tBaxter/tango-shared-core | build/lib/tango_shared/utils/maptools.py | get_geocode | def get_geocode(city, state, street_address="", zipcode=""):
"""
For given location or object, takes address data and returns
latitude and longitude coordinates from Google geocoding service
get_geocode(self, street_address="1709 Grand Ave.", state="MO", zip="64112")
Returns a tuple of (lat, long)... | python | def get_geocode(city, state, street_address="", zipcode=""):
"""
For given location or object, takes address data and returns
latitude and longitude coordinates from Google geocoding service
get_geocode(self, street_address="1709 Grand Ave.", state="MO", zip="64112")
Returns a tuple of (lat, long)... | [
"def",
"get_geocode",
"(",
"city",
",",
"state",
",",
"street_address",
"=",
"\"\"",
",",
"zipcode",
"=",
"\"\"",
")",
":",
"try",
":",
"key",
"=",
"settings",
".",
"GMAP_KEY",
"except",
"AttributeError",
":",
"return",
"\"You need to put GMAP_KEY in settings\""... | For given location or object, takes address data and returns
latitude and longitude coordinates from Google geocoding service
get_geocode(self, street_address="1709 Grand Ave.", state="MO", zip="64112")
Returns a tuple of (lat, long)
Most times you'll want to join the return. | [
"For",
"given",
"location",
"or",
"object",
"takes",
"address",
"data",
"and",
"returns",
"latitude",
"and",
"longitude",
"coordinates",
"from",
"Google",
"geocoding",
"service"
] | train | https://github.com/tBaxter/tango-shared-core/blob/35fc10aef1ceedcdb4d6d866d44a22efff718812/build/lib/tango_shared/utils/maptools.py#L10-L50 |
dicaso/leopard | leopard/__init__.py | Section.append | def append(self,*args,toSection=None,**kwargs):
"""Append a new section
If toSection is None, section is appended to the main section/subs list.
Else if toSection is int or (int,int,...), it gets added to the subs (subsection)
list of the specified section.
*args* and *kwargs* a... | python | def append(self,*args,toSection=None,**kwargs):
"""Append a new section
If toSection is None, section is appended to the main section/subs list.
Else if toSection is int or (int,int,...), it gets added to the subs (subsection)
list of the specified section.
*args* and *kwargs* a... | [
"def",
"append",
"(",
"self",
",",
"*",
"args",
",",
"toSection",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"toSection",
"and",
"toSection",
"is",
"not",
"0",
":",
"s",
"=",
"Section",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",... | Append a new section
If toSection is None, section is appended to the main section/subs list.
Else if toSection is int or (int,int,...), it gets added to the subs (subsection)
list of the specified section.
*args* and *kwargs* are processed by Section class initiation | [
"Append",
"a",
"new",
"section",
"If",
"toSection",
"is",
"None",
"section",
"is",
"appended",
"to",
"the",
"main",
"section",
"/",
"subs",
"list",
".",
"Else",
"if",
"toSection",
"is",
"int",
"or",
"(",
"int",
"int",
"...",
")",
"it",
"gets",
"added",... | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L79-L96 |
dicaso/leopard | leopard/__init__.py | Section.sectionWalker | def sectionWalker(section,callback,*args,walkTrace=tuple(),**kwargs):
"""
callback needs to be a function that handles different
Section elements appropriately
walkTrace needs to be a tuple, indicate the route to the section, e.g. (1,2,0)
"""
callback(section,*args,walkT... | python | def sectionWalker(section,callback,*args,walkTrace=tuple(),**kwargs):
"""
callback needs to be a function that handles different
Section elements appropriately
walkTrace needs to be a tuple, indicate the route to the section, e.g. (1,2,0)
"""
callback(section,*args,walkT... | [
"def",
"sectionWalker",
"(",
"section",
",",
"callback",
",",
"*",
"args",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"callback",
"(",
"section",
",",
"*",
"args",
",",
"walkTrace",
"=",
"walkTrace",
",",
"case",
"="... | callback needs to be a function that handles different
Section elements appropriately
walkTrace needs to be a tuple, indicate the route to the section, e.g. (1,2,0) | [
"callback",
"needs",
"to",
"be",
"a",
"function",
"that",
"handles",
"different",
"Section",
"elements",
"appropriately",
"walkTrace",
"needs",
"to",
"be",
"a",
"tuple",
"indicate",
"the",
"route",
"to",
"the",
"section",
"e",
".",
"g",
".",
"(",
"1",
"2",... | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L99-L114 |
dicaso/leopard | leopard/__init__.py | Section.walkerWrapper | def walkerWrapper(callback):
"""
Wraps a callback function in a wrapper that will be applied to all [sub]sections.
Returns:
function
"""
def wrapper(*args,**kwargs):
#args[0] => has to be the current walked section
return Section.sectionWalker... | python | def walkerWrapper(callback):
"""
Wraps a callback function in a wrapper that will be applied to all [sub]sections.
Returns:
function
"""
def wrapper(*args,**kwargs):
#args[0] => has to be the current walked section
return Section.sectionWalker... | [
"def",
"walkerWrapper",
"(",
"callback",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#args[0] => has to be the current walked section",
"return",
"Section",
".",
"sectionWalker",
"(",
"args",
"[",
"0",
"]",
",",
"callback"... | Wraps a callback function in a wrapper that will be applied to all [sub]sections.
Returns:
function | [
"Wraps",
"a",
"callback",
"function",
"in",
"a",
"wrapper",
"that",
"will",
"be",
"applied",
"to",
"all",
"[",
"sub",
"]",
"sections",
"."
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L116-L126 |
dicaso/leopard | leopard/__init__.py | Section.list | def list(self,walkTrace=tuple(),case=None,element=None):
"""List section titles.
"""
if case == 'sectionmain': print(walkTrace,self.title) | python | def list(self,walkTrace=tuple(),case=None,element=None):
"""List section titles.
"""
if case == 'sectionmain': print(walkTrace,self.title) | [
"def",
"list",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
")",
":",
"if",
"case",
"==",
"'sectionmain'",
":",
"print",
"(",
"walkTrace",
",",
"self",
".",
"title",
")"
] | List section titles. | [
"List",
"section",
"titles",
"."
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L129-L132 |
dicaso/leopard | leopard/__init__.py | Section.listFigures | def listFigures(self,walkTrace=tuple(),case=None,element=None):
"""List section figures.
"""
if case == 'sectionmain': print(walkTrace,self.title)
if case == 'figure':
caption,fig = element
try:
print(walkTrace,fig._leopardref,caption)
... | python | def listFigures(self,walkTrace=tuple(),case=None,element=None):
"""List section figures.
"""
if case == 'sectionmain': print(walkTrace,self.title)
if case == 'figure':
caption,fig = element
try:
print(walkTrace,fig._leopardref,caption)
... | [
"def",
"listFigures",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
")",
":",
"if",
"case",
"==",
"'sectionmain'",
":",
"print",
"(",
"walkTrace",
",",
"self",
".",
"title",
")",
"if",
... | List section figures. | [
"List",
"section",
"figures",
"."
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L135-L145 |
dicaso/leopard | leopard/__init__.py | Section.listTables | def listTables(self,walkTrace=tuple(),case=None,element=None):
"""List section tables.
"""
if case == 'sectionmain': print(walkTrace,self.title)
if case == 'table':
caption,tab = element
try:
print(walkTrace,tab._leopardref,caption)
exc... | python | def listTables(self,walkTrace=tuple(),case=None,element=None):
"""List section tables.
"""
if case == 'sectionmain': print(walkTrace,self.title)
if case == 'table':
caption,tab = element
try:
print(walkTrace,tab._leopardref,caption)
exc... | [
"def",
"listTables",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
")",
":",
"if",
"case",
"==",
"'sectionmain'",
":",
"print",
"(",
"walkTrace",
",",
"self",
".",
"title",
")",
"if",
... | List section tables. | [
"List",
"section",
"tables",
"."
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L148-L158 |
dicaso/leopard | leopard/__init__.py | Section.sectionOutZip | def sectionOutZip(self,zipcontainer,zipdir='',figtype='png'):
"""Prepares section for zip output
"""
from io import StringIO, BytesIO
text = self.p if not self.settings['doubleslashnewline'] else self.p.replace('//','\n')
zipcontainer.writestr(
zipdir+'section.txt',
... | python | def sectionOutZip(self,zipcontainer,zipdir='',figtype='png'):
"""Prepares section for zip output
"""
from io import StringIO, BytesIO
text = self.p if not self.settings['doubleslashnewline'] else self.p.replace('//','\n')
zipcontainer.writestr(
zipdir+'section.txt',
... | [
"def",
"sectionOutZip",
"(",
"self",
",",
"zipcontainer",
",",
"zipdir",
"=",
"''",
",",
"figtype",
"=",
"'png'",
")",
":",
"from",
"io",
"import",
"StringIO",
",",
"BytesIO",
"text",
"=",
"self",
".",
"p",
"if",
"not",
"self",
".",
"settings",
"[",
... | Prepares section for zip output | [
"Prepares",
"section",
"for",
"zip",
"output"
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L160-L187 |
dicaso/leopard | leopard/__init__.py | Section.sectionsPDF | def sectionsPDF(self,walkTrace=tuple(),case=None,element=None,doc=None):
"""Prepares section for PDF output.
"""
import pylatex as pl
if case == 'sectionmain':
if self.settings['clearpage']: doc.append(pl.utils.NoEscape(r'\clearpage'))
with doc.create(pl.Section(s... | python | def sectionsPDF(self,walkTrace=tuple(),case=None,element=None,doc=None):
"""Prepares section for PDF output.
"""
import pylatex as pl
if case == 'sectionmain':
if self.settings['clearpage']: doc.append(pl.utils.NoEscape(r'\clearpage'))
with doc.create(pl.Section(s... | [
"def",
"sectionsPDF",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
",",
"doc",
"=",
"None",
")",
":",
"import",
"pylatex",
"as",
"pl",
"if",
"case",
"==",
"'sectionmain'",
":",
"if",
... | Prepares section for PDF output. | [
"Prepares",
"section",
"for",
"PDF",
"output",
"."
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L190-L240 |
dicaso/leopard | leopard/__init__.py | Section.sectionsWord | def sectionsWord(self,walkTrace=tuple(),case=None,element=None,doc=None):
"""Prepares section for word output.
"""
from docx.shared import Inches
from io import BytesIO
#p.add_run('italic.').italic = True
if case == 'sectionmain':
if self.sett... | python | def sectionsWord(self,walkTrace=tuple(),case=None,element=None,doc=None):
"""Prepares section for word output.
"""
from docx.shared import Inches
from io import BytesIO
#p.add_run('italic.').italic = True
if case == 'sectionmain':
if self.sett... | [
"def",
"sectionsWord",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
",",
"doc",
"=",
"None",
")",
":",
"from",
"docx",
".",
"shared",
"import",
"Inches",
"from",
"io",
"import",
"BytesI... | Prepares section for word output. | [
"Prepares",
"section",
"for",
"word",
"output",
"."
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L244-L286 |
dicaso/leopard | leopard/__init__.py | Section.sectionFromFunction | def sectionFromFunction(function,*args,**kwargs):
"""
This staticmethod executes the function that is passed with the provided args and kwargs.
The first line of the function docstring is used as the section title, the comments
within the function body are parsed and added as the section... | python | def sectionFromFunction(function,*args,**kwargs):
"""
This staticmethod executes the function that is passed with the provided args and kwargs.
The first line of the function docstring is used as the section title, the comments
within the function body are parsed and added as the section... | [
"def",
"sectionFromFunction",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"figures",
",",
"tables",
"=",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"title",
"=",
"inspect",
".",
"getcomments",
"(",
"function",... | This staticmethod executes the function that is passed with the provided args and kwargs.
The first line of the function docstring is used as the section title, the comments
within the function body are parsed and added as the section text.
The function should return an ordered dict of figures a... | [
"This",
"staticmethod",
"executes",
"the",
"function",
"that",
"is",
"passed",
"with",
"the",
"provided",
"args",
"and",
"kwargs",
".",
"The",
"first",
"line",
"of",
"the",
"function",
"docstring",
"is",
"used",
"as",
"the",
"section",
"title",
"the",
"comme... | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L289-L316 |
dicaso/leopard | leopard/__init__.py | Report.list | def list(self):
"""
Get an overview of the report content list
"""
for i in range(len(self.sections)):
self.sections[i].list(walkTrace=(i+1,)) | python | def list(self):
"""
Get an overview of the report content list
"""
for i in range(len(self.sections)):
self.sections[i].list(walkTrace=(i+1,)) | [
"def",
"list",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"sections",
")",
")",
":",
"self",
".",
"sections",
"[",
"i",
"]",
".",
"list",
"(",
"walkTrace",
"=",
"(",
"i",
"+",
"1",
",",
")",
")"
] | Get an overview of the report content list | [
"Get",
"an",
"overview",
"of",
"the",
"report",
"content",
"list"
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L357-L362 |
dicaso/leopard | leopard/__init__.py | Report.outputZip | def outputZip(self,figtype='png'):
"""
Outputs the report in a zip container.
Figs and tabs as pngs and excells.
Args:
figtype (str): Figure type of images in the zip folder.
"""
from zipfile import ZipFile
with ZipFile(self.outfile+'.zip', 'w') as zi... | python | def outputZip(self,figtype='png'):
"""
Outputs the report in a zip container.
Figs and tabs as pngs and excells.
Args:
figtype (str): Figure type of images in the zip folder.
"""
from zipfile import ZipFile
with ZipFile(self.outfile+'.zip', 'w') as zi... | [
"def",
"outputZip",
"(",
"self",
",",
"figtype",
"=",
"'png'",
")",
":",
"from",
"zipfile",
"import",
"ZipFile",
"with",
"ZipFile",
"(",
"self",
".",
"outfile",
"+",
"'.zip'",
",",
"'w'",
")",
"as",
"zipcontainer",
":",
"zipcontainer",
".",
"writestr",
"... | Outputs the report in a zip container.
Figs and tabs as pngs and excells.
Args:
figtype (str): Figure type of images in the zip folder. | [
"Outputs",
"the",
"report",
"in",
"a",
"zip",
"container",
".",
"Figs",
"and",
"tabs",
"as",
"pngs",
"and",
"excells",
"."
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L364-L385 |
dicaso/leopard | leopard/__init__.py | Report.outputPDF | def outputPDF(self,**kwargs):
"""Makes a pdf report with pylatex
*kwargs* are send to doc.generate_pdf
-> see pylatex.Document.generate_pdf for help
"""
import pylatex as pl
geometry_options = {"tmargin": "2cm", "lmargin": "2cm"}
doc = pl.Document(geometry_option... | python | def outputPDF(self,**kwargs):
"""Makes a pdf report with pylatex
*kwargs* are send to doc.generate_pdf
-> see pylatex.Document.generate_pdf for help
"""
import pylatex as pl
geometry_options = {"tmargin": "2cm", "lmargin": "2cm"}
doc = pl.Document(geometry_option... | [
"def",
"outputPDF",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"pylatex",
"as",
"pl",
"geometry_options",
"=",
"{",
"\"tmargin\"",
":",
"\"2cm\"",
",",
"\"lmargin\"",
":",
"\"2cm\"",
"}",
"doc",
"=",
"pl",
".",
"Document",
"(",
"geometry_o... | Makes a pdf report with pylatex
*kwargs* are send to doc.generate_pdf
-> see pylatex.Document.generate_pdf for help | [
"Makes",
"a",
"pdf",
"report",
"with",
"pylatex",
"*",
"kwargs",
"*",
"are",
"send",
"to",
"doc",
".",
"generate_pdf",
"-",
">",
"see",
"pylatex",
".",
"Document",
".",
"generate_pdf",
"for",
"help"
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L387-L422 |
dicaso/leopard | leopard/__init__.py | Report.outputWord | def outputWord(self):
"""Output report to word docx
"""
import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = docx.Document()
doc.styles['Normal'].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
doc.add_heading(self.title, level... | python | def outputWord(self):
"""Output report to word docx
"""
import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc = docx.Document()
doc.styles['Normal'].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
doc.add_heading(self.title, level... | [
"def",
"outputWord",
"(",
"self",
")",
":",
"import",
"docx",
"from",
"docx",
".",
"enum",
".",
"text",
"import",
"WD_ALIGN_PARAGRAPH",
"doc",
"=",
"docx",
".",
"Document",
"(",
")",
"doc",
".",
"styles",
"[",
"'Normal'",
"]",
".",
"paragraph_format",
".... | Output report to word docx | [
"Output",
"report",
"to",
"word",
"docx"
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L424-L459 |
dicaso/leopard | leopard/__init__.py | Report.getReportTable | def getReportTable(reportzipfile,tablefilename,inReportsDir=True,verbose=False):
"""Get a pandas table from a previous report
Args:
reportzipfile (str): Zip folder location, '.zip' extension is optional.
tablefilename (str or list int): Table location within the zip folder.
... | python | def getReportTable(reportzipfile,tablefilename,inReportsDir=True,verbose=False):
"""Get a pandas table from a previous report
Args:
reportzipfile (str): Zip folder location, '.zip' extension is optional.
tablefilename (str or list int): Table location within the zip folder.
... | [
"def",
"getReportTable",
"(",
"reportzipfile",
",",
"tablefilename",
",",
"inReportsDir",
"=",
"True",
",",
"verbose",
"=",
"False",
")",
":",
"import",
"zipfile",
",",
"io",
",",
"re",
"# zipfilename preparation",
"if",
"not",
"reportzipfile",
".",
"endswith",
... | Get a pandas table from a previous report
Args:
reportzipfile (str): Zip folder location, '.zip' extension is optional.
tablefilename (str or list int): Table location within the zip folder.
Can be provided as the filename within the zip folder, or a list of integers
... | [
"Get",
"a",
"pandas",
"table",
"from",
"a",
"previous",
"report"
] | train | https://github.com/dicaso/leopard/blob/ee9f45251aaacd1e453b135b419f4f0b50fb036e/leopard/__init__.py#L462-L502 |
dillonhicks/rekt | rekt/service.py | create_api_call_func | def create_api_call_func(api, verb):
"""
From an api definition object create the related api call method
that will validate the arguments for the api call and then
dynamically dispatch the request to the appropriate requests module
convenience method for the specific HTTP verb .
"""
# Scop... | python | def create_api_call_func(api, verb):
"""
From an api definition object create the related api call method
that will validate the arguments for the api call and then
dynamically dispatch the request to the appropriate requests module
convenience method for the specific HTTP verb .
"""
# Scop... | [
"def",
"create_api_call_func",
"(",
"api",
",",
"verb",
")",
":",
"# Scopes some local context in which we can build",
"# request functions with reflection that primed with",
"# some static parameters.",
"def",
"api_call_func",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
... | From an api definition object create the related api call method
that will validate the arguments for the api call and then
dynamically dispatch the request to the appropriate requests module
convenience method for the specific HTTP verb . | [
"From",
"an",
"api",
"definition",
"object",
"create",
"the",
"related",
"api",
"call",
"method",
"that",
"will",
"validate",
"the",
"arguments",
"for",
"the",
"api",
"call",
"and",
"then",
"dynamically",
"dispatch",
"the",
"request",
"to",
"the",
"appropriate... | train | https://github.com/dillonhicks/rekt/blob/3848b272726c78214cb96b906f9b9f289497f27e/rekt/service.py#L150-L195 |
dillonhicks/rekt | rekt/service.py | create_async_api_call_func | def create_async_api_call_func(api, verb):
"""
From an api definition object create the related api call method
that will validate the arguments for the api call and then
dynamically dispatch the request to the appropriate requests module
convenience method for the specific HTTP verb .
"""
... | python | def create_async_api_call_func(api, verb):
"""
From an api definition object create the related api call method
that will validate the arguments for the api call and then
dynamically dispatch the request to the appropriate requests module
convenience method for the specific HTTP verb .
"""
... | [
"def",
"create_async_api_call_func",
"(",
"api",
",",
"verb",
")",
":",
"# Scopes some local context in which we can build",
"# request functions with reflection that primed with",
"# some static parameters.",
"def",
"api_call_func",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
... | From an api definition object create the related api call method
that will validate the arguments for the api call and then
dynamically dispatch the request to the appropriate requests module
convenience method for the specific HTTP verb . | [
"From",
"an",
"api",
"definition",
"object",
"create",
"the",
"related",
"api",
"call",
"method",
"that",
"will",
"validate",
"the",
"arguments",
"for",
"the",
"api",
"call",
"and",
"then",
"dynamically",
"dispatch",
"the",
"request",
"to",
"the",
"appropriate... | train | https://github.com/dillonhicks/rekt/blob/3848b272726c78214cb96b906f9b9f289497f27e/rekt/service.py#L198-L223 |
dillonhicks/rekt | rekt/service.py | create_rest_client_class | def create_rest_client_class(name, apis, BaseClass=RestClient):
"""
Generate the api call functions and attach them to the generated
RestClient subclass with the name <Service>Client.
"""
apis_with_actions = list(itertools.chain.from_iterable([ zip([api] * len(api.actions), api.actions) for api in ... | python | def create_rest_client_class(name, apis, BaseClass=RestClient):
"""
Generate the api call functions and attach them to the generated
RestClient subclass with the name <Service>Client.
"""
apis_with_actions = list(itertools.chain.from_iterable([ zip([api] * len(api.actions), api.actions) for api in ... | [
"def",
"create_rest_client_class",
"(",
"name",
",",
"apis",
",",
"BaseClass",
"=",
"RestClient",
")",
":",
"apis_with_actions",
"=",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"[",
"zip",
"(",
"[",
"api",
"]",
"*",
"len",
"(",
"a... | Generate the api call functions and attach them to the generated
RestClient subclass with the name <Service>Client. | [
"Generate",
"the",
"api",
"call",
"functions",
"and",
"attach",
"them",
"to",
"the",
"generated",
"RestClient",
"subclass",
"with",
"the",
"name",
"<Service",
">",
"Client",
"."
] | train | https://github.com/dillonhicks/rekt/blob/3848b272726c78214cb96b906f9b9f289497f27e/rekt/service.py#L227-L249 |
dillonhicks/rekt | rekt/service.py | create_service_module | def create_service_module(service_name, apis):
"""
Dynamically creates a module named defined by the PEP-8 version of
the string contained in service_name (from the YAML config). This
module will contain a Client class, a Call Factory, and list of API
definition objects.
"""
service_module = imp.ne... | python | def create_service_module(service_name, apis):
"""
Dynamically creates a module named defined by the PEP-8 version of
the string contained in service_name (from the YAML config). This
module will contain a Client class, a Call Factory, and list of API
definition objects.
"""
service_module = imp.ne... | [
"def",
"create_service_module",
"(",
"service_name",
",",
"apis",
")",
":",
"service_module",
"=",
"imp",
".",
"new_module",
"(",
"service_name",
".",
"lower",
"(",
")",
")",
"for",
"api",
"in",
"apis",
":",
"setattr",
"(",
"service_module",
",",
"api",
".... | Dynamically creates a module named defined by the PEP-8 version of
the string contained in service_name (from the YAML config). This
module will contain a Client class, a Call Factory, and list of API
definition objects. | [
"Dynamically",
"creates",
"a",
"module",
"named",
"defined",
"by",
"the",
"PEP",
"-",
"8",
"version",
"of",
"the",
"string",
"contained",
"in",
"service_name",
"(",
"from",
"the",
"YAML",
"config",
")",
".",
"This",
"module",
"will",
"contain",
"a",
"Clien... | train | https://github.com/dillonhicks/rekt/blob/3848b272726c78214cb96b906f9b9f289497f27e/rekt/service.py#L252-L270 |
dillonhicks/rekt | rekt/service.py | load_service | def load_service(config):
"""
Load a restful service specified by some YAML file at config_path.
:param config_path: A pathlib Path object that points to the yaml
config
:returns: A python module containing a Client class, call factory,
and the definition of each of the APIs defined by the co... | python | def load_service(config):
"""
Load a restful service specified by some YAML file at config_path.
:param config_path: A pathlib Path object that points to the yaml
config
:returns: A python module containing a Client class, call factory,
and the definition of each of the APIs defined by the co... | [
"def",
"load_service",
"(",
"config",
")",
":",
"if",
"isinstance",
"(",
"config",
",",
"collections",
".",
"abc",
".",
"Mapping",
")",
":",
"service_config",
"=",
"config",
"elif",
"isinstance",
"(",
"config",
",",
"str",
")",
":",
"service_config",
"=",
... | Load a restful service specified by some YAML file at config_path.
:param config_path: A pathlib Path object that points to the yaml
config
:returns: A python module containing a Client class, call factory,
and the definition of each of the APIs defined by the config. | [
"Load",
"a",
"restful",
"service",
"specified",
"by",
"some",
"YAML",
"file",
"at",
"config_path",
"."
] | train | https://github.com/dillonhicks/rekt/blob/3848b272726c78214cb96b906f9b9f289497f27e/rekt/service.py#L273-L297 |
cdeboever3/cdpybio | cdpybio/general.py | estimate_allele_frequency | def estimate_allele_frequency(ac, an, a=1, b=100):
"""
Make sample (or other) names.
Parameters:
-----------
ac : array-like
Array-like object with the observed allele counts for each variant. If
ac is a pandas Series, the output dataframe will have the same index as
ac.
... | python | def estimate_allele_frequency(ac, an, a=1, b=100):
"""
Make sample (or other) names.
Parameters:
-----------
ac : array-like
Array-like object with the observed allele counts for each variant. If
ac is a pandas Series, the output dataframe will have the same index as
ac.
... | [
"def",
"estimate_allele_frequency",
"(",
"ac",
",",
"an",
",",
"a",
"=",
"1",
",",
"b",
"=",
"100",
")",
":",
"# Credible interval is 95% highest posterior density",
"td",
"=",
"dict",
"(",
"zip",
"(",
"[",
"'ci_lower'",
",",
"'ci_upper'",
"]",
",",
"stats",... | Make sample (or other) names.
Parameters:
-----------
ac : array-like
Array-like object with the observed allele counts for each variant. If
ac is a pandas Series, the output dataframe will have the same index as
ac.
an : array-like
Array-like object with the number of... | [
"Make",
"sample",
"(",
"or",
"other",
")",
"names",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/general.py#L16-L51 |
cdeboever3/cdpybio | cdpybio/general.py | transform_standard_normal | def transform_standard_normal(df):
"""Transform a series or the rows of a dataframe to the values of a standard
normal based on rank."""
import pandas as pd
import scipy.stats as stats
if type(df) == pd.core.frame.DataFrame:
gc_ranks = df.rank(axis=1)
gc_ranks = gc_ranks / (gc_ranks.... | python | def transform_standard_normal(df):
"""Transform a series or the rows of a dataframe to the values of a standard
normal based on rank."""
import pandas as pd
import scipy.stats as stats
if type(df) == pd.core.frame.DataFrame:
gc_ranks = df.rank(axis=1)
gc_ranks = gc_ranks / (gc_ranks.... | [
"def",
"transform_standard_normal",
"(",
"df",
")",
":",
"import",
"pandas",
"as",
"pd",
"import",
"scipy",
".",
"stats",
"as",
"stats",
"if",
"type",
"(",
"df",
")",
"==",
"pd",
".",
"core",
".",
"frame",
".",
"DataFrame",
":",
"gc_ranks",
"=",
"df",
... | Transform a series or the rows of a dataframe to the values of a standard
normal based on rank. | [
"Transform",
"a",
"series",
"or",
"the",
"rows",
"of",
"a",
"dataframe",
"to",
"the",
"values",
"of",
"a",
"standard",
"normal",
"based",
"on",
"rank",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/general.py#L53-L69 |
cdeboever3/cdpybio | cdpybio/general.py | read_gzipped_text_url | def read_gzipped_text_url(url):
"""Read a gzipped text file from a URL and return
contents as a string."""
import urllib2
import zlib
from StringIO import StringIO
opener = urllib2.build_opener()
request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip')
respond ... | python | def read_gzipped_text_url(url):
"""Read a gzipped text file from a URL and return
contents as a string."""
import urllib2
import zlib
from StringIO import StringIO
opener = urllib2.build_opener()
request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip')
respond ... | [
"def",
"read_gzipped_text_url",
"(",
"url",
")",
":",
"import",
"urllib2",
"import",
"zlib",
"from",
"StringIO",
"import",
"StringIO",
"opener",
"=",
"urllib2",
".",
"build_opener",
"(",
")",
"request",
"=",
"urllib2",
".",
"Request",
"(",
"url",
")",
"reque... | Read a gzipped text file from a URL and return
contents as a string. | [
"Read",
"a",
"gzipped",
"text",
"file",
"from",
"a",
"URL",
"and",
"return",
"contents",
"as",
"a",
"string",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/general.py#L71-L94 |
cdeboever3/cdpybio | cdpybio/general.py | parse_region | def parse_region(region):
"""
Parse region of type chr1:10-20 or chr1:10-20:+
Parameters:
-----------
region : str
Region of type chr1:10-20 or chr1:10-20:+.
Returns
-------
groups : tuple
Tuple of groups from regex e.g. (chr1, 10, 20) or (chr1, 10, 20, +).
"""
... | python | def parse_region(region):
"""
Parse region of type chr1:10-20 or chr1:10-20:+
Parameters:
-----------
region : str
Region of type chr1:10-20 or chr1:10-20:+.
Returns
-------
groups : tuple
Tuple of groups from regex e.g. (chr1, 10, 20) or (chr1, 10, 20, +).
"""
... | [
"def",
"parse_region",
"(",
"region",
")",
":",
"m",
"=",
"R_REGEX_STRAND",
".",
"search",
"(",
"region",
")",
"if",
"not",
"m",
":",
"m",
"=",
"R_REGEX",
".",
"search",
"(",
"region",
")",
"if",
"m",
":",
"groups",
"=",
"m",
".",
"groups",
"(",
... | Parse region of type chr1:10-20 or chr1:10-20:+
Parameters:
-----------
region : str
Region of type chr1:10-20 or chr1:10-20:+.
Returns
-------
groups : tuple
Tuple of groups from regex e.g. (chr1, 10, 20) or (chr1, 10, 20, +). | [
"Parse",
"region",
"of",
"type",
"chr1",
":",
"10",
"-",
"20",
"or",
"chr1",
":",
"10",
"-",
"20",
":",
"+"
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/general.py#L96-L119 |
cdeboever3/cdpybio | cdpybio/general.py | _sample_names | def _sample_names(files, kwargs):
"""
Make sample (or other) names.
Parameters:
-----------
files : list of string
Typically a list of file paths although could be any list of strings
that you want to make names for. If neither names nor define_sample_name
are provided, the... | python | def _sample_names(files, kwargs):
"""
Make sample (or other) names.
Parameters:
-----------
files : list of string
Typically a list of file paths although could be any list of strings
that you want to make names for. If neither names nor define_sample_name
are provided, the... | [
"def",
"_sample_names",
"(",
"files",
",",
"kwargs",
")",
":",
"if",
"'define_sample_name'",
"not",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"define_sample_name",
"=",
"lambda",
"x",
":",
"x",
"else",
":",
"define_sample_name",
"=",
"kwargs",
"[",
"'def... | Make sample (or other) names.
Parameters:
-----------
files : list of string
Typically a list of file paths although could be any list of strings
that you want to make names for. If neither names nor define_sample_name
are provided, then files is returned as is.
kwargs : dict
... | [
"Make",
"sample",
"(",
"or",
"other",
")",
"names",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/general.py#L121-L156 |
proversity-org/bibblio-api-python | bibbliothon/discovery.py | content_recommendations | def content_recommendations(access_token, content_item_id):
'''
Name: content_recommendations
Parameters: access_token, content_item_id
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
recommendations_url =\
construct_content_recommendations_url(enrichment_url, content_item_id... | python | def content_recommendations(access_token, content_item_id):
'''
Name: content_recommendations
Parameters: access_token, content_item_id
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
recommendations_url =\
construct_content_recommendations_url(enrichment_url, content_item_id... | [
"def",
"content_recommendations",
"(",
"access_token",
",",
"content_item_id",
")",
":",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Bearer '",
"+",
"str",
"(",
"access_token",
")",
"}",
"recommendations_url",
"=",
"construct_content_recommendations_url",
"(",
"enr... | Name: content_recommendations
Parameters: access_token, content_item_id
Return: dictionary | [
"Name",
":",
"content_recommendations",
"Parameters",
":",
"access_token",
"content_item_id",
"Return",
":",
"dictionary"
] | train | https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/discovery.py#L14-L30 |
proversity-org/bibblio-api-python | bibbliothon/discovery.py | recommendations | def recommendations(access_token, payload): # (Legacy)
'''
Name: recommendations
Parameters: access_token, payload
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
request = requests.post(recommendations_url, json=payload, headers=headers)
if request.status_code == 200:
metad... | python | def recommendations(access_token, payload): # (Legacy)
'''
Name: recommendations
Parameters: access_token, payload
Return: dictionary
'''
headers = {'Authorization': 'Bearer ' + str(access_token)}
request = requests.post(recommendations_url, json=payload, headers=headers)
if request.status_code == 200:
metad... | [
"def",
"recommendations",
"(",
"access_token",
",",
"payload",
")",
":",
"# (Legacy)",
"headers",
"=",
"{",
"'Authorization'",
":",
"'Bearer '",
"+",
"str",
"(",
"access_token",
")",
"}",
"request",
"=",
"requests",
".",
"post",
"(",
"recommendations_url",
","... | Name: recommendations
Parameters: access_token, payload
Return: dictionary | [
"Name",
":",
"recommendations",
"Parameters",
":",
"access_token",
"payload",
"Return",
":",
"dictionary"
] | train | https://github.com/proversity-org/bibblio-api-python/blob/d619223ad80a4bcd32f90ba64d93370260601b60/bibbliothon/discovery.py#L32-L45 |
OpenGov/carpenter | carpenter/blocks/flagable.py | Flagable.flag_change | def flag_change(self, flags, level, location=None, worksheet=None, message=''):
'''
Wraps the pushing of a change flag into the flags dictionary to handle
all edge cases/auto-filling.
'''
if not isinstance(level, basestring):
try:
level = self.FLAG_LEV... | python | def flag_change(self, flags, level, location=None, worksheet=None, message=''):
'''
Wraps the pushing of a change flag into the flags dictionary to handle
all edge cases/auto-filling.
'''
if not isinstance(level, basestring):
try:
level = self.FLAG_LEV... | [
"def",
"flag_change",
"(",
"self",
",",
"flags",
",",
"level",
",",
"location",
"=",
"None",
",",
"worksheet",
"=",
"None",
",",
"message",
"=",
"''",
")",
":",
"if",
"not",
"isinstance",
"(",
"level",
",",
"basestring",
")",
":",
"try",
":",
"level"... | Wraps the pushing of a change flag into the flags dictionary to handle
all edge cases/auto-filling. | [
"Wraps",
"the",
"pushing",
"of",
"a",
"change",
"flag",
"into",
"the",
"flags",
"dictionary",
"to",
"handle",
"all",
"edge",
"cases",
"/",
"auto",
"-",
"filling",
"."
] | train | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/flagable.py#L54-L74 |
OpenGov/carpenter | carpenter/blocks/flagable.py | Flagable.get_worst_flag_level | def get_worst_flag_level(self, flags):
'''
Determines the worst flag present in the provided flags. If no
flags are given then a 'minor' value is returned.
'''
worst_flag_level = 0
for flag_level_name in flags:
flag_level = self.FLAG_LEVELS[flag_level_name]
... | python | def get_worst_flag_level(self, flags):
'''
Determines the worst flag present in the provided flags. If no
flags are given then a 'minor' value is returned.
'''
worst_flag_level = 0
for flag_level_name in flags:
flag_level = self.FLAG_LEVELS[flag_level_name]
... | [
"def",
"get_worst_flag_level",
"(",
"self",
",",
"flags",
")",
":",
"worst_flag_level",
"=",
"0",
"for",
"flag_level_name",
"in",
"flags",
":",
"flag_level",
"=",
"self",
".",
"FLAG_LEVELS",
"[",
"flag_level_name",
"]",
"if",
"flag_level",
">",
"worst_flag_level... | Determines the worst flag present in the provided flags. If no
flags are given then a 'minor' value is returned. | [
"Determines",
"the",
"worst",
"flag",
"present",
"in",
"the",
"provided",
"flags",
".",
"If",
"no",
"flags",
"are",
"given",
"then",
"a",
"minor",
"value",
"is",
"returned",
"."
] | train | https://github.com/OpenGov/carpenter/blob/0ab3c54c05133b9b0468c63e834a7ce3a6fb575b/carpenter/blocks/flagable.py#L76-L86 |
skitazaki/python-clitool | clitool/accesslog.py | parse | def parse(line):
""" Parse accesslog line to map Python dictionary.
Returned dictionary has following keys:
- time: access time (datetime; naive)
- utcoffset: UTC offset of access time (timedelta)
- host: remote IP address.
- path: HTTP request path, this will be splitted from query.
- que... | python | def parse(line):
""" Parse accesslog line to map Python dictionary.
Returned dictionary has following keys:
- time: access time (datetime; naive)
- utcoffset: UTC offset of access time (timedelta)
- host: remote IP address.
- path: HTTP request path, this will be splitted from query.
- que... | [
"def",
"parse",
"(",
"line",
")",
":",
"m",
"=",
"LOG_FORMAT",
".",
"match",
"(",
"line",
")",
"if",
"m",
"is",
"None",
":",
"return",
"access",
"=",
"Access",
".",
"_make",
"(",
"m",
".",
"groups",
"(",
")",
")",
"entry",
"=",
"{",
"'host'",
"... | Parse accesslog line to map Python dictionary.
Returned dictionary has following keys:
- time: access time (datetime; naive)
- utcoffset: UTC offset of access time (timedelta)
- host: remote IP address.
- path: HTTP request path, this will be splitted from query.
- query: HTTP requert query st... | [
"Parse",
"accesslog",
"line",
"to",
"map",
"Python",
"dictionary",
"."
] | train | https://github.com/skitazaki/python-clitool/blob/4971f8d093d51c6fd0e6cc536bbb597f78b570ab/clitool/accesslog.py#L60-L122 |
skitazaki/python-clitool | clitool/accesslog.py | logentry | def logentry(raw):
"""[DEPRECATED] Process accesslog record to map Python dictionary.
Returned dictionary has following keys:
- remote_address: remote IP address.
- access_time: datetime object.
- request_path: HTTP request path, this will be splitted from query.
- request_query: HTTP requert ... | python | def logentry(raw):
"""[DEPRECATED] Process accesslog record to map Python dictionary.
Returned dictionary has following keys:
- remote_address: remote IP address.
- access_time: datetime object.
- request_path: HTTP request path, this will be splitted from query.
- request_query: HTTP requert ... | [
"def",
"logentry",
"(",
"raw",
")",
":",
"warnings",
".",
"warn",
"(",
"'use \"parse()\" instead'",
",",
"DeprecationWarning",
")",
"e",
"=",
"parse",
"(",
"raw",
".",
"rstrip",
"(",
")",
")",
"if",
"e",
"is",
"None",
":",
"return",
"# backward compat mapp... | [DEPRECATED] Process accesslog record to map Python dictionary.
Returned dictionary has following keys:
- remote_address: remote IP address.
- access_time: datetime object.
- request_path: HTTP request path, this will be splitted from query.
- request_query: HTTP requert query string removed from ... | [
"[",
"DEPRECATED",
"]",
"Process",
"accesslog",
"record",
"to",
"map",
"Python",
"dictionary",
"."
] | train | https://github.com/skitazaki/python-clitool/blob/4971f8d093d51c6fd0e6cc536bbb597f78b570ab/clitool/accesslog.py#L125-L166 |
skitazaki/python-clitool | clitool/accesslog.py | logparse | def logparse(*args, **kwargs):
""" Parse access log on the terminal application.
If list of files are given, parse each file. Otherwise, parse standard
input.
:param args: supporting functions after processed raw log line
:type: list of callables
:rtype: tuple of (statistics, key/value report)
... | python | def logparse(*args, **kwargs):
""" Parse access log on the terminal application.
If list of files are given, parse each file. Otherwise, parse standard
input.
:param args: supporting functions after processed raw log line
:type: list of callables
:rtype: tuple of (statistics, key/value report)
... | [
"def",
"logparse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"clitool",
".",
"cli",
"import",
"clistream",
"from",
"clitool",
".",
"processor",
"import",
"SimpleDictReporter",
"lst",
"=",
"[",
"parse",
"]",
"+",
"args",
"reporter",
"="... | Parse access log on the terminal application.
If list of files are given, parse each file. Otherwise, parse standard
input.
:param args: supporting functions after processed raw log line
:type: list of callables
:rtype: tuple of (statistics, key/value report) | [
"Parse",
"access",
"log",
"on",
"the",
"terminal",
"application",
".",
"If",
"list",
"of",
"files",
"are",
"given",
"parse",
"each",
"file",
".",
"Otherwise",
"parse",
"standard",
"input",
"."
] | train | https://github.com/skitazaki/python-clitool/blob/4971f8d093d51c6fd0e6cc536bbb597f78b570ab/clitool/accesslog.py#L169-L184 |
MacHu-GWU/angora-project | angora/math/outlier.py | std_filter | def std_filter(array, n_std=2.0, return_index=False):
"""Standard deviation outlier detector.
:param array: array of data.
:param n_std: default 2.0, exclude data out of ``n_std`` standard deviation.
:param return_index: boolean, default False, if True, only returns index.
"""
if not isinstance... | python | def std_filter(array, n_std=2.0, return_index=False):
"""Standard deviation outlier detector.
:param array: array of data.
:param n_std: default 2.0, exclude data out of ``n_std`` standard deviation.
:param return_index: boolean, default False, if True, only returns index.
"""
if not isinstance... | [
"def",
"std_filter",
"(",
"array",
",",
"n_std",
"=",
"2.0",
",",
"return_index",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"array",
",",
"np",
".",
"ndarray",
")",
":",
"array",
"=",
"np",
".",
"array",
"(",
"array",
")",
"mean",
","... | Standard deviation outlier detector.
:param array: array of data.
:param n_std: default 2.0, exclude data out of ``n_std`` standard deviation.
:param return_index: boolean, default False, if True, only returns index. | [
"Standard",
"deviation",
"outlier",
"detector",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/outlier.py#L47-L64 |
MacHu-GWU/angora-project | angora/math/outlier.py | box_filter | def box_filter(array, n_iqr=1.5, return_index=False):
"""Box plot outlier detector.
:param array: array of data.
:param n_std: default 1.5, exclude data out of ``n_iqr`` IQR.
:param return_index: boolean, default False, if True, only returns index.
"""
if not isinstance(array, np.ndarray):
... | python | def box_filter(array, n_iqr=1.5, return_index=False):
"""Box plot outlier detector.
:param array: array of data.
:param n_std: default 1.5, exclude data out of ``n_iqr`` IQR.
:param return_index: boolean, default False, if True, only returns index.
"""
if not isinstance(array, np.ndarray):
... | [
"def",
"box_filter",
"(",
"array",
",",
"n_iqr",
"=",
"1.5",
",",
"return_index",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"array",
",",
"np",
".",
"ndarray",
")",
":",
"array",
"=",
"np",
".",
"array",
"(",
"array",
")",
"Q3",
"=",
... | Box plot outlier detector.
:param array: array of data.
:param n_std: default 1.5, exclude data out of ``n_iqr`` IQR.
:param return_index: boolean, default False, if True, only returns index. | [
"Box",
"plot",
"outlier",
"detector",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/math/outlier.py#L67-L87 |
jkawamoto/dsargparse | sample.py | main | def main():
""" The main function.
"""
parser = dsargparse.ArgumentParser(main=main)
subparsers = parser.add_subparsers()
greeting_cmd = subparsers.add_parser(greeting)
greeting_cmd.add_argument("title")
greeting_cmd.add_argument("name")
goodbye_cmd = subparsers.add_parser(goodbye)
... | python | def main():
""" The main function.
"""
parser = dsargparse.ArgumentParser(main=main)
subparsers = parser.add_subparsers()
greeting_cmd = subparsers.add_parser(greeting)
greeting_cmd.add_argument("title")
greeting_cmd.add_argument("name")
goodbye_cmd = subparsers.add_parser(goodbye)
... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"dsargparse",
".",
"ArgumentParser",
"(",
"main",
"=",
"main",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
")",
"greeting_cmd",
"=",
"subparsers",
".",
"add_parser",
"(",
"greeting",
")",
"gree... | The main function. | [
"The",
"main",
"function",
"."
] | train | https://github.com/jkawamoto/dsargparse/blob/dbbcea11ff1ae7b84bdfccb9f97d1947574e4126/sample.py#L80-L93 |
esterhui/pypu | pypu/pusher_utils.py | resize_image | def resize_image(fullfile,fullfile_resized,_megapixels):
"""Resizes image (fullfile), saves to fullfile_resized. Image
aspect ratio is conserved, will be scaled to be close to _megapixels in
size. Eg if _megapixels=2, will resize 2560x1920 so each dimension
is scaled by ((2**(20+1*MP))/float(2560*1920)... | python | def resize_image(fullfile,fullfile_resized,_megapixels):
"""Resizes image (fullfile), saves to fullfile_resized. Image
aspect ratio is conserved, will be scaled to be close to _megapixels in
size. Eg if _megapixels=2, will resize 2560x1920 so each dimension
is scaled by ((2**(20+1*MP))/float(2560*1920)... | [
"def",
"resize_image",
"(",
"fullfile",
",",
"fullfile_resized",
",",
"_megapixels",
")",
":",
"logger",
".",
"debug",
"(",
"\"%s - Resizing to %s MP\"",
"%",
"(",
"fullfile",
",",
"_megapixels",
")",
")",
"img",
"=",
"Image",
".",
"open",
"(",
"fullfile",
"... | Resizes image (fullfile), saves to fullfile_resized. Image
aspect ratio is conserved, will be scaled to be close to _megapixels in
size. Eg if _megapixels=2, will resize 2560x1920 so each dimension
is scaled by ((2**(20+1*MP))/float(2560*1920))**2 | [
"Resizes",
"image",
"(",
"fullfile",
")",
"saves",
"to",
"fullfile_resized",
".",
"Image",
"aspect",
"ratio",
"is",
"conserved",
"will",
"be",
"scaled",
"to",
"be",
"close",
"to",
"_megapixels",
"in",
"size",
".",
"Eg",
"if",
"_megapixels",
"=",
"2",
"will... | train | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/pusher_utils.py#L9-L43 |
esterhui/pypu | pypu/pusher_utils.py | update_exif_GEXIV2 | def update_exif_GEXIV2(oldfile,newfile):
"""Transfers oldfile's exif to newfile's exif and
updates the width/height EXIF fields"""
# Requires gexiv2 and pygobject package in gentoo
# (USE=introspection)
try:
from gi.repository import GExiv2
except:
print("Couldn't import GExiv... | python | def update_exif_GEXIV2(oldfile,newfile):
"""Transfers oldfile's exif to newfile's exif and
updates the width/height EXIF fields"""
# Requires gexiv2 and pygobject package in gentoo
# (USE=introspection)
try:
from gi.repository import GExiv2
except:
print("Couldn't import GExiv... | [
"def",
"update_exif_GEXIV2",
"(",
"oldfile",
",",
"newfile",
")",
":",
"# Requires gexiv2 and pygobject package in gentoo ",
"# (USE=introspection)",
"try",
":",
"from",
"gi",
".",
"repository",
"import",
"GExiv2",
"except",
":",
"print",
"(",
"\"Couldn't import GExiv2\""... | Transfers oldfile's exif to newfile's exif and
updates the width/height EXIF fields | [
"Transfers",
"oldfile",
"s",
"exif",
"to",
"newfile",
"s",
"exif",
"and",
"updates",
"the",
"width",
"/",
"height",
"EXIF",
"fields"
] | train | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/pusher_utils.py#L45-L82 |
esterhui/pypu | pypu/pusher_utils.py | resize_compute_width_height | def resize_compute_width_height(fullfile,_megapixels):
"""Given image file and desired megapixels,
computes the new width and height"""
img = Image.open(fullfile)
width,height=img.size
current_megapixels=width*height/(2.0**20)
scale=sqrt(_megapixels/float(current_megapixels))
logger.debug... | python | def resize_compute_width_height(fullfile,_megapixels):
"""Given image file and desired megapixels,
computes the new width and height"""
img = Image.open(fullfile)
width,height=img.size
current_megapixels=width*height/(2.0**20)
scale=sqrt(_megapixels/float(current_megapixels))
logger.debug... | [
"def",
"resize_compute_width_height",
"(",
"fullfile",
",",
"_megapixels",
")",
":",
"img",
"=",
"Image",
".",
"open",
"(",
"fullfile",
")",
"width",
",",
"height",
"=",
"img",
".",
"size",
"current_megapixels",
"=",
"width",
"*",
"height",
"/",
"(",
"2.0"... | Given image file and desired megapixels,
computes the new width and height | [
"Given",
"image",
"file",
"and",
"desired",
"megapixels",
"computes",
"the",
"new",
"width",
"and",
"height"
] | train | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/pusher_utils.py#L84-L104 |
esterhui/pypu | pypu/pusher_utils.py | getexif_location | def getexif_location(directory,fn):
"""
directory - Dir where file is located
fn - filename to check for EXIF GPS
Returns touple of lat,lon if EXIF
eg. (34.035460,-118.227885)
files contains GPS info, otherwise returns
None,None
"""
lat=None
lon=None
sign_lat=+1.0
sign_... | python | def getexif_location(directory,fn):
"""
directory - Dir where file is located
fn - filename to check for EXIF GPS
Returns touple of lat,lon if EXIF
eg. (34.035460,-118.227885)
files contains GPS info, otherwise returns
None,None
"""
lat=None
lon=None
sign_lat=+1.0
sign_... | [
"def",
"getexif_location",
"(",
"directory",
",",
"fn",
")",
":",
"lat",
"=",
"None",
"lon",
"=",
"None",
"sign_lat",
"=",
"+",
"1.0",
"sign_lon",
"=",
"+",
"1.0",
"# Check if photo as geo info already",
"exif_tags",
"=",
"exifread",
".",
"process_file",
"(",
... | directory - Dir where file is located
fn - filename to check for EXIF GPS
Returns touple of lat,lon if EXIF
eg. (34.035460,-118.227885)
files contains GPS info, otherwise returns
None,None | [
"directory",
"-",
"Dir",
"where",
"file",
"is",
"located",
"fn",
"-",
"filename",
"to",
"check",
"for",
"EXIF",
"GPS"
] | train | https://github.com/esterhui/pypu/blob/cc3e259d59f024c2c4c0fbb9c8a1547e51de75ec/pypu/pusher_utils.py#L107-L143 |
CognitionGuidedSurgery/pyclictk | clictk/model.py | Parameter.from_xml_node | def from_xml_node(xml_node):
"""constructs a CLI.Parameter from an xml node.
:param xml_node:
:type xml_node: xml.etree.ElementTree.Element
:rtype: Executable.Parameter
:return:
"""
def gather_enum_values():
l = []
for element in xml_node.... | python | def from_xml_node(xml_node):
"""constructs a CLI.Parameter from an xml node.
:param xml_node:
:type xml_node: xml.etree.ElementTree.Element
:rtype: Executable.Parameter
:return:
"""
def gather_enum_values():
l = []
for element in xml_node.... | [
"def",
"from_xml_node",
"(",
"xml_node",
")",
":",
"def",
"gather_enum_values",
"(",
")",
":",
"l",
"=",
"[",
"]",
"for",
"element",
"in",
"xml_node",
".",
"iterfind",
"(",
"'element'",
")",
":",
"l",
".",
"append",
"(",
"element",
".",
"text",
")",
... | constructs a CLI.Parameter from an xml node.
:param xml_node:
:type xml_node: xml.etree.ElementTree.Element
:rtype: Executable.Parameter
:return: | [
"constructs",
"a",
"CLI",
".",
"Parameter",
"from",
"an",
"xml",
"node",
".",
":",
"param",
"xml_node",
":",
":",
"type",
"xml_node",
":",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"Element",
":",
"rtype",
":",
"Executable",
".",
"Parameter",
":",
... | train | https://github.com/CognitionGuidedSurgery/pyclictk/blob/74915098a24a33adb46d8738f9c4746d91ecc1dc/clictk/model.py#L240-L279 |
CognitionGuidedSurgery/pyclictk | clictk/model.py | Executable.cmdline | def cmdline(self, **kwargs):
"""Generates a valid command line call for the executable given by call arguments in `kwargs`
:param kwargs: values to call the executable
:return: the command line
:rtype: list
"""
args = [self.executable]
indexed_args = []
... | python | def cmdline(self, **kwargs):
"""Generates a valid command line call for the executable given by call arguments in `kwargs`
:param kwargs: values to call the executable
:return: the command line
:rtype: list
"""
args = [self.executable]
indexed_args = []
... | [
"def",
"cmdline",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"self",
".",
"executable",
"]",
"indexed_args",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"parameter",
"=",
"self"... | Generates a valid command line call for the executable given by call arguments in `kwargs`
:param kwargs: values to call the executable
:return: the command line
:rtype: list | [
"Generates",
"a",
"valid",
"command",
"line",
"call",
"for",
"the",
"executable",
"given",
"by",
"call",
"arguments",
"in",
"kwargs",
":",
"param",
"kwargs",
":",
"values",
"to",
"call",
"the",
"executable",
":",
"return",
":",
"the",
"command",
"line",
":... | train | https://github.com/CognitionGuidedSurgery/pyclictk/blob/74915098a24a33adb46d8738f9c4746d91ecc1dc/clictk/model.py#L412-L438 |
CognitionGuidedSurgery/pyclictk | clictk/model.py | Executable.from_etree | def from_etree(tree):
"""Constructs an executable form a given ElementTree structure.
:param tree:
:type tree: xml.etree.ElementTree.ElementTree
:rtype: Executable
"""
exe = Executable(tree)
exe.category = tree.findtext('category')
exe.version = tree.fi... | python | def from_etree(tree):
"""Constructs an executable form a given ElementTree structure.
:param tree:
:type tree: xml.etree.ElementTree.ElementTree
:rtype: Executable
"""
exe = Executable(tree)
exe.category = tree.findtext('category')
exe.version = tree.fi... | [
"def",
"from_etree",
"(",
"tree",
")",
":",
"exe",
"=",
"Executable",
"(",
"tree",
")",
"exe",
".",
"category",
"=",
"tree",
".",
"findtext",
"(",
"'category'",
")",
"exe",
".",
"version",
"=",
"tree",
".",
"findtext",
"(",
"'version'",
")",
"exe",
"... | Constructs an executable form a given ElementTree structure.
:param tree:
:type tree: xml.etree.ElementTree.ElementTree
:rtype: Executable | [
"Constructs",
"an",
"executable",
"form",
"a",
"given",
"ElementTree",
"structure",
"."
] | train | https://github.com/CognitionGuidedSurgery/pyclictk/blob/74915098a24a33adb46d8738f9c4746d91ecc1dc/clictk/model.py#L501-L529 |
edwards-lab/libGWAS | libgwas/snp_boundary_check.py | SnpBoundaryCheck.ReportConfiguration | def ReportConfiguration(self, f):
"""Report the boundary configuration details
:param f: File (or standard out/err)
:return: None
"""
if BoundaryCheck.chrom != -1:
print >> f, BuildReportLine("CHROM", BoundaryCheck.chrom)
if len(self.start_bounds) > 0:
... | python | def ReportConfiguration(self, f):
"""Report the boundary configuration details
:param f: File (or standard out/err)
:return: None
"""
if BoundaryCheck.chrom != -1:
print >> f, BuildReportLine("CHROM", BoundaryCheck.chrom)
if len(self.start_bounds) > 0:
... | [
"def",
"ReportConfiguration",
"(",
"self",
",",
"f",
")",
":",
"if",
"BoundaryCheck",
".",
"chrom",
"!=",
"-",
"1",
":",
"print",
">>",
"f",
",",
"BuildReportLine",
"(",
"\"CHROM\"",
",",
"BoundaryCheck",
".",
"chrom",
")",
"if",
"len",
"(",
"self",
".... | Report the boundary configuration details
:param f: File (or standard out/err)
:return: None | [
"Report",
"the",
"boundary",
"configuration",
"details"
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/snp_boundary_check.py#L77-L92 |
edwards-lab/libGWAS | libgwas/snp_boundary_check.py | SnpBoundaryCheck.NoExclusions | def NoExclusions(self):
"""Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be moderately compute intensive.
... | python | def NoExclusions(self):
"""Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be moderately compute intensive.
... | [
"def",
"NoExclusions",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"start_bounds",
")",
"+",
"len",
"(",
"self",
".",
"target_rs",
")",
"+",
"len",
"(",
"self",
".",
"ignored_rs",
")",
"==",
"0",
":",
"return",
"BoundaryCheck",
".",
"chrom"... | Determine that there are no exclusion criterion in play
:return: True if there is no real boundary specification of any kind.
Simple method allowing parsers to short circuit the determination of
missingness, which can be moderately compute intensive. | [
"Determine",
"that",
"there",
"are",
"no",
"exclusion",
"criterion",
"in",
"play"
] | train | https://github.com/edwards-lab/libGWAS/blob/d68c9a083d443dfa5d7c5112de29010909cfe23f/libgwas/snp_boundary_check.py#L128-L138 |
mjalas/messaging-client | messaging_client/messaging_client.py | MessagingClient.set_address | def set_address(self, host, port):
"""Add host and port attributes"""
self.host = host
self.port = port | python | def set_address(self, host, port):
"""Add host and port attributes"""
self.host = host
self.port = port | [
"def",
"set_address",
"(",
"self",
",",
"host",
",",
"port",
")",
":",
"self",
".",
"host",
"=",
"host",
"self",
".",
"port",
"=",
"port"
] | Add host and port attributes | [
"Add",
"host",
"and",
"port",
"attributes"
] | train | https://github.com/mjalas/messaging-client/blob/b72ad622d9c94a879fe1085f0dbb52349892cd15/messaging_client/messaging_client.py#L32-L35 |
mjalas/messaging-client | messaging_client/messaging_client.py | MessagingClient.connect | def connect(self, host=None, port=None):
"""Connects to given host address and port."""
host = self.host if host is None else host
port = self.port if port is None else port
self.socket.connect(host, port) | python | def connect(self, host=None, port=None):
"""Connects to given host address and port."""
host = self.host if host is None else host
port = self.port if port is None else port
self.socket.connect(host, port) | [
"def",
"connect",
"(",
"self",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"host",
"=",
"self",
".",
"host",
"if",
"host",
"is",
"None",
"else",
"host",
"port",
"=",
"self",
".",
"port",
"if",
"port",
"is",
"None",
"else",
"port... | Connects to given host address and port. | [
"Connects",
"to",
"given",
"host",
"address",
"and",
"port",
"."
] | train | https://github.com/mjalas/messaging-client/blob/b72ad622d9c94a879fe1085f0dbb52349892cd15/messaging_client/messaging_client.py#L37-L41 |
mjalas/messaging-client | messaging_client/messaging_client.py | MessagingClient.send_file_message | def send_file_message(self, filename):
"""Send message inside the given file."""
data = self._readFile(filename)
self.print_debug_message(data)
self.socket.send(data) | python | def send_file_message(self, filename):
"""Send message inside the given file."""
data = self._readFile(filename)
self.print_debug_message(data)
self.socket.send(data) | [
"def",
"send_file_message",
"(",
"self",
",",
"filename",
")",
":",
"data",
"=",
"self",
".",
"_readFile",
"(",
"filename",
")",
"self",
".",
"print_debug_message",
"(",
"data",
")",
"self",
".",
"socket",
".",
"send",
"(",
"data",
")"
] | Send message inside the given file. | [
"Send",
"message",
"inside",
"the",
"given",
"file",
"."
] | train | https://github.com/mjalas/messaging-client/blob/b72ad622d9c94a879fe1085f0dbb52349892cd15/messaging_client/messaging_client.py#L54-L58 |
mjalas/messaging-client | messaging_client/messaging_client.py | MessagingClient.send_message | def send_message(self, message):
"""Send a given message to the remote host."""
self.print_debug_message(message)
self.socket.send(message) | python | def send_message(self, message):
"""Send a given message to the remote host."""
self.print_debug_message(message)
self.socket.send(message) | [
"def",
"send_message",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"print_debug_message",
"(",
"message",
")",
"self",
".",
"socket",
".",
"send",
"(",
"message",
")"
] | Send a given message to the remote host. | [
"Send",
"a",
"given",
"message",
"to",
"the",
"remote",
"host",
"."
] | train | https://github.com/mjalas/messaging-client/blob/b72ad622d9c94a879fe1085f0dbb52349892cd15/messaging_client/messaging_client.py#L60-L63 |
hsoft/xibless | xibless/util.py | modified_after | def modified_after(first_path, second_path):
"""Returns True if first_path's mtime is higher than second_path's mtime."""
try:
first_mtime = os.stat(first_path).st_mtime
except EnvironmentError:
return False
try:
second_mtime = os.stat(second_path).st_mtime
except Environment... | python | def modified_after(first_path, second_path):
"""Returns True if first_path's mtime is higher than second_path's mtime."""
try:
first_mtime = os.stat(first_path).st_mtime
except EnvironmentError:
return False
try:
second_mtime = os.stat(second_path).st_mtime
except Environment... | [
"def",
"modified_after",
"(",
"first_path",
",",
"second_path",
")",
":",
"try",
":",
"first_mtime",
"=",
"os",
".",
"stat",
"(",
"first_path",
")",
".",
"st_mtime",
"except",
"EnvironmentError",
":",
"return",
"False",
"try",
":",
"second_mtime",
"=",
"os",... | Returns True if first_path's mtime is higher than second_path's mtime. | [
"Returns",
"True",
"if",
"first_path",
"s",
"mtime",
"is",
"higher",
"than",
"second_path",
"s",
"mtime",
"."
] | train | https://github.com/hsoft/xibless/blob/a7393d28b4a31698869b2203d4d8b3398de1de7f/xibless/util.py#L3-L13 |
davidmiller/letter | letter/social.py | TwitterPostie.send | def send(self, to, from_, body, dm=False):
"""
Send BODY as an @message from FROM to TO
If we don't have the access tokens for FROM, raise AccountNotFoundError.
If the tweet resulting from '@{0} {1}'.format(TO, BODY) is > 140 chars
raise TweetTooLongError.
If we want to... | python | def send(self, to, from_, body, dm=False):
"""
Send BODY as an @message from FROM to TO
If we don't have the access tokens for FROM, raise AccountNotFoundError.
If the tweet resulting from '@{0} {1}'.format(TO, BODY) is > 140 chars
raise TweetTooLongError.
If we want to... | [
"def",
"send",
"(",
"self",
",",
"to",
",",
"from_",
",",
"body",
",",
"dm",
"=",
"False",
")",
":",
"tweet",
"=",
"'@{0} {1}'",
".",
"format",
"(",
"to",
",",
"body",
")",
"if",
"from_",
"not",
"in",
"self",
".",
"accounts",
":",
"raise",
"Accou... | Send BODY as an @message from FROM to TO
If we don't have the access tokens for FROM, raise AccountNotFoundError.
If the tweet resulting from '@{0} {1}'.format(TO, BODY) is > 140 chars
raise TweetTooLongError.
If we want to send this message as a DM, do so.
Arguments:
... | [
"Send",
"BODY",
"as",
"an",
"@message",
"from",
"FROM",
"to",
"TO"
] | train | https://github.com/davidmiller/letter/blob/c0c66ae2c6a792106e9a8374a01421817c8a8ae0/letter/social.py#L31-L64 |
Tathorack/searchcolor | searchcolor/average.py | average_image_url | def average_image_url(url, name, timeout=5, max_size=5):
"""Takes an image url and averages the image.
Arguments
url: str
url for image to average
name: str
name to use
timeout: int
request timeout in seconds
max_size: int
max size of request in MB
return {red... | python | def average_image_url(url, name, timeout=5, max_size=5):
"""Takes an image url and averages the image.
Arguments
url: str
url for image to average
name: str
name to use
timeout: int
request timeout in seconds
max_size: int
max size of request in MB
return {red... | [
"def",
"average_image_url",
"(",
"url",
",",
"name",
",",
"timeout",
"=",
"5",
",",
"max_size",
"=",
"5",
")",
":",
"try",
":",
"shorturl",
"=",
"url",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"-",
"1",
"]",
"logger",
".",
"debug",
"(",
"... | Takes an image url and averages the image.
Arguments
url: str
url for image to average
name: str
name to use
timeout: int
request timeout in seconds
max_size: int
max size of request in MB
return {red':r_avg, 'green':g_avg, 'blue':b_avg} or None | [
"Takes",
"an",
"image",
"url",
"and",
"averages",
"the",
"image",
".",
"Arguments",
"url",
":",
"str",
"url",
"for",
"image",
"to",
"average",
"name",
":",
"str",
"name",
"to",
"use",
"timeout",
":",
"int",
"request",
"timeout",
"in",
"seconds",
"max_siz... | train | https://github.com/Tathorack/searchcolor/blob/f50b0a40e9da59fd994440f20e106730b9deb6bf/searchcolor/average.py#L39-L72 |
Tathorack/searchcolor | searchcolor/average.py | _image_search_average | def _image_search_average(url_list, max_threads=2, **kwargs):
"""Takes a list of image urls and averages the images to get the
average color. Designed to be implimented with many methods of
url sourcing.
Arguments
url_list: list
list of strings with the image urls to average
max_threads:... | python | def _image_search_average(url_list, max_threads=2, **kwargs):
"""Takes a list of image urls and averages the images to get the
average color. Designed to be implimented with many methods of
url sourcing.
Arguments
url_list: list
list of strings with the image urls to average
max_threads:... | [
"def",
"_image_search_average",
"(",
"url_list",
",",
"max_threads",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"url_list",
")",
"<",
"1",
":",
"raise",
"ZeroResultsException",
"(",
"'No urls to average'",
")",
"r_total",
"=",
"0",
"g_t... | Takes a list of image urls and averages the images to get the
average color. Designed to be implimented with many methods of
url sourcing.
Arguments
url_list: list
list of strings with the image urls to average
max_threads: int
max number of processes to spawn
return {red':r_avg,... | [
"Takes",
"a",
"list",
"of",
"image",
"urls",
"and",
"averages",
"the",
"images",
"to",
"get",
"the",
"average",
"color",
".",
"Designed",
"to",
"be",
"implimented",
"with",
"many",
"methods",
"of",
"url",
"sourcing",
".",
"Arguments",
"url_list",
":",
"lis... | train | https://github.com/Tathorack/searchcolor/blob/f50b0a40e9da59fd994440f20e106730b9deb6bf/searchcolor/average.py#L75-L120 |
Tathorack/searchcolor | searchcolor/average.py | google_average | def google_average(search_term, num_results, api_key, cse_id, **kwargs):
"""Does a Google image search to get the average color of the
top x results.
Arguments
search_term: str
tearm to search for
num_results: int
number of results to average
api_key: str
Google API key
... | python | def google_average(search_term, num_results, api_key, cse_id, **kwargs):
"""Does a Google image search to get the average color of the
top x results.
Arguments
search_term: str
tearm to search for
num_results: int
number of results to average
api_key: str
Google API key
... | [
"def",
"google_average",
"(",
"search_term",
",",
"num_results",
",",
"api_key",
",",
"cse_id",
",",
"*",
"*",
"kwargs",
")",
":",
"url_list",
"=",
"[",
"]",
"result",
"=",
"{",
"'name'",
":",
"search_term",
"}",
"GIS",
"=",
"GoogleImageSearch",
"(",
"ap... | Does a Google image search to get the average color of the
top x results.
Arguments
search_term: str
tearm to search for
num_results: int
number of results to average
api_key: str
Google API key
cse_id: str
Google CSE ID
max_threads: int
max number of ... | [
"Does",
"a",
"Google",
"image",
"search",
"to",
"get",
"the",
"average",
"color",
"of",
"the",
"top",
"x",
"results",
".",
"Arguments",
"search_term",
":",
"str",
"tearm",
"to",
"search",
"for",
"num_results",
":",
"int",
"number",
"of",
"results",
"to",
... | train | https://github.com/Tathorack/searchcolor/blob/f50b0a40e9da59fd994440f20e106730b9deb6bf/searchcolor/average.py#L123-L146 |
Tathorack/searchcolor | searchcolor/average.py | mscs_average | def mscs_average(search_term, num_results, api_key, **kwargs):
"""Does a Microsoft Cognitive image search to get the average color of the
top x results.
Arguments
search_term: str
tearm to search for
num_results: int
number of results to average
api_key: str
Microsoft Cog... | python | def mscs_average(search_term, num_results, api_key, **kwargs):
"""Does a Microsoft Cognitive image search to get the average color of the
top x results.
Arguments
search_term: str
tearm to search for
num_results: int
number of results to average
api_key: str
Microsoft Cog... | [
"def",
"mscs_average",
"(",
"search_term",
",",
"num_results",
",",
"api_key",
",",
"*",
"*",
"kwargs",
")",
":",
"url_list",
"=",
"[",
"]",
"result",
"=",
"{",
"'name'",
":",
"search_term",
"}",
"MCIS",
"=",
"MicrosoftCognitiveImageSearch",
"(",
"api_key",
... | Does a Microsoft Cognitive image search to get the average color of the
top x results.
Arguments
search_term: str
tearm to search for
num_results: int
number of results to average
api_key: str
Microsoft Cognitive API key
max_threads: int
max number of processes to... | [
"Does",
"a",
"Microsoft",
"Cognitive",
"image",
"search",
"to",
"get",
"the",
"average",
"color",
"of",
"the",
"top",
"x",
"results",
".",
"Arguments",
"search_term",
":",
"str",
"tearm",
"to",
"search",
"for",
"num_results",
":",
"int",
"number",
"of",
"r... | train | https://github.com/Tathorack/searchcolor/blob/f50b0a40e9da59fd994440f20e106730b9deb6bf/searchcolor/average.py#L149-L170 |
gear11/pypelogs | pypein/nginx.py | Nginx.to_ts | def to_ts(s):
"""Parses an NGINX timestamp from "30/Apr/2014:07:32:09 +0000" and returns it as ISO 8601" """
# Strip TZ portion if present
m = Nginx.DATE_FMT.match(s)
if m:
s = m.group(1)
delta = timedelta(seconds=int(m.group(3)) * (-1 if m.group(2) == '-' else ... | python | def to_ts(s):
"""Parses an NGINX timestamp from "30/Apr/2014:07:32:09 +0000" and returns it as ISO 8601" """
# Strip TZ portion if present
m = Nginx.DATE_FMT.match(s)
if m:
s = m.group(1)
delta = timedelta(seconds=int(m.group(3)) * (-1 if m.group(2) == '-' else ... | [
"def",
"to_ts",
"(",
"s",
")",
":",
"# Strip TZ portion if present",
"m",
"=",
"Nginx",
".",
"DATE_FMT",
".",
"match",
"(",
"s",
")",
"if",
"m",
":",
"s",
"=",
"m",
".",
"group",
"(",
"1",
")",
"delta",
"=",
"timedelta",
"(",
"seconds",
"=",
"int",... | Parses an NGINX timestamp from "30/Apr/2014:07:32:09 +0000" and returns it as ISO 8601" | [
"Parses",
"an",
"NGINX",
"timestamp",
"from",
"30",
"/",
"Apr",
"/",
"2014",
":",
"07",
":",
"32",
":",
"09",
"+",
"0000",
"and",
"returns",
"it",
"as",
"ISO",
"8601"
] | train | https://github.com/gear11/pypelogs/blob/da5dc0fee5373a4be294798b5e32cd0a803d8bbe/pypein/nginx.py#L65-L77 |
lextoumbourou/txstripe | stripe/api_requestor.py | APIRequestor.encode | def encode(cls, d):
"""
Internal: encode a string for url representation
"""
warnings.warn(
'The `encode` class method of APIRequestor is deprecated and '
'will be removed in version 2.0.'
'If you need public access to this function, please email us '
... | python | def encode(cls, d):
"""
Internal: encode a string for url representation
"""
warnings.warn(
'The `encode` class method of APIRequestor is deprecated and '
'will be removed in version 2.0.'
'If you need public access to this function, please email us '
... | [
"def",
"encode",
"(",
"cls",
",",
"d",
")",
":",
"warnings",
".",
"warn",
"(",
"'The `encode` class method of APIRequestor is deprecated and '",
"'will be removed in version 2.0.'",
"'If you need public access to this function, please email us '",
"'at support@stripe.com.'",
",",
"... | Internal: encode a string for url representation | [
"Internal",
":",
"encode",
"a",
"string",
"for",
"url",
"representation"
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/stripe/api_requestor.py#L115-L125 |
lextoumbourou/txstripe | stripe/api_requestor.py | APIRequestor.request_raw | def request_raw(self, method, url, params=None, supplied_headers=None):
"""
Mechanism for issuing an API call
"""
from stripe import api_version
if self.api_key:
my_api_key = self.api_key
else:
from stripe import api_key
my_api_key = a... | python | def request_raw(self, method, url, params=None, supplied_headers=None):
"""
Mechanism for issuing an API call
"""
from stripe import api_version
if self.api_key:
my_api_key = self.api_key
else:
from stripe import api_key
my_api_key = a... | [
"def",
"request_raw",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"supplied_headers",
"=",
"None",
")",
":",
"from",
"stripe",
"import",
"api_version",
"if",
"self",
".",
"api_key",
":",
"my_api_key",
"=",
"self",
".",
"api_k... | Mechanism for issuing an API call | [
"Mechanism",
"for",
"issuing",
"an",
"API",
"call"
] | train | https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/stripe/api_requestor.py#L176-L268 |
CitrineInformatics/dftparse | dftparse/wien2k/epsilon_parser.py | _parse_epsilon | def _parse_epsilon(line, lines):
"""Parse Energy [eV] Re_eps_xx Im_eps_xx Re_eps_zz Im_eps_zz"""
split_line = line.split()
energy = float(split_line[0])
re_eps_xx = float(split_line[1])
im_eps_xx = float(split_line[2])
re_eps_zz = float(split_line[3])
im_eps_zz = float(split_li... | python | def _parse_epsilon(line, lines):
"""Parse Energy [eV] Re_eps_xx Im_eps_xx Re_eps_zz Im_eps_zz"""
split_line = line.split()
energy = float(split_line[0])
re_eps_xx = float(split_line[1])
im_eps_xx = float(split_line[2])
re_eps_zz = float(split_line[3])
im_eps_zz = float(split_li... | [
"def",
"_parse_epsilon",
"(",
"line",
",",
"lines",
")",
":",
"split_line",
"=",
"line",
".",
"split",
"(",
")",
"energy",
"=",
"float",
"(",
"split_line",
"[",
"0",
"]",
")",
"re_eps_xx",
"=",
"float",
"(",
"split_line",
"[",
"1",
"]",
")",
"im_eps_... | Parse Energy [eV] Re_eps_xx Im_eps_xx Re_eps_zz Im_eps_zz | [
"Parse",
"Energy",
"[",
"eV",
"]",
"Re_eps_xx",
"Im_eps_xx",
"Re_eps_zz",
"Im_eps_zz"
] | train | https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/wien2k/epsilon_parser.py#L4-L16 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer._packet_loop | def _packet_loop(self):
"""
Loop (while running) the inbox and handle incoming packages
:rtype: None
"""
while not self._is_stopped.is_set():
if self.inbox.empty() and \
not self.new_packet.wait(self._packet_wait):
continue
... | python | def _packet_loop(self):
"""
Loop (while running) the inbox and handle incoming packages
:rtype: None
"""
while not self._is_stopped.is_set():
if self.inbox.empty() and \
not self.new_packet.wait(self._packet_wait):
continue
... | [
"def",
"_packet_loop",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"_is_stopped",
".",
"is_set",
"(",
")",
":",
"if",
"self",
".",
"inbox",
".",
"empty",
"(",
")",
"and",
"not",
"self",
".",
"new_packet",
".",
"wait",
"(",
"self",
".",
"_pa... | Loop (while running) the inbox and handle incoming packages
:rtype: None | [
"Loop",
"(",
"while",
"running",
")",
"the",
"inbox",
"and",
"handle",
"incoming",
"packages"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L58-L73 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer._do_packet | def _do_packet(self, packet, ip, port):
"""
React to incoming packet
:param packet: Packet to handle
:type packet: T >= paps.si.app.message.APPMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: ... | python | def _do_packet(self, packet, ip, port):
"""
React to incoming packet
:param packet: Packet to handle
:type packet: T >= paps.si.app.message.APPMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: ... | [
"def",
"_do_packet",
"(",
"self",
",",
"packet",
",",
"ip",
",",
"port",
")",
":",
"msg_type",
"=",
"packet",
".",
"header",
".",
"message_type",
"if",
"msg_type",
"==",
"MsgType",
".",
"JOIN",
":",
"self",
".",
"_do_join_packet",
"(",
"packet",
",",
"... | React to incoming packet
:param packet: Packet to handle
:type packet: T >= paps.si.app.message.APPMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: None | [
"React",
"to",
"incoming",
"packet"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L75-L94 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer._do_join_packet | def _do_join_packet(self, packet, ip, port):
"""
React to join packet - add a client to this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:param port: C... | python | def _do_join_packet(self, packet, ip, port):
"""
React to join packet - add a client to this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:param port: C... | [
"def",
"_do_join_packet",
"(",
"self",
",",
"packet",
",",
"ip",
",",
"port",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"device_id",
"=",
"packet",
".",
"header",
".",
"device_id",
"key",
"=",
"u\"{}:{}\"",
".",
"format",
"(",
"ip",
",",
"p... | React to join packet - add a client to this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: None | [
"React",
"to",
"join",
"packet",
"-",
"add",
"a",
"client",
"to",
"this",
"server"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L96-L147 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer._do_unjoin_packet | def _do_unjoin_packet(self, packet, ip, port):
"""
React to unjoin packet - remove a client from this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:para... | python | def _do_unjoin_packet(self, packet, ip, port):
"""
React to unjoin packet - remove a client from this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:para... | [
"def",
"_do_unjoin_packet",
"(",
"self",
",",
"packet",
",",
"ip",
",",
"port",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"device_id",
"=",
"packet",
".",
"header",
".",
"device_id",
"if",
"device_id",
"<=",
"Id",
".",
"SERVER",
":",
"self",
... | React to unjoin packet - remove a client from this server
:param packet: Packet from client that wants to join
:type packet: paps.si.app.message.APPJoinMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: None | [
"React",
"to",
"unjoin",
"packet",
"-",
"remove",
"a",
"client",
"from",
"this",
"server"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L149-L190 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer._do_update_packet | def _do_update_packet(self, packet, ip, port):
"""
React to update packet - people/person on a device have changed
:param packet: Packet from client with changes
:type packet: paps.si.app.message.APPUpdateMessage
:param ip: Client ip address
:type ip: unicode
:pa... | python | def _do_update_packet(self, packet, ip, port):
"""
React to update packet - people/person on a device have changed
:param packet: Packet from client with changes
:type packet: paps.si.app.message.APPUpdateMessage
:param ip: Client ip address
:type ip: unicode
:pa... | [
"def",
"_do_update_packet",
"(",
"self",
",",
"packet",
",",
"ip",
",",
"port",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"device_id",
"=",
"packet",
".",
"header",
".",
"device_id",
"if",
"device_id",
"<=",
"Id",
".",
"SERVER",
":",
"self",
... | React to update packet - people/person on a device have changed
:param packet: Packet from client with changes
:type packet: paps.si.app.message.APPUpdateMessage
:param ip: Client ip address
:type ip: unicode
:param port: Client port
:type port: int
:rtype: None | [
"React",
"to",
"update",
"packet",
"-",
"people",
"/",
"person",
"on",
"a",
"device",
"have",
"changed"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L192-L251 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer._new_device_id | def _new_device_id(self, key):
"""
Generate a new device id or return existing device id for key
:param key: Key for device
:type key: unicode
:return: The device id
:rtype: int
"""
device_id = Id.SERVER + 1
if key in self._key2deviceId:
... | python | def _new_device_id(self, key):
"""
Generate a new device id or return existing device id for key
:param key: Key for device
:type key: unicode
:return: The device id
:rtype: int
"""
device_id = Id.SERVER + 1
if key in self._key2deviceId:
... | [
"def",
"_new_device_id",
"(",
"self",
",",
"key",
")",
":",
"device_id",
"=",
"Id",
".",
"SERVER",
"+",
"1",
"if",
"key",
"in",
"self",
".",
"_key2deviceId",
":",
"return",
"self",
".",
"_key2deviceId",
"[",
"key",
"]",
"while",
"device_id",
"in",
"sel... | Generate a new device id or return existing device id for key
:param key: Key for device
:type key: unicode
:return: The device id
:rtype: int | [
"Generate",
"a",
"new",
"device",
"id",
"or",
"return",
"existing",
"device",
"id",
"for",
"key"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L253-L267 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer._init_multicast_socket | def _init_multicast_socket(self):
"""
Init multicast socket
:rtype: None
"""
self.debug("()")
# Create a UDP socket
self._multicast_socket = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)
# Allow reuse of addresses
... | python | def _init_multicast_socket(self):
"""
Init multicast socket
:rtype: None
"""
self.debug("()")
# Create a UDP socket
self._multicast_socket = socket.socket(
socket.AF_INET,
socket.SOCK_DGRAM
)
# Allow reuse of addresses
... | [
"def",
"_init_multicast_socket",
"(",
"self",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"# Create a UDP socket",
"self",
".",
"_multicast_socket",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"... | Init multicast socket
:rtype: None | [
"Init",
"multicast",
"socket"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L269-L312 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer._shutdown_multicast_socket | def _shutdown_multicast_socket(self):
"""
Shutdown multicast socket
:rtype: None
"""
self.debug("()")
self._drop_membership_multicast_socket()
self._listening.remove(self._multicast_socket)
self._multicast_socket.close()
self._multicast_socket = N... | python | def _shutdown_multicast_socket(self):
"""
Shutdown multicast socket
:rtype: None
"""
self.debug("()")
self._drop_membership_multicast_socket()
self._listening.remove(self._multicast_socket)
self._multicast_socket.close()
self._multicast_socket = N... | [
"def",
"_shutdown_multicast_socket",
"(",
"self",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"self",
".",
"_drop_membership_multicast_socket",
"(",
")",
"self",
".",
"_listening",
".",
"remove",
"(",
"self",
".",
"_multicast_socket",
")",
"self",
".",... | Shutdown multicast socket
:rtype: None | [
"Shutdown",
"multicast",
"socket"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L314-L324 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer._add_membership_multicast_socket | def _add_membership_multicast_socket(self):
"""
Make membership request to multicast
:rtype: None
"""
self._membership_request = socket.inet_aton(self._multicast_group) \
+ socket.inet_aton(self._multicast_ip)
# Send add membership request to socket
... | python | def _add_membership_multicast_socket(self):
"""
Make membership request to multicast
:rtype: None
"""
self._membership_request = socket.inet_aton(self._multicast_group) \
+ socket.inet_aton(self._multicast_ip)
# Send add membership request to socket
... | [
"def",
"_add_membership_multicast_socket",
"(",
"self",
")",
":",
"self",
".",
"_membership_request",
"=",
"socket",
".",
"inet_aton",
"(",
"self",
".",
"_multicast_group",
")",
"+",
"socket",
".",
"inet_aton",
"(",
"self",
".",
"_multicast_ip",
")",
"# Send add... | Make membership request to multicast
:rtype: None | [
"Make",
"membership",
"request",
"to",
"multicast"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L326-L342 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer._drop_membership_multicast_socket | def _drop_membership_multicast_socket(self):
"""
Drop membership to multicast
:rtype: None
"""
# Leave group
self._multicast_socket.setsockopt(
socket.IPPROTO_IP,
socket.IP_DROP_MEMBERSHIP,
self._membership_request
)
se... | python | def _drop_membership_multicast_socket(self):
"""
Drop membership to multicast
:rtype: None
"""
# Leave group
self._multicast_socket.setsockopt(
socket.IPPROTO_IP,
socket.IP_DROP_MEMBERSHIP,
self._membership_request
)
se... | [
"def",
"_drop_membership_multicast_socket",
"(",
"self",
")",
":",
"# Leave group",
"self",
".",
"_multicast_socket",
".",
"setsockopt",
"(",
"socket",
".",
"IPPROTO_IP",
",",
"socket",
".",
"IP_DROP_MEMBERSHIP",
",",
"self",
".",
"_membership_request",
")",
"self",... | Drop membership to multicast
:rtype: None | [
"Drop",
"membership",
"to",
"multicast"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L344-L356 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer.start | def start(self, blocking=False):
"""
Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
:raises SensorStartException: Failed to start
"""
self.debug("()")
... | python | def start(self, blocking=False):
"""
Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
:raises SensorStartException: Failed to start
"""
self.debug("()")
... | [
"def",
"start",
"(",
"self",
",",
"blocking",
"=",
"False",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"try",
":",
"self",
".",
"_init_multicast_socket",
"(",
")",
"except",
":",
"self",
".",
"_multicast_socket",
"=",
"None",
"self",
".",
"exc... | Start the interface
:param blocking: Should the call block until stop() is called
(default: False)
:type blocking: bool
:rtype: None
:raises SensorStartException: Failed to start | [
"Start",
"the",
"interface"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L358-L390 |
the01/python-paps | paps/si/app/sensorServer.py | SensorServer.stop | def stop(self):
"""
Stop the sensor server (soft stop - signal packet loop to stop)
Warning: Is non blocking (server might still do something after this!)
:rtype: None
"""
self.debug("()")
super(SensorServer, self).stop()
# No new clients
if self.... | python | def stop(self):
"""
Stop the sensor server (soft stop - signal packet loop to stop)
Warning: Is non blocking (server might still do something after this!)
:rtype: None
"""
self.debug("()")
super(SensorServer, self).stop()
# No new clients
if self.... | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"debug",
"(",
"\"()\"",
")",
"super",
"(",
"SensorServer",
",",
"self",
")",
".",
"stop",
"(",
")",
"# No new clients",
"if",
"self",
".",
"_multicast_socket",
"is",
"not",
"None",
":",
"self",
".",
... | Stop the sensor server (soft stop - signal packet loop to stop)
Warning: Is non blocking (server might still do something after this!)
:rtype: None | [
"Stop",
"the",
"sensor",
"server",
"(",
"soft",
"stop",
"-",
"signal",
"packet",
"loop",
"to",
"stop",
")",
"Warning",
":",
"Is",
"non",
"blocking",
"(",
"server",
"might",
"still",
"do",
"something",
"after",
"this!",
")"
] | train | https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensorServer.py#L392-L405 |
ludwiktrammer/applamp | applamp/rgb.py | RgbLight.fade_out | def fade_out(self, duration=3):
"""Turns off the light by gradually fading it out.
The optional `duration` parameter allows for control
of the fade out duration (in seconds)"""
super(RgbLight, self).fade_out(duration)
self.off() | python | def fade_out(self, duration=3):
"""Turns off the light by gradually fading it out.
The optional `duration` parameter allows for control
of the fade out duration (in seconds)"""
super(RgbLight, self).fade_out(duration)
self.off() | [
"def",
"fade_out",
"(",
"self",
",",
"duration",
"=",
"3",
")",
":",
"super",
"(",
"RgbLight",
",",
"self",
")",
".",
"fade_out",
"(",
"duration",
")",
"self",
".",
"off",
"(",
")"
] | Turns off the light by gradually fading it out.
The optional `duration` parameter allows for control
of the fade out duration (in seconds) | [
"Turns",
"off",
"the",
"light",
"by",
"gradually",
"fading",
"it",
"out",
".",
"The",
"optional",
"duration",
"parameter",
"allows",
"for",
"control",
"of",
"the",
"fade",
"out",
"duration",
"(",
"in",
"seconds",
")"
] | train | https://github.com/ludwiktrammer/applamp/blob/90d7d463826f0c8dcd33dfdbc5efc9fa44b0b484/applamp/rgb.py#L51-L56 |
racker/torment | torment/helpers.py | evert | def evert(iterable: Iterable[Dict[str, Tuple]]) -> Iterable[Iterable[Dict[str, Any]]]:
'''Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ... | python | def evert(iterable: Iterable[Dict[str, Tuple]]) -> Iterable[Iterable[Dict[str, Any]]]:
'''Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ... | [
"def",
"evert",
"(",
"iterable",
":",
"Iterable",
"[",
"Dict",
"[",
"str",
",",
"Tuple",
"]",
"]",
")",
"->",
"Iterable",
"[",
"Iterable",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"]",
":",
"keys",
"=",
"list",
"(",
"itertools",
".",
"chain... | Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ]``
The resulting iterable contains the same number of tuples as the
initial iterable... | [
"Evert",
"dictionaries",
"with",
"tuples",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L32-L63 |
racker/torment | torment/helpers.py | extend | def extend(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Extend base by updating with the extension.
**Arguments**
:``base``: dictionary to have keys updated or added
:``extension``: dictionary to update base with
**Return Value(s)**
Resulting dictionary from up... | python | def extend(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Extend base by updating with the extension.
**Arguments**
:``base``: dictionary to have keys updated or added
:``extension``: dictionary to update base with
**Return Value(s)**
Resulting dictionary from up... | [
"def",
"extend",
"(",
"base",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
",",
"extension",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"Any",
",",
"Any",
"]",
":",
"_",
"=",
"copy",
".",
"deepcopy",
"(",
"base",
")",
"_",... | Extend base by updating with the extension.
**Arguments**
:``base``: dictionary to have keys updated or added
:``extension``: dictionary to update base with
**Return Value(s)**
Resulting dictionary from updating base with extension. | [
"Extend",
"base",
"by",
"updating",
"with",
"the",
"extension",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L66-L83 |
racker/torment | torment/helpers.py | merge | def merge(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Merge extension into base recursively.
**Argumetnts**
:``base``: dictionary to overlay values onto
:``extension``: dictionary to overlay with
**Return Value(s)**
Resulting dictionary from overlaying extensi... | python | def merge(base: Dict[Any, Any], extension: Dict[Any, Any]) -> Dict[Any, Any]:
'''Merge extension into base recursively.
**Argumetnts**
:``base``: dictionary to overlay values onto
:``extension``: dictionary to overlay with
**Return Value(s)**
Resulting dictionary from overlaying extensi... | [
"def",
"merge",
"(",
"base",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
",",
"extension",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"Any",
",",
"Any",
"]",
":",
"_",
"=",
"copy",
".",
"deepcopy",
"(",
"base",
")",
"for"... | Merge extension into base recursively.
**Argumetnts**
:``base``: dictionary to overlay values onto
:``extension``: dictionary to overlay with
**Return Value(s)**
Resulting dictionary from overlaying extension on base. | [
"Merge",
"extension",
"into",
"base",
"recursively",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L86-L108 |
racker/torment | torment/helpers.py | import_directory | def import_directory(module_basename: str, directory: str, sort_key = None) -> None:
'''Load all python modules in directory and directory's children.
Parameters
----------
:``module_basename``: module name prefix for loaded modules
:``directory``: directory to load python modules from
:... | python | def import_directory(module_basename: str, directory: str, sort_key = None) -> None:
'''Load all python modules in directory and directory's children.
Parameters
----------
:``module_basename``: module name prefix for loaded modules
:``directory``: directory to load python modules from
:... | [
"def",
"import_directory",
"(",
"module_basename",
":",
"str",
",",
"directory",
":",
"str",
",",
"sort_key",
"=",
"None",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"'loading submodules of %s'",
",",
"module_basename",
")",
"logger",
".",
"info",
"... | Load all python modules in directory and directory's children.
Parameters
----------
:``module_basename``: module name prefix for loaded modules
:``directory``: directory to load python modules from
:``sort_key``: function to sort module names with before loading | [
"Load",
"all",
"python",
"modules",
"in",
"directory",
"and",
"directory",
"s",
"children",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L112-L137 |
racker/torment | torment/helpers.py | _filenames_to_modulenames | def _filenames_to_modulenames(filenames: Iterable[str], modulename_prefix: str, filename_prefix: str = '') -> Iterable[str]:
'''Convert given filenames to module names.
Any filename that does not have a corresponding module name will be dropped
from the result (i.e. __init__.py).
Parameters
------... | python | def _filenames_to_modulenames(filenames: Iterable[str], modulename_prefix: str, filename_prefix: str = '') -> Iterable[str]:
'''Convert given filenames to module names.
Any filename that does not have a corresponding module name will be dropped
from the result (i.e. __init__.py).
Parameters
------... | [
"def",
"_filenames_to_modulenames",
"(",
"filenames",
":",
"Iterable",
"[",
"str",
"]",
",",
"modulename_prefix",
":",
"str",
",",
"filename_prefix",
":",
"str",
"=",
"''",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"modulenames",
"=",
"[",
"]",
"# type:... | Convert given filenames to module names.
Any filename that does not have a corresponding module name will be dropped
from the result (i.e. __init__.py).
Parameters
----------
:``filename_prefix``: a prefix to drop from all filenames (typically a
common directory); de... | [
"Convert",
"given",
"filenames",
"to",
"module",
"names",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/helpers.py#L158-L208 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.