repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
developmentseed/sentinel-s3
sentinel_s3/crawler.py
get_product_metadata_path
def get_product_metadata_path(product_name): """ gets a single products metadata """ string_date = product_name.split('_')[-1] date = datetime.datetime.strptime(string_date, '%Y%m%dT%H%M%S') path = 'products/{0}/{1}/{2}/{3}'.format(date.year, date.month, date.day, product_name) return { pr...
python
def get_product_metadata_path(product_name): """ gets a single products metadata """ string_date = product_name.split('_')[-1] date = datetime.datetime.strptime(string_date, '%Y%m%dT%H%M%S') path = 'products/{0}/{1}/{2}/{3}'.format(date.year, date.month, date.day, product_name) return { pr...
[ "def", "get_product_metadata_path", "(", "product_name", ")", ":", "string_date", "=", "product_name", ".", "split", "(", "'_'", ")", "[", "-", "1", "]", "date", "=", "datetime", ".", "datetime", ".", "strptime", "(", "string_date", ",", "'%Y%m%dT%H%M%S'", "...
gets a single products metadata
[ "gets", "a", "single", "products", "metadata" ]
02bf2f9cb6aff527e492b39518a54f0b4613ddda
https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/crawler.py#L24-L36
train
gets a single product metadata
developmentseed/sentinel-s3
sentinel_s3/crawler.py
get_products_metadata_path
def get_products_metadata_path(year, month, day): """ Get paths to multiple products metadata """ products = {} path = 'products/{0}/{1}/{2}/'.format(year, month, day) for key in bucket.objects.filter(Prefix=path): product_path = key.key.replace(path, '').split('/') name = product_path[...
python
def get_products_metadata_path(year, month, day): """ Get paths to multiple products metadata """ products = {} path = 'products/{0}/{1}/{2}/'.format(year, month, day) for key in bucket.objects.filter(Prefix=path): product_path = key.key.replace(path, '').split('/') name = product_path[...
[ "def", "get_products_metadata_path", "(", "year", ",", "month", ",", "day", ")", ":", "products", "=", "{", "}", "path", "=", "'products/{0}/{1}/{2}/'", ".", "format", "(", "year", ",", "month", ",", "day", ")", "for", "key", "in", "bucket", ".", "object...
Get paths to multiple products metadata
[ "Get", "paths", "to", "multiple", "products", "metadata" ]
02bf2f9cb6aff527e492b39518a54f0b4613ddda
https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/crawler.py#L39-L56
train
Get paths to multiple products metadata
ioos/pyoos
pyoos/collectors/ioos/swe_sos.py
IoosSweSos.metadata
def metadata( self, output_format=None, feature_name_callback=None, **kwargs ): """ Gets SensorML objects for all procedures in your filtered features. You should override the default output_format for servers that do not respond properly. """ callback = feat...
python
def metadata( self, output_format=None, feature_name_callback=None, **kwargs ): """ Gets SensorML objects for all procedures in your filtered features. You should override the default output_format for servers that do not respond properly. """ callback = feat...
[ "def", "metadata", "(", "self", ",", "output_format", "=", "None", ",", "feature_name_callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "callback", "=", "feature_name_callback", "or", "str", "if", "output_format", "is", "None", ":", "output_format", ...
Gets SensorML objects for all procedures in your filtered features. You should override the default output_format for servers that do not respond properly.
[ "Gets", "SensorML", "objects", "for", "all", "procedures", "in", "your", "filtered", "features", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/ioos/swe_sos.py#L18-L48
train
Gets SensorML objects for all procedures in your filtered features.
ioos/pyoos
pyoos/collectors/ioos/swe_sos.py
IoosSweSos.metadata_plus_exceptions
def metadata_plus_exceptions( self, output_format=None, feature_name_callback=None, **kwargs ): """ Gets SensorML objects for all procedures in your filtered features. Return two dictionaries for service responses keyed by 'feature': responses: values are SOS DescribeSen...
python
def metadata_plus_exceptions( self, output_format=None, feature_name_callback=None, **kwargs ): """ Gets SensorML objects for all procedures in your filtered features. Return two dictionaries for service responses keyed by 'feature': responses: values are SOS DescribeSen...
[ "def", "metadata_plus_exceptions", "(", "self", ",", "output_format", "=", "None", ",", "feature_name_callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "callback", "=", "feature_name_callback", "or", "str", "if", "output_format", "is", "None", ":", "o...
Gets SensorML objects for all procedures in your filtered features. Return two dictionaries for service responses keyed by 'feature': responses: values are SOS DescribeSensor response text response_failures: values are exception text content furnished from ServiceException, ExceptionRep...
[ "Gets", "SensorML", "objects", "for", "all", "procedures", "in", "your", "filtered", "features", "." ]
908660385029ecd8eccda8ab3a6b20b47b915c77
https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/collectors/ioos/swe_sos.py#L50-L87
train
Returns two dictionaries for all services and their associated responses and responses with exception text content furnished from ServiceException and ExceptionReport objects.
PrefPy/prefpy
prefpy/gmm_mixpl_objectives.py
uncons_term
def uncons_term(params, c): """ Description: Computes an additional value for the objective function value when used in an unconstrained optimization formulation. Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) c: constant multiplie...
python
def uncons_term(params, c): """ Description: Computes an additional value for the objective function value when used in an unconstrained optimization formulation. Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) c: constant multiplie...
[ "def", "uncons_term", "(", "params", ",", "c", ")", ":", "return", "(", "c", "*", "(", "(", "np", ".", "sum", "(", "params", "[", "1", ":", "5", "]", ")", "-", "1", ")", "**", "2", ")", ")", "+", "(", "c", "*", "(", "(", "np", ".", "sum...
Description: Computes an additional value for the objective function value when used in an unconstrained optimization formulation. Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) c: constant multiplier scaling factor of the returned term
[ "Description", ":", "Computes", "an", "additional", "value", "for", "the", "objective", "function", "value", "when", "used", "in", "an", "unconstrained", "optimization", "formulation", ".", "Parameters", ":", "params", ":", "all", "parameters", "for", "the", "Pl...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/gmm_mixpl_objectives.py#L12-L21
train
Returns the term that is used in an unconstrained optimization formulation.
PrefPy/prefpy
prefpy/gmm_mixpl_objectives.py
top2_reduced
def top2_reduced(params, moments): """ Description: Top 2 alternatives 12 moment conditions objective function Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) moments: values of the moment conditions from the data (numpy ndarray) """ pa...
python
def top2_reduced(params, moments): """ Description: Top 2 alternatives 12 moment conditions objective function Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) moments: values of the moment conditions from the data (numpy ndarray) """ pa...
[ "def", "top2_reduced", "(", "params", ",", "moments", ")", ":", "params", "=", "np", ".", "asarray", "(", "params", ")", "alpha", "=", "params", "[", "0", "]", "a", "=", "params", "[", "1", ":", "5", "]", "b", "=", "params", "[", "5", ":", "]",...
Description: Top 2 alternatives 12 moment conditions objective function Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) moments: values of the moment conditions from the data (numpy ndarray)
[ "Description", ":", "Top", "2", "alternatives", "12", "moment", "conditions", "objective", "function", "Parameters", ":", "params", ":", "all", "parameters", "for", "the", "Plackett", "-", "Luce", "mixture", "model", "(", "numpy", "ndarray", ")", "moments", ":...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/gmm_mixpl_objectives.py#L23-L42
train
This function calculates the top 2 reduced probability of the model.
PrefPy/prefpy
prefpy/gmm_mixpl_objectives.py
top3_reduced
def top3_reduced(params, moments): """ Description: Top 3 alternatives 16 moment conditions objective function Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) moments: values of the moment conditions from the data (numpy ndarray) """ pa...
python
def top3_reduced(params, moments): """ Description: Top 3 alternatives 16 moment conditions objective function Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) moments: values of the moment conditions from the data (numpy ndarray) """ pa...
[ "def", "top3_reduced", "(", "params", ",", "moments", ")", ":", "params", "=", "np", ".", "asarray", "(", "params", ")", "alpha", "=", "params", "[", "0", "]", "a", "=", "params", "[", "1", ":", "5", "]", "b", "=", "params", "[", "5", ":", "]",...
Description: Top 3 alternatives 16 moment conditions objective function Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) moments: values of the moment conditions from the data (numpy ndarray)
[ "Description", ":", "Top", "3", "alternatives", "16", "moment", "conditions", "objective", "function", "Parameters", ":", "params", ":", "all", "parameters", "for", "the", "Plackett", "-", "Luce", "mixture", "model", "(", "numpy", "ndarray", ")", "moments", ":...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/gmm_mixpl_objectives.py#L91-L116
train
This function calculates the top 3 reduced objective function for the given set of parameters.
PrefPy/prefpy
prefpy/gmm_mixpl_objectives.py
top3_full
def top3_full(params, moments): """ Description: Top m - 1 alternatives m(m - 1) + 2m moment conditions objective function Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) moments: values of the moment conditions from the data (numpy ndarray) ...
python
def top3_full(params, moments): """ Description: Top m - 1 alternatives m(m - 1) + 2m moment conditions objective function Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) moments: values of the moment conditions from the data (numpy ndarray) ...
[ "def", "top3_full", "(", "params", ",", "moments", ")", ":", "#variables", "params", "=", "np", ".", "asarray", "(", "params", ")", "#convert numpy matrix to list", "alpha", "=", "params", "[", "0", "]", "#first parameter is the alpha value", "half", "=", "int",...
Description: Top m - 1 alternatives m(m - 1) + 2m moment conditions objective function Parameters: params: all parameters for the Plackett-Luce mixture model (numpy ndarray) moments: values of the moment conditions from the data (numpy ndarray)
[ "Description", ":", "Top", "m", "-", "1", "alternatives", "m", "(", "m", "-", "1", ")", "+", "2m", "moment", "conditions", "objective", "function", "Parameters", ":", "params", ":", "all", "parameters", "for", "the", "Plackett", "-", "Luce", "mixture", "...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/gmm_mixpl_objectives.py#L131-L182
train
This function is used to compute the top 3 of the Plackett - Luce mixture model for a given set of parameters.
astooke/gtimer
gtimer/public/timer.py
start
def start(backdate=None): """ Mark the start of timing, overwriting the automatic start data written on import, or the automatic start at the beginning of a subdivision. Notes: Backdating: For subdivisions only. Backdate time must be in the past but more recent than the latest stamp in...
python
def start(backdate=None): """ Mark the start of timing, overwriting the automatic start data written on import, or the automatic start at the beginning of a subdivision. Notes: Backdating: For subdivisions only. Backdate time must be in the past but more recent than the latest stamp in...
[ "def", "start", "(", "backdate", "=", "None", ")", ":", "if", "f", ".", "s", ".", "cum", ":", "raise", "StartError", "(", "\"Already have stamps, can't start again (must reset).\"", ")", "if", "f", ".", "t", ".", "subdvsn_awaiting", "or", "f", ".", "t", "....
Mark the start of timing, overwriting the automatic start data written on import, or the automatic start at the beginning of a subdivision. Notes: Backdating: For subdivisions only. Backdate time must be in the past but more recent than the latest stamp in the parent timer. Args: ...
[ "Mark", "the", "start", "of", "timing", "overwriting", "the", "automatic", "start", "data", "written", "on", "import", "or", "the", "automatic", "start", "at", "the", "beginning", "of", "a", "subdivision", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L40-L85
train
Start a new subdivision.
astooke/gtimer
gtimer/public/timer.py
stamp
def stamp(name, backdate=None, unique=None, keep_subdivisions=None, quick_print=None, un=None, ks=None, qp=None): """ Mark the end of a timing interval. Notes: If keeping subdivisions, each subdivision currently awaiting assignment to a stamp (i.e. ended since the last s...
python
def stamp(name, backdate=None, unique=None, keep_subdivisions=None, quick_print=None, un=None, ks=None, qp=None): """ Mark the end of a timing interval. Notes: If keeping subdivisions, each subdivision currently awaiting assignment to a stamp (i.e. ended since the last s...
[ "def", "stamp", "(", "name", ",", "backdate", "=", "None", ",", "unique", "=", "None", ",", "keep_subdivisions", "=", "None", ",", "quick_print", "=", "None", ",", "un", "=", "None", ",", "ks", "=", "None", ",", "qp", "=", "None", ")", ":", "t", ...
Mark the end of a timing interval. Notes: If keeping subdivisions, each subdivision currently awaiting assignment to a stamp (i.e. ended since the last stamp in this level) will be assigned to this one. Otherwise, all awaiting ones will be discarded after aggregating their self tim...
[ "Mark", "the", "end", "of", "a", "timing", "interval", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L88-L155
train
This function is used to mark a new time for a given time interval.
astooke/gtimer
gtimer/public/timer.py
stop
def stop(name=None, backdate=None, unique=None, keep_subdivisions=None, quick_print=None, un=None, ks=None, qp=None): """ Mark the end of timing. Optionally performs a stamp, hence accepts the same arguments. Notes: If keeping subdivisions and not calling a stamp, any awaitin...
python
def stop(name=None, backdate=None, unique=None, keep_subdivisions=None, quick_print=None, un=None, ks=None, qp=None): """ Mark the end of timing. Optionally performs a stamp, hence accepts the same arguments. Notes: If keeping subdivisions and not calling a stamp, any awaitin...
[ "def", "stop", "(", "name", "=", "None", ",", "backdate", "=", "None", ",", "unique", "=", "None", ",", "keep_subdivisions", "=", "None", ",", "quick_print", "=", "None", ",", "un", "=", "None", ",", "ks", "=", "None", ",", "qp", "=", "None", ")", ...
Mark the end of timing. Optionally performs a stamp, hence accepts the same arguments. Notes: If keeping subdivisions and not calling a stamp, any awaiting subdivisions will be assigned to a special 'UNASSIGNED' position to indicate that they are not properly accounted for in the hiera...
[ "Mark", "the", "end", "of", "timing", ".", "Optionally", "performs", "a", "stamp", "hence", "accepts", "the", "same", "arguments", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L158-L231
train
Stop a timer.
astooke/gtimer
gtimer/public/timer.py
pause
def pause(): """ Pause the timer, preventing subsequent time from accumulating in the total. Renders the timer inactive, disabling other timing commands. Returns: float: The current time. Raises: PausedError: If timer already paused. StoppedError: If timer already stopped....
python
def pause(): """ Pause the timer, preventing subsequent time from accumulating in the total. Renders the timer inactive, disabling other timing commands. Returns: float: The current time. Raises: PausedError: If timer already paused. StoppedError: If timer already stopped....
[ "def", "pause", "(", ")", ":", "t", "=", "timer", "(", ")", "if", "f", ".", "t", ".", "stopped", ":", "raise", "StoppedError", "(", "\"Cannot pause stopped timer.\"", ")", "if", "f", ".", "t", ".", "paused", ":", "raise", "PausedError", "(", "\"Timer a...
Pause the timer, preventing subsequent time from accumulating in the total. Renders the timer inactive, disabling other timing commands. Returns: float: The current time. Raises: PausedError: If timer already paused. StoppedError: If timer already stopped.
[ "Pause", "the", "timer", "preventing", "subsequent", "time", "from", "accumulating", "in", "the", "total", ".", "Renders", "the", "timer", "inactive", "disabling", "other", "timing", "commands", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L234-L255
train
Pause the timer preventing subsequent time from accumulating in the the total.
astooke/gtimer
gtimer/public/timer.py
resume
def resume(): """ Resume a paused timer, re-activating it. Subsequent time accumulates in the total. Returns: float: The current time. Raises: PausedError: If timer was not in paused state. StoppedError: If timer was already stopped. """ t = timer() if f.t.stop...
python
def resume(): """ Resume a paused timer, re-activating it. Subsequent time accumulates in the total. Returns: float: The current time. Raises: PausedError: If timer was not in paused state. StoppedError: If timer was already stopped. """ t = timer() if f.t.stop...
[ "def", "resume", "(", ")", ":", "t", "=", "timer", "(", ")", "if", "f", ".", "t", ".", "stopped", ":", "raise", "StoppedError", "(", "\"Cannot resume stopped timer.\"", ")", "if", "not", "f", ".", "t", ".", "paused", ":", "raise", "PausedError", "(", ...
Resume a paused timer, re-activating it. Subsequent time accumulates in the total. Returns: float: The current time. Raises: PausedError: If timer was not in paused state. StoppedError: If timer was already stopped.
[ "Resume", "a", "paused", "timer", "re", "-", "activating", "it", ".", "Subsequent", "time", "accumulates", "in", "the", "total", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L258-L278
train
Resume a paused timer re - activating it.
astooke/gtimer
gtimer/public/timer.py
blank_stamp
def blank_stamp(name=None, backdate=None, unique=None, keep_subdivisions=False, quick_print=None, un=None, ks=False, qp=None): """ Mark the beginning of a new interval, but the elapsed time of the previous interval is discarded. Intentionally the same signature as stamp(...
python
def blank_stamp(name=None, backdate=None, unique=None, keep_subdivisions=False, quick_print=None, un=None, ks=False, qp=None): """ Mark the beginning of a new interval, but the elapsed time of the previous interval is discarded. Intentionally the same signature as stamp(...
[ "def", "blank_stamp", "(", "name", "=", "None", ",", "backdate", "=", "None", ",", "unique", "=", "None", ",", "keep_subdivisions", "=", "False", ",", "quick_print", "=", "None", ",", "un", "=", "None", ",", "ks", "=", "False", ",", "qp", "=", "None"...
Mark the beginning of a new interval, but the elapsed time of the previous interval is discarded. Intentionally the same signature as stamp(). Notes: The default for keep_subdivisions is False (does not refer to an adjustable global setting), meaning that any subdivisons awaiting would be ...
[ "Mark", "the", "beginning", "of", "a", "new", "interval", "but", "the", "elapsed", "time", "of", "the", "previous", "interval", "is", "discarded", ".", "Intentionally", "the", "same", "signature", "as", "stamp", "()", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L281-L319
train
Blanks the current time of a new interval.
astooke/gtimer
gtimer/public/timer.py
reset
def reset(): """ Reset the timer at the current level in the hierarchy (i.e. might or might not be the root). Notes: Erases timing data but preserves relationship to the hierarchy. If the current timer level was not previously stopped, any timing data from this timer (including...
python
def reset(): """ Reset the timer at the current level in the hierarchy (i.e. might or might not be the root). Notes: Erases timing data but preserves relationship to the hierarchy. If the current timer level was not previously stopped, any timing data from this timer (including...
[ "def", "reset", "(", ")", ":", "if", "f", ".", "t", ".", "in_loop", ":", "raise", "LoopError", "(", "\"Cannot reset a timer while it is in timed loop.\"", ")", "f", ".", "t", ".", "reset", "(", ")", "f", ".", "refresh_shortcuts", "(", ")", "return", "f", ...
Reset the timer at the current level in the hierarchy (i.e. might or might not be the root). Notes: Erases timing data but preserves relationship to the hierarchy. If the current timer level was not previously stopped, any timing data from this timer (including subdivisions) will be di...
[ "Reset", "the", "timer", "at", "the", "current", "level", "in", "the", "hierarchy", "(", "i", ".", "e", ".", "might", "or", "might", "not", "be", "the", "root", ")", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L322-L344
train
Reset the timer at the current level in the hierarchy.
astooke/gtimer
gtimer/public/timer.py
wrap
def wrap(func, subdivide=True, name=None, rgstr_stamps=None, save_itrs=None): """ Decorator function which can automatically induce a subdivision on entering a subfunction or method. Can be used (as @gtimer.wrap) with or without any arguments. Notes: If subdivide is False, then the wrapper...
python
def wrap(func, subdivide=True, name=None, rgstr_stamps=None, save_itrs=None): """ Decorator function which can automatically induce a subdivision on entering a subfunction or method. Can be used (as @gtimer.wrap) with or without any arguments. Notes: If subdivide is False, then the wrapper...
[ "def", "wrap", "(", "func", ",", "subdivide", "=", "True", ",", "name", "=", "None", ",", "rgstr_stamps", "=", "None", ",", "save_itrs", "=", "None", ")", ":", "subdivision", "=", "bool", "(", "subdivide", ")", "if", "subdivision", ":", "name", "=", ...
Decorator function which can automatically induce a subdivision on entering a subfunction or method. Can be used (as @gtimer.wrap) with or without any arguments. Notes: If subdivide is False, then the wrapper does nothing but return the provided function. If a name is not provided...
[ "Decorator", "function", "which", "can", "automatically", "induce", "a", "subdivision", "on", "entering", "a", "subfunction", "or", "method", ".", "Can", "be", "used", "(", "as", "@gtimer", ".", "wrap", ")", "with", "or", "without", "any", "arguments", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L364-L405
train
Decorator for creating a new function or method with timing hierarchy management.
astooke/gtimer
gtimer/public/timer.py
subdivide
def subdivide(name, rgstr_stamps=None, save_itrs=SET['SI']): """ Induce a new subdivision--a lower level in the timing hierarchy. Subsequent calls to methods like stamp() operate on this new level. Notes: If rgstr_stamps is used, the collection is passed through set() for uniqueness, an...
python
def subdivide(name, rgstr_stamps=None, save_itrs=SET['SI']): """ Induce a new subdivision--a lower level in the timing hierarchy. Subsequent calls to methods like stamp() operate on this new level. Notes: If rgstr_stamps is used, the collection is passed through set() for uniqueness, an...
[ "def", "subdivide", "(", "name", ",", "rgstr_stamps", "=", "None", ",", "save_itrs", "=", "SET", "[", "'SI'", "]", ")", ":", "_auto_subdivide", "(", "name", ",", "rgstr_stamps", ",", "save_itrs", ")", "f", ".", "t", ".", "is_user_subdvsn", "=", "True" ]
Induce a new subdivision--a lower level in the timing hierarchy. Subsequent calls to methods like stamp() operate on this new level. Notes: If rgstr_stamps is used, the collection is passed through set() for uniqueness, and the each entry is passed through str(). Any identifiers contai...
[ "Induce", "a", "new", "subdivision", "--", "a", "lower", "level", "in", "the", "timing", "hierarchy", ".", "Subsequent", "calls", "to", "methods", "like", "stamp", "()", "operate", "on", "this", "new", "level", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L408-L440
train
Induce a new subdivision of a timer.
astooke/gtimer
gtimer/public/timer.py
end_subdivision
def end_subdivision(): """ End a user-induced timing subdivision, returning the previous level in the timing hierarchy as the target of timing commands such as stamp(). Includes a call to stop(); a previous call to stop() is OK. Returns: None Raises: GTimerError: If current sub...
python
def end_subdivision(): """ End a user-induced timing subdivision, returning the previous level in the timing hierarchy as the target of timing commands such as stamp(). Includes a call to stop(); a previous call to stop() is OK. Returns: None Raises: GTimerError: If current sub...
[ "def", "end_subdivision", "(", ")", ":", "if", "not", "f", ".", "t", ".", "is_user_subdvsn", ":", "raise", "GTimerError", "(", "'Attempted to end a subdivision not started by user.'", ")", "if", "f", ".", "t", ".", "in_loop", ":", "raise", "LoopError", "(", "'...
End a user-induced timing subdivision, returning the previous level in the timing hierarchy as the target of timing commands such as stamp(). Includes a call to stop(); a previous call to stop() is OK. Returns: None Raises: GTimerError: If current subdivision was not induced by user. ...
[ "End", "a", "user", "-", "induced", "timing", "subdivision", "returning", "the", "previous", "level", "in", "the", "timing", "hierarchy", "as", "the", "target", "of", "timing", "commands", "such", "as", "stamp", "()", ".", "Includes", "a", "call", "to", "s...
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L443-L460
train
End a user - induced timing subdivision.
astooke/gtimer
gtimer/public/timer.py
rename_root
def rename_root(name): """ Rename the root timer (regardless of current timing level). Args: name (any): Identifier, passed through str() Returns: str: Implemented identifier. """ name = str(name) f.root.name = name f.root.times.name = name return name
python
def rename_root(name): """ Rename the root timer (regardless of current timing level). Args: name (any): Identifier, passed through str() Returns: str: Implemented identifier. """ name = str(name) f.root.name = name f.root.times.name = name return name
[ "def", "rename_root", "(", "name", ")", ":", "name", "=", "str", "(", "name", ")", "f", ".", "root", ".", "name", "=", "name", "f", ".", "root", ".", "times", ".", "name", "=", "name", "return", "name" ]
Rename the root timer (regardless of current timing level). Args: name (any): Identifier, passed through str() Returns: str: Implemented identifier.
[ "Rename", "the", "root", "timer", "(", "regardless", "of", "current", "timing", "level", ")", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L468-L481
train
Rename the root timer.
astooke/gtimer
gtimer/public/timer.py
set_save_itrs_root
def set_save_itrs_root(setting): """ Adjust the root timer save_itrs setting, such as for use in multiprocessing, when a root timer may become a parallel subdivision (see subdivide()). Args: setting (bool): Save individual iterations data, passed through bool() Returns: bool: I...
python
def set_save_itrs_root(setting): """ Adjust the root timer save_itrs setting, such as for use in multiprocessing, when a root timer may become a parallel subdivision (see subdivide()). Args: setting (bool): Save individual iterations data, passed through bool() Returns: bool: I...
[ "def", "set_save_itrs_root", "(", "setting", ")", ":", "setting", "=", "bool", "(", "setting", ")", "f", ".", "root", ".", "times", ".", "save_itrs", "=", "setting", "return", "setting" ]
Adjust the root timer save_itrs setting, such as for use in multiprocessing, when a root timer may become a parallel subdivision (see subdivide()). Args: setting (bool): Save individual iterations data, passed through bool() Returns: bool: Implemented setting value.
[ "Adjust", "the", "root", "timer", "save_itrs", "setting", "such", "as", "for", "use", "in", "multiprocessing", "when", "a", "root", "timer", "may", "become", "a", "parallel", "subdivision", "(", "see", "subdivide", "()", ")", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L484-L498
train
Adjust the root timer save_itrs setting such as for use in a parallel subdivision.
astooke/gtimer
gtimer/public/timer.py
rgstr_stamps_root
def rgstr_stamps_root(rgstr_stamps): """ Register stamps with the root timer (see subdivision()). Args: rgstr_stamps (list, tuple): Collection of identifiers, passed through set(), then each is passed through str(). Returns: list: Implemented registered stamp collection. ...
python
def rgstr_stamps_root(rgstr_stamps): """ Register stamps with the root timer (see subdivision()). Args: rgstr_stamps (list, tuple): Collection of identifiers, passed through set(), then each is passed through str(). Returns: list: Implemented registered stamp collection. ...
[ "def", "rgstr_stamps_root", "(", "rgstr_stamps", ")", ":", "rgstr_stamps", "=", "sanitize_rgstr_stamps", "(", "rgstr_stamps", ")", "f", ".", "root", ".", "rgstr_stamps", "=", "rgstr_stamps", "return", "rgstr_stamps" ]
Register stamps with the root timer (see subdivision()). Args: rgstr_stamps (list, tuple): Collection of identifiers, passed through set(), then each is passed through str(). Returns: list: Implemented registered stamp collection.
[ "Register", "stamps", "with", "the", "root", "timer", "(", "see", "subdivision", "()", ")", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L501-L514
train
Registers stamps with the root timer.
astooke/gtimer
gtimer/public/timer.py
get_active_lineage
def get_active_lineage(): """ Query the lineage of the current timer level. Provides only timer names, not stamp names (as these have not been decided yet!). Returns: str: Formatted sequence of timer names in one string. """ lin_str = '' for active_timer in f.timer_stack: l...
python
def get_active_lineage(): """ Query the lineage of the current timer level. Provides only timer names, not stamp names (as these have not been decided yet!). Returns: str: Formatted sequence of timer names in one string. """ lin_str = '' for active_timer in f.timer_stack: l...
[ "def", "get_active_lineage", "(", ")", ":", "lin_str", "=", "''", "for", "active_timer", "in", "f", ".", "timer_stack", ":", "lin_str", "+=", "\"{}-->\"", ".", "format", "(", "active_timer", ".", "name", ")", "try", ":", "return", "lin_str", "[", ":", "-...
Query the lineage of the current timer level. Provides only timer names, not stamp names (as these have not been decided yet!). Returns: str: Formatted sequence of timer names in one string.
[ "Query", "the", "lineage", "of", "the", "current", "timer", "level", ".", "Provides", "only", "timer", "names", "not", "stamp", "names", "(", "as", "these", "have", "not", "been", "decided", "yet!", ")", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L579-L593
train
Query the lineage of the current timer level.
PrefPy/prefpy
prefpy/plackettluce.py
_generate_pl_dataset
def _generate_pl_dataset(n, m, outfile, useDirichlet): """ Description: Generate a Plackett-Luce dataset and save it to disk. Parameters: n: number of votes to generate m: number of alternatives outfile: open file object to which the...
python
def _generate_pl_dataset(n, m, outfile, useDirichlet): """ Description: Generate a Plackett-Luce dataset and save it to disk. Parameters: n: number of votes to generate m: number of alternatives outfile: open file object to which the...
[ "def", "_generate_pl_dataset", "(", "n", ",", "m", ",", "outfile", ",", "useDirichlet", ")", ":", "gamma", ",", "votes", "=", "generate_pl_dataset", "(", "n", ",", "m", ",", "useDirichlet", ")", "outfile", ".", "write", "(", "str", "(", "len", "(", "ga...
Description: Generate a Plackett-Luce dataset and save it to disk. Parameters: n: number of votes to generate m: number of alternatives outfile: open file object to which the dataset is written useDirichlet: boolean flag to use the Di...
[ "Description", ":", "Generate", "a", "Plackett", "-", "Luce", "dataset", "and", "save", "it", "to", "disk", ".", "Parameters", ":", "n", ":", "number", "of", "votes", "to", "generate", "m", ":", "number", "of", "alternatives", "outfile", ":", "open", "fi...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/plackettluce.py#L10-L27
train
Generate a Plackett - Luce dataset and save it to disk.
PrefPy/prefpy
prefpy/plackettluce.py
generate_pl_dataset
def generate_pl_dataset(n, m, useDirichlet=True): """ Description: Generate a Plackett-Luce dataset and return the parameters and votes Parameters: n: number of votes to generate m: number of alternatives useDirichlet: boolean flag to use the Diri...
python
def generate_pl_dataset(n, m, useDirichlet=True): """ Description: Generate a Plackett-Luce dataset and return the parameters and votes Parameters: n: number of votes to generate m: number of alternatives useDirichlet: boolean flag to use the Diri...
[ "def", "generate_pl_dataset", "(", "n", ",", "m", ",", "useDirichlet", "=", "True", ")", ":", "gamma", "=", "None", "if", "useDirichlet", ":", "gamma", "=", "np", ".", "random", ".", "dirichlet", "(", "np", ".", "ones", "(", "m", ")", ")", "else", ...
Description: Generate a Plackett-Luce dataset and return the parameters and votes Parameters: n: number of votes to generate m: number of alternatives useDirichlet: boolean flag to use the Dirichlet distribution
[ "Description", ":", "Generate", "a", "Plackett", "-", "Luce", "dataset", "and", "return", "the", "parameters", "and", "votes", "Parameters", ":", "n", ":", "number", "of", "votes", "to", "generate", "m", ":", "number", "of", "alternatives", "useDirichlet", "...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/plackettluce.py#L29-L47
train
Generate a Plackett - Luce dataset and return the parameters and votes
PrefPy/prefpy
prefpy/plackettluce.py
read_pl_dataset
def read_pl_dataset(infile): """ Description: Read from disk a Plackett-Luce dataset. Parameters: infile: open file object from which to read the dataset """ m, n = [int(i) for i in infile.readline().split(',')] gamma = np.array([float(f) for f in infile.readline().spli...
python
def read_pl_dataset(infile): """ Description: Read from disk a Plackett-Luce dataset. Parameters: infile: open file object from which to read the dataset """ m, n = [int(i) for i in infile.readline().split(',')] gamma = np.array([float(f) for f in infile.readline().spli...
[ "def", "read_pl_dataset", "(", "infile", ")", ":", "m", ",", "n", "=", "[", "int", "(", "i", ")", "for", "i", "in", "infile", ".", "readline", "(", ")", ".", "split", "(", "','", ")", "]", "gamma", "=", "np", ".", "array", "(", "[", "float", ...
Description: Read from disk a Plackett-Luce dataset. Parameters: infile: open file object from which to read the dataset
[ "Description", ":", "Read", "from", "disk", "a", "Plackett", "-", "Luce", "dataset", ".", "Parameters", ":", "infile", ":", "open", "file", "object", "from", "which", "to", "read", "the", "dataset" ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/plackettluce.py#L49-L74
train
Reads from disk a Plackett - Luce dataset.
PrefPy/prefpy
prefpy/plackettluce.py
draw_pl_vote
def draw_pl_vote(m, gamma): """ Description: Generate a Plackett-Luce vote given the model parameters. Parameters: m: number of alternatives gamma: parameters of the Plackett-Luce model """ localgamma = np.copy(gamma) # work on a copy of gamma localalts = n...
python
def draw_pl_vote(m, gamma): """ Description: Generate a Plackett-Luce vote given the model parameters. Parameters: m: number of alternatives gamma: parameters of the Plackett-Luce model """ localgamma = np.copy(gamma) # work on a copy of gamma localalts = n...
[ "def", "draw_pl_vote", "(", "m", ",", "gamma", ")", ":", "localgamma", "=", "np", ".", "copy", "(", "gamma", ")", "# work on a copy of gamma\r", "localalts", "=", "np", ".", "arange", "(", "m", ")", "# enumeration of the candidates\r", "vote", "=", "[", "]",...
Description: Generate a Plackett-Luce vote given the model parameters. Parameters: m: number of alternatives gamma: parameters of the Plackett-Luce model
[ "Description", ":", "Generate", "a", "Plackett", "-", "Luce", "vote", "given", "the", "model", "parameters", ".", "Parameters", ":", "m", ":", "number", "of", "alternatives", "gamma", ":", "parameters", "of", "the", "Plackett", "-", "Luce", "model" ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/plackettluce.py#L76-L107
train
Returns a list of candidates that are in the Plackett - Luce model.
PrefPy/prefpy
prefpy/plackettluce.py
_generate_mix2pl_dataset
def _generate_mix2pl_dataset(n, m, outfile, useDirichlet=True): """ Description: Generate a Mixture of 2 Plackett-Luce models dataset and save it to disk. Parameters: n: number of votes to generate m: number of alternatives outfile: ...
python
def _generate_mix2pl_dataset(n, m, outfile, useDirichlet=True): """ Description: Generate a Mixture of 2 Plackett-Luce models dataset and save it to disk. Parameters: n: number of votes to generate m: number of alternatives outfile: ...
[ "def", "_generate_mix2pl_dataset", "(", "n", ",", "m", ",", "outfile", ",", "useDirichlet", "=", "True", ")", ":", "params", ",", "votes", "=", "generate_mix2pl_dataset", "(", "n", ",", "m", ",", "useDirichlet", ")", "outfile", ".", "write", "(", "str", ...
Description: Generate a Mixture of 2 Plackett-Luce models dataset and save it to disk. Parameters: n: number of votes to generate m: number of alternatives outfile: open file object to which the dataset is written useDirichlet: boolea...
[ "Description", ":", "Generate", "a", "Mixture", "of", "2", "Plackett", "-", "Luce", "models", "dataset", "and", "save", "it", "to", "disk", ".", "Parameters", ":", "n", ":", "number", "of", "votes", "to", "generate", "m", ":", "number", "of", "alternativ...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/plackettluce.py#L109-L125
train
This function generates a Mixture of 2 Plackett - Luce models and saves it to disk.
PrefPy/prefpy
prefpy/plackettluce.py
read_mix2pl_dataset
def read_mix2pl_dataset(infile, numVotes=None): """ Description: Read from disk a Mixture of 2 Plackett-Luce models dataset. Parameters: infile: open file object from which to read the dataset numVotes: number of votes to read from the file or all if None """ m, n =...
python
def read_mix2pl_dataset(infile, numVotes=None): """ Description: Read from disk a Mixture of 2 Plackett-Luce models dataset. Parameters: infile: open file object from which to read the dataset numVotes: number of votes to read from the file or all if None """ m, n =...
[ "def", "read_mix2pl_dataset", "(", "infile", ",", "numVotes", "=", "None", ")", ":", "m", ",", "n", "=", "[", "int", "(", "i", ")", "for", "i", "in", "infile", ".", "readline", "(", ")", ".", "split", "(", "','", ")", "]", "if", "numVotes", "is",...
Description: Read from disk a Mixture of 2 Plackett-Luce models dataset. Parameters: infile: open file object from which to read the dataset numVotes: number of votes to read from the file or all if None
[ "Description", ":", "Read", "from", "disk", "a", "Mixture", "of", "2", "Plackett", "-", "Luce", "models", "dataset", ".", "Parameters", ":", "infile", ":", "open", "file", "object", "from", "which", "to", "read", "the", "dataset", "numVotes", ":", "number"...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/plackettluce.py#L127-L154
train
Reads a Mixture of 2 Plackett - Luce models dataset from disk.
PrefPy/prefpy
prefpy/plackettluce.py
generate_mix2pl_dataset
def generate_mix2pl_dataset(n, m, useDirichlet=True): """ Description: Generate a mixture of 2 Plackett-Luce models dataset and return the parameters and votes. Parameters: n: number of votes to generate m: number of alternatives useDiric...
python
def generate_mix2pl_dataset(n, m, useDirichlet=True): """ Description: Generate a mixture of 2 Plackett-Luce models dataset and return the parameters and votes. Parameters: n: number of votes to generate m: number of alternatives useDiric...
[ "def", "generate_mix2pl_dataset", "(", "n", ",", "m", ",", "useDirichlet", "=", "True", ")", ":", "alpha", "=", "np", ".", "random", ".", "rand", "(", ")", "gamma1", "=", "None", "gamma2", "=", "None", "if", "useDirichlet", ":", "gamma1", "=", "np", ...
Description: Generate a mixture of 2 Plackett-Luce models dataset and return the parameters and votes. Parameters: n: number of votes to generate m: number of alternatives useDirichlet: boolean flag to use the Dirichlet distribution
[ "Description", ":", "Generate", "a", "mixture", "of", "2", "Plackett", "-", "Luce", "models", "dataset", "and", "return", "the", "parameters", "and", "votes", ".", "Parameters", ":", "n", ":", "number", "of", "votes", "to", "generate", "m", ":", "number", ...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/plackettluce.py#L156-L191
train
Generate a mixture of 2 Plackett - Luce models dataset
astooke/gtimer
gtimer/private/collapse.py
collapse_times
def collapse_times(): """Make copies of everything, assign to global shortcuts so functions work on them, extract the times, then restore the running stacks. """ orig_ts = f.timer_stack orig_ls = f.loop_stack copy_ts = _copy_timer_stack() copy_ls = copy.deepcopy(f.loop_stack) f.timer_sta...
python
def collapse_times(): """Make copies of everything, assign to global shortcuts so functions work on them, extract the times, then restore the running stacks. """ orig_ts = f.timer_stack orig_ls = f.loop_stack copy_ts = _copy_timer_stack() copy_ls = copy.deepcopy(f.loop_stack) f.timer_sta...
[ "def", "collapse_times", "(", ")", ":", "orig_ts", "=", "f", ".", "timer_stack", "orig_ls", "=", "f", ".", "loop_stack", "copy_ts", "=", "_copy_timer_stack", "(", ")", "copy_ls", "=", "copy", ".", "deepcopy", "(", "f", ".", "loop_stack", ")", "f", ".", ...
Make copies of everything, assign to global shortcuts so functions work on them, extract the times, then restore the running stacks.
[ "Make", "copies", "of", "everything", "assign", "to", "global", "shortcuts", "so", "functions", "work", "on", "them", "extract", "the", "times", "then", "restore", "the", "running", "stacks", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/private/collapse.py#L15-L33
train
Collapse all times in the current hierarchy.
IRC-SPHERE/HyperStream
hyperstream/plate/plate_manager.py
PlateManager.delete_plate
def delete_plate(self, plate_id, delete_meta_data=False): """ Delete a plate from the database :param plate_id: The plate id :param delete_meta_data: Optionally delete all meta data associated with this plate as well :return: None """ if plate_id not in ...
python
def delete_plate(self, plate_id, delete_meta_data=False): """ Delete a plate from the database :param plate_id: The plate id :param delete_meta_data: Optionally delete all meta data associated with this plate as well :return: None """ if plate_id not in ...
[ "def", "delete_plate", "(", "self", ",", "plate_id", ",", "delete_meta_data", "=", "False", ")", ":", "if", "plate_id", "not", "in", "self", ".", "plates", ":", "logging", ".", "info", "(", "\"Plate {} not found for deletion\"", ".", "format", "(", "plate_id",...
Delete a plate from the database :param plate_id: The plate id :param delete_meta_data: Optionally delete all meta data associated with this plate as well :return: None
[ "Delete", "a", "plate", "from", "the", "database", ":", "param", "plate_id", ":", "The", "plate", "id", ":", "param", "delete_meta_data", ":", "Optionally", "delete", "all", "meta", "data", "associated", "with", "this", "plate", "as", "well", ":", "return", ...
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/plate/plate_manager.py#L71-L98
train
Delete a specific plate from the database.
IRC-SPHERE/HyperStream
hyperstream/plate/plate_manager.py
PlateManager.create_plate
def create_plate(self, plate_id, description, meta_data_id, values, complement, parent_plate): """ Create a new plate, and commit it to the database :param plate_id: The plate id - required to be unique :param description: A human readable description :param meta_data_id: The me...
python
def create_plate(self, plate_id, description, meta_data_id, values, complement, parent_plate): """ Create a new plate, and commit it to the database :param plate_id: The plate id - required to be unique :param description: A human readable description :param meta_data_id: The me...
[ "def", "create_plate", "(", "self", ",", "plate_id", ",", "description", ",", "meta_data_id", ",", "values", ",", "complement", ",", "parent_plate", ")", ":", "# Make sure the plate id doesn't already exist", "with", "switch_db", "(", "PlateDefinitionModel", ",", "db_...
Create a new plate, and commit it to the database :param plate_id: The plate id - required to be unique :param description: A human readable description :param meta_data_id: The meta data id, which should correspond to the tag in the global meta data :param values: Either a list of stri...
[ "Create", "a", "new", "plate", "and", "commit", "it", "to", "the", "database" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/plate/plate_manager.py#L100-L139
train
Create a new plate and commit it to the database
IRC-SPHERE/HyperStream
hyperstream/plate/plate_manager.py
PlateManager.add_plate
def add_plate(self, plate_definition): """ Add a plate using the plate definition :param plate_definition: The plate definition :return: None :type plate_definition: PlateDefinitionModel """ values = self.get_plate_values(plate_definition) # TODO: We shou...
python
def add_plate(self, plate_definition): """ Add a plate using the plate definition :param plate_definition: The plate definition :return: None :type plate_definition: PlateDefinitionModel """ values = self.get_plate_values(plate_definition) # TODO: We shou...
[ "def", "add_plate", "(", "self", ",", "plate_definition", ")", ":", "values", "=", "self", ".", "get_plate_values", "(", "plate_definition", ")", "# TODO: We should also be checking that the plate is defined over all of the values of the parent plate", "self", ".", "plates", ...
Add a plate using the plate definition :param plate_definition: The plate definition :return: None :type plate_definition: PlateDefinitionModel
[ "Add", "a", "plate", "using", "the", "plate", "definition", ":", "param", "plate_definition", ":", "The", "plate", "definition", ":", "return", ":", "None", ":", "type", "plate_definition", ":", "PlateDefinitionModel" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/plate/plate_manager.py#L141-L157
train
Adds a plate using the plate definition
IRC-SPHERE/HyperStream
hyperstream/plate/plate_manager.py
PlateManager.get_plate_values
def get_plate_values(self, plate_definition): """ Gets the plate values from the global meta data according to the given plate definition :param plate_definition: The plate definition :return: The plate values :type plate_definition: PlateDefinitionModel """ if no...
python
def get_plate_values(self, plate_definition): """ Gets the plate values from the global meta data according to the given plate definition :param plate_definition: The plate definition :return: The plate values :type plate_definition: PlateDefinitionModel """ if no...
[ "def", "get_plate_values", "(", "self", ",", "plate_definition", ")", ":", "if", "not", "plate_definition", ".", "values", "and", "not", "plate_definition", ".", "complement", ":", "raise", "PlateDefinitionError", "(", ")", "values", "=", "[", "]", "for", "n",...
Gets the plate values from the global meta data according to the given plate definition :param plate_definition: The plate definition :return: The plate values :type plate_definition: PlateDefinitionModel
[ "Gets", "the", "plate", "values", "from", "the", "global", "meta", "data", "according", "to", "the", "given", "plate", "definition", ":", "param", "plate_definition", ":", "The", "plate", "definition", ":", "return", ":", "The", "plate", "values", ":", "type...
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/plate/plate_manager.py#L159-L187
train
Gets the values of the given plate definition from the global meta data according to the given plate definition.
IRC-SPHERE/HyperStream
hyperstream/plate/plate_manager.py
PlateManager.get_parent_plate_value
def get_parent_plate_value(tree, node, value=None): """ Recurse up the tree getting parent plate values :param tree: The tree :param node: The current node :param value: The initial plate value :return: The plate value as a list of tuples """ if value is N...
python
def get_parent_plate_value(tree, node, value=None): """ Recurse up the tree getting parent plate values :param tree: The tree :param node: The current node :param value: The initial plate value :return: The plate value as a list of tuples """ if value is N...
[ "def", "get_parent_plate_value", "(", "tree", ",", "node", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "value", "=", "[", "]", "parent", "=", "tree", ".", "parent", "(", "node", ".", "identifier", ")", "if", "parent", ".", ...
Recurse up the tree getting parent plate values :param tree: The tree :param node: The current node :param value: The initial plate value :return: The plate value as a list of tuples
[ "Recurse", "up", "the", "tree", "getting", "parent", "plate", "values", ":", "param", "tree", ":", "The", "tree", ":", "param", "node", ":", "The", "current", "node", ":", "param", "value", ":", "The", "initial", "plate", "value", ":", "return", ":", "...
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/plate/plate_manager.py#L190-L208
train
Recursively gets the parent plate value of the given node.
IRC-SPHERE/HyperStream
hyperstream/plate/plate_manager.py
PlateManager.get_parent_data
def get_parent_data(tree, node, current): """ Recurse up the tree getting parent data :param tree: The tree :param node: The current node :param current: The current list :return: The hierarchical dictionary """ if not current: current = [] ...
python
def get_parent_data(tree, node, current): """ Recurse up the tree getting parent data :param tree: The tree :param node: The current node :param current: The current list :return: The hierarchical dictionary """ if not current: current = [] ...
[ "def", "get_parent_data", "(", "tree", ",", "node", ",", "current", ")", ":", "if", "not", "current", ":", "current", "=", "[", "]", "parent", "=", "tree", ".", "parent", "(", "node", ".", "identifier", ")", "if", "parent", ".", "is_root", "(", ")", ...
Recurse up the tree getting parent data :param tree: The tree :param node: The current node :param current: The current list :return: The hierarchical dictionary
[ "Recurse", "up", "the", "tree", "getting", "parent", "data", ":", "param", "tree", ":", "The", "tree", ":", "param", "node", ":", "The", "current", "node", ":", "param", "current", ":", "The", "current", "list", ":", "return", ":", "The", "hierarchical",...
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/plate/plate_manager.py#L211-L227
train
Recurse up the tree getting the parent data
astooke/gtimer
gtimer/public/timedloop.py
timed_loop
def timed_loop(name=None, rgstr_stamps=None, save_itrs=SET['SI'], loop_end_stamp=None, end_stamp_unique=SET['UN'], keep_prev_subdivisions=SET['KS'], keep_end_subdivisions=SET['KS'], quick_print=SET['QP']): """ ...
python
def timed_loop(name=None, rgstr_stamps=None, save_itrs=SET['SI'], loop_end_stamp=None, end_stamp_unique=SET['UN'], keep_prev_subdivisions=SET['KS'], keep_end_subdivisions=SET['KS'], quick_print=SET['QP']): """ ...
[ "def", "timed_loop", "(", "name", "=", "None", ",", "rgstr_stamps", "=", "None", ",", "save_itrs", "=", "SET", "[", "'SI'", "]", ",", "loop_end_stamp", "=", "None", ",", "end_stamp_unique", "=", "SET", "[", "'UN'", "]", ",", "keep_prev_subdivisions", "=", ...
Instantiate a TimedLoop object for measuring loop iteration timing data. Can be used with either for or while loops. Example:: loop = timed_loop() while x > 0: # or for x in <iterable>: next(loop) # or loop.next() <body of loop, with gtimer stamps> loop.exit()...
[ "Instantiate", "a", "TimedLoop", "object", "for", "measuring", "loop", "iteration", "timing", "data", ".", "Can", "be", "used", "with", "either", "for", "or", "while", "loops", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timedloop.py#L13-L69
train
Return a TimedLoop object that can be used to measure loop timing data.
astooke/gtimer
gtimer/public/timedloop.py
timed_for
def timed_for(iterable, name=None, rgstr_stamps=None, save_itrs=SET['SI'], loop_end_stamp=None, end_stamp_unique=SET['UN'], keep_prev_subdivisions=SET['KS'], keep_end_subdivisions=SET['KS'], quick_print=SET['...
python
def timed_for(iterable, name=None, rgstr_stamps=None, save_itrs=SET['SI'], loop_end_stamp=None, end_stamp_unique=SET['UN'], keep_prev_subdivisions=SET['KS'], keep_end_subdivisions=SET['KS'], quick_print=SET['...
[ "def", "timed_for", "(", "iterable", ",", "name", "=", "None", ",", "rgstr_stamps", "=", "None", ",", "save_itrs", "=", "SET", "[", "'SI'", "]", ",", "loop_end_stamp", "=", "None", ",", "end_stamp_unique", "=", "SET", "[", "'UN'", "]", ",", "keep_prev_su...
Instantiate a TimedLoop object for measuring for loop iteration timing data. Can be used only on for loops. Example:: for i in gtimer.timed_for(iterable, ..): <body of loop with gtimer stamps> Notes: Can be used as a context manager around the loop. When breaking out of ...
[ "Instantiate", "a", "TimedLoop", "object", "for", "measuring", "for", "loop", "iteration", "timing", "data", ".", "Can", "be", "used", "only", "on", "for", "loops", "." ]
2146dab459e5d959feb291821733d3d3ba7c523c
https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timedloop.py#L72-L131
train
Return a TimedLoop object for the given iterable of times.
tamasgal/km3pipe
km3pipe/utils/calibrate.py
write_calibration
def write_calibration(calib, f, loc): """Write calibration set to file""" for i, node in enumerate( [p + '_' + s for p in ['pos', 'dir'] for s in 'xyz']): h5loc = loc + '/' + node ca = f.get_node(h5loc) ca.append(calib[:, i]) du = f.get_node(loc + '/du') du.append(calib[...
python
def write_calibration(calib, f, loc): """Write calibration set to file""" for i, node in enumerate( [p + '_' + s for p in ['pos', 'dir'] for s in 'xyz']): h5loc = loc + '/' + node ca = f.get_node(h5loc) ca.append(calib[:, i]) du = f.get_node(loc + '/du') du.append(calib[...
[ "def", "write_calibration", "(", "calib", ",", "f", ",", "loc", ")", ":", "for", "i", ",", "node", "in", "enumerate", "(", "[", "p", "+", "'_'", "+", "s", "for", "p", "in", "[", "'pos'", ",", "'dir'", "]", "for", "s", "in", "'xyz'", "]", ")", ...
Write calibration set to file
[ "Write", "calibration", "set", "to", "file" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/calibrate.py#L87-L108
train
Write calibration set to file
tamasgal/km3pipe
km3pipe/utils/calibrate.py
initialise_arrays
def initialise_arrays(group, f): """Create EArrays for calibrated hits""" for node in ['pos_x', 'pos_y', 'pos_z', 'dir_x', 'dir_y', 'dir_z', 'du', 'floor', 't0']: if node in ['floor', 'du']: atom = U1_ATOM else: atom = F4_ATOM f.create_earray(grou...
python
def initialise_arrays(group, f): """Create EArrays for calibrated hits""" for node in ['pos_x', 'pos_y', 'pos_z', 'dir_x', 'dir_y', 'dir_z', 'du', 'floor', 't0']: if node in ['floor', 'du']: atom = U1_ATOM else: atom = F4_ATOM f.create_earray(grou...
[ "def", "initialise_arrays", "(", "group", ",", "f", ")", ":", "for", "node", "in", "[", "'pos_x'", ",", "'pos_y'", ",", "'pos_z'", ",", "'dir_x'", ",", "'dir_y'", ",", "'dir_z'", ",", "'du'", ",", "'floor'", ",", "'t0'", "]", ":", "if", "node", "in",...
Create EArrays for calibrated hits
[ "Create", "EArrays", "for", "calibrated", "hits" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/calibrate.py#L111-L119
train
Initialise the EArrays for calibrated hits
tamasgal/km3pipe
km3pipe/io/aanet.py
AanetPump.blob_counter
def blob_counter(self): """Create a blob counter.""" import aa # pylint: disablF0401 # noqa from ROOT import EventFile # pylint: disable F0401 try: event_file = EventFile(self.filename) except Exception: raise SystemExit("Could not open file"...
python
def blob_counter(self): """Create a blob counter.""" import aa # pylint: disablF0401 # noqa from ROOT import EventFile # pylint: disable F0401 try: event_file = EventFile(self.filename) except Exception: raise SystemExit("Could not open file"...
[ "def", "blob_counter", "(", "self", ")", ":", "import", "aa", "# pylint: disablF0401 # noqa", "from", "ROOT", "import", "EventFile", "# pylint: disable F0401", "try", ":", "event_file", "=", "EventFile", "(", "self", ".", "filename", ")", "except", "Exception...
Create a blob counter.
[ "Create", "a", "blob", "counter", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/aanet.py#L248-L262
train
Create a blob counter.
tamasgal/km3pipe
km3pipe/io/aanet.py
AanetPump.blob_generator
def blob_generator(self): """Create a blob generator.""" # pylint: disable:F0401,W0612 import aa # pylint: disablF0401 # noqa from ROOT import EventFile # pylint: disable F0401 filename = self.filename log.info("Reading from file: {0}".format(filename)) ...
python
def blob_generator(self): """Create a blob generator.""" # pylint: disable:F0401,W0612 import aa # pylint: disablF0401 # noqa from ROOT import EventFile # pylint: disable F0401 filename = self.filename log.info("Reading from file: {0}".format(filename)) ...
[ "def", "blob_generator", "(", "self", ")", ":", "# pylint: disable:F0401,W0612", "import", "aa", "# pylint: disablF0401 # noqa", "from", "ROOT", "import", "EventFile", "# pylint: disable F0401", "filename", "=", "self", ".", "filename", "log", ".", "info", "(", ...
Create a blob generator.
[ "Create", "a", "blob", "generator", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/aanet.py#L264-L320
train
Create a blob generator.
tamasgal/km3pipe
km3pipe/io/aanet.py
MetaParser.parse_string
def parse_string(self, string): """Parse ASCII output of JPrintMeta""" self.log.info("Parsing ASCII data") if not string: self.log.warning("Empty metadata") return lines = string.splitlines() application_data = [] application = lines[0].split()[...
python
def parse_string(self, string): """Parse ASCII output of JPrintMeta""" self.log.info("Parsing ASCII data") if not string: self.log.warning("Empty metadata") return lines = string.splitlines() application_data = [] application = lines[0].split()[...
[ "def", "parse_string", "(", "self", ",", "string", ")", ":", "self", ".", "log", ".", "info", "(", "\"Parsing ASCII data\"", ")", "if", "not", "string", ":", "self", ".", "log", ".", "warning", "(", "\"Empty metadata\"", ")", "return", "lines", "=", "str...
Parse ASCII output of JPrintMeta
[ "Parse", "ASCII", "output", "of", "JPrintMeta" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/aanet.py#L692-L716
train
Parse the ASCII output of JPrintMeta
tamasgal/km3pipe
km3pipe/io/aanet.py
MetaParser._record_app_data
def _record_app_data(self, data): """Parse raw metadata output for a single application The usual output is: ApplicationName RevisionNumber ApplicationName ROOT_Version ApplicationName KM3NET ApplicationName ./command/line --arguments --which --can contain ...
python
def _record_app_data(self, data): """Parse raw metadata output for a single application The usual output is: ApplicationName RevisionNumber ApplicationName ROOT_Version ApplicationName KM3NET ApplicationName ./command/line --arguments --which --can contain ...
[ "def", "_record_app_data", "(", "self", ",", "data", ")", ":", "name", ",", "revision", "=", "data", "[", "0", "]", ".", "split", "(", ")", "root_version", "=", "data", "[", "1", "]", ".", "split", "(", ")", "[", "1", "]", "command", "=", "b'\\n'...
Parse raw metadata output for a single application The usual output is: ApplicationName RevisionNumber ApplicationName ROOT_Version ApplicationName KM3NET ApplicationName ./command/line --arguments --which --can contain also multiple lines and --a...
[ "Parse", "raw", "metadata", "output", "for", "a", "single", "application" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/aanet.py#L718-L741
train
Parse raw metadata output for a single application and record it as meta data.
tamasgal/km3pipe
km3pipe/io/aanet.py
MetaParser.get_table
def get_table(self, name='Meta', h5loc='/meta'): """Convert metadata to a KM3Pipe Table. Returns `None` if there is no data. Each column's dtype will be set to a fixed size string (numpy.string_) with the length of the longest entry, since writing variable length strings does n...
python
def get_table(self, name='Meta', h5loc='/meta'): """Convert metadata to a KM3Pipe Table. Returns `None` if there is no data. Each column's dtype will be set to a fixed size string (numpy.string_) with the length of the longest entry, since writing variable length strings does n...
[ "def", "get_table", "(", "self", ",", "name", "=", "'Meta'", ",", "h5loc", "=", "'/meta'", ")", ":", "if", "not", "self", ".", "meta", ":", "return", "None", "data", "=", "defaultdict", "(", "list", ")", "for", "entry", "in", "self", ".", "meta", "...
Convert metadata to a KM3Pipe Table. Returns `None` if there is no data. Each column's dtype will be set to a fixed size string (numpy.string_) with the length of the longest entry, since writing variable length strings does not fit the current scheme.
[ "Convert", "metadata", "to", "a", "KM3Pipe", "Table", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/aanet.py#L743-L767
train
Convert metadata to a KM3Pipe Table.
PrefPy/prefpy
prefpy/aggregate.py
RankAggregator.get_ranking
def get_ranking(self, alt): """ Description: Returns the ranking of a given alternative in the computed aggregate ranking. An error is thrown if the alternative does not exist. The ranking is the index in the aggregate ranking, which is 0-indexed. ...
python
def get_ranking(self, alt): """ Description: Returns the ranking of a given alternative in the computed aggregate ranking. An error is thrown if the alternative does not exist. The ranking is the index in the aggregate ranking, which is 0-indexed. ...
[ "def", "get_ranking", "(", "self", ",", "alt", ")", ":", "if", "self", ".", "alts_to_ranks", "is", "None", ":", "raise", "ValueError", "(", "\"Aggregate ranking must be created first\"", ")", "try", ":", "rank", "=", "self", ".", "alts_to_ranks", "[", "alt", ...
Description: Returns the ranking of a given alternative in the computed aggregate ranking. An error is thrown if the alternative does not exist. The ranking is the index in the aggregate ranking, which is 0-indexed. Parameters: alt: the key tha...
[ "Description", ":", "Returns", "the", "ranking", "of", "a", "given", "alternative", "in", "the", "computed", "aggregate", "ranking", ".", "An", "error", "is", "thrown", "if", "the", "alternative", "does", "not", "exist", ".", "The", "ranking", "is", "the", ...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/aggregate.py#L36-L53
train
Returns the aggregate ranking of a given alternative in the aggregate ranking of the given key.
PrefPy/prefpy
prefpy/aggregate.py
RankAggregator.get_alternatives
def get_alternatives(self, rank): """ Description: Returns the alternative(s) with the given ranking in the computed aggregate ranking. An error is thrown if the ranking does not exist. """ if self.ranks_to_alts is None: raise Va...
python
def get_alternatives(self, rank): """ Description: Returns the alternative(s) with the given ranking in the computed aggregate ranking. An error is thrown if the ranking does not exist. """ if self.ranks_to_alts is None: raise Va...
[ "def", "get_alternatives", "(", "self", ",", "rank", ")", ":", "if", "self", ".", "ranks_to_alts", "is", "None", ":", "raise", "ValueError", "(", "\"Aggregate ranking must be created first\"", ")", "try", ":", "alts", "=", "self", ".", "ranks_to_alts", "[", "r...
Description: Returns the alternative(s) with the given ranking in the computed aggregate ranking. An error is thrown if the ranking does not exist.
[ "Description", ":", "Returns", "the", "alternative", "(", "s", ")", "with", "the", "given", "ranking", "in", "the", "computed", "aggregate", "ranking", ".", "An", "error", "is", "thrown", "if", "the", "ranking", "does", "not", "exist", "." ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/aggregate.py#L55-L69
train
Returns the alternative(s) with the given ranking in the aggregate ranking.
PrefPy/prefpy
prefpy/aggregate.py
RankAggregator.create_rank_dicts
def create_rank_dicts(self, alt_scores): """ Description: Takes in the scores of the alternatives in the form alt:score and generates the dictionaries mapping alternatives to rankings and rankings to alternatives. Parameters: alt_scores: dic...
python
def create_rank_dicts(self, alt_scores): """ Description: Takes in the scores of the alternatives in the form alt:score and generates the dictionaries mapping alternatives to rankings and rankings to alternatives. Parameters: alt_scores: dic...
[ "def", "create_rank_dicts", "(", "self", ",", "alt_scores", ")", ":", "self", ".", "alts_to_ranks", "=", "dict", "(", ")", "cur_score", "=", "max", "(", "alt_scores", ".", "values", "(", ")", ")", "cur_rank", "=", "0", "self", ".", "ranks_to_alts", "=", ...
Description: Takes in the scores of the alternatives in the form alt:score and generates the dictionaries mapping alternatives to rankings and rankings to alternatives. Parameters: alt_scores: dictionary of the scores of every alternative
[ "Description", ":", "Takes", "in", "the", "scores", "of", "the", "alternatives", "in", "the", "form", "alt", ":", "score", "and", "generates", "the", "dictionaries", "mapping", "alternatives", "to", "rankings", "and", "rankings", "to", "alternatives", ".", "Pa...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/aggregate.py#L71-L91
train
Create the ranking and ranking dictionaries for the given set of alternatives.
NaPs/Kolekto
kolekto/db.py
MoviesMetadata.itermovieshash
def itermovieshash(self): """ Iterate over movies hash stored in the database. """ cur = self._db.firstkey() while cur is not None: yield cur cur = self._db.nextkey(cur)
python
def itermovieshash(self): """ Iterate over movies hash stored in the database. """ cur = self._db.firstkey() while cur is not None: yield cur cur = self._db.nextkey(cur)
[ "def", "itermovieshash", "(", "self", ")", ":", "cur", "=", "self", ".", "_db", ".", "firstkey", "(", ")", "while", "cur", "is", "not", "None", ":", "yield", "cur", "cur", "=", "self", ".", "_db", ".", "nextkey", "(", "cur", ")" ]
Iterate over movies hash stored in the database.
[ "Iterate", "over", "movies", "hash", "stored", "in", "the", "database", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/db.py#L12-L18
train
Iterate over the movies hash stored in the database.
rorychatterton/Terraform-Enterprise-2-Python-SDK
te2_sdk/te2.py
TE2WorkspaceRuns._get_run_results
def _get_run_results(self, run_id, request_type="plan", timeout_count=120): """ Wait for plan/apply results, else timeout :param run_id: ID for the run :return: Returns object of the results. """ if request_type is not "plan" and request_type is not "apply": ...
python
def _get_run_results(self, run_id, request_type="plan", timeout_count=120): """ Wait for plan/apply results, else timeout :param run_id: ID for the run :return: Returns object of the results. """ if request_type is not "plan" and request_type is not "apply": ...
[ "def", "_get_run_results", "(", "self", ",", "run_id", ",", "request_type", "=", "\"plan\"", ",", "timeout_count", "=", "120", ")", ":", "if", "request_type", "is", "not", "\"plan\"", "and", "request_type", "is", "not", "\"apply\"", ":", "raise", "KeyError", ...
Wait for plan/apply results, else timeout :param run_id: ID for the run :return: Returns object of the results.
[ "Wait", "for", "plan", "/", "apply", "results", "else", "timeout" ]
2a519a3e0569565cb04840d170d0f73969d9deb7
https://github.com/rorychatterton/Terraform-Enterprise-2-Python-SDK/blob/2a519a3e0569565cb04840d170d0f73969d9deb7/te2_sdk/te2.py#L88-L109
train
Get the results of a single run.
wtsi-hgi/consul-lock
consullock/configuration.py
get_consul_configuration_from_environment
def get_consul_configuration_from_environment() -> ConsulConfiguration: """ Gets configuration on how to connect to Consul from the environment. :return: the configuration derived from the environment :raises KeyError: if a required environment variable has not been set """ address = os.environ[...
python
def get_consul_configuration_from_environment() -> ConsulConfiguration: """ Gets configuration on how to connect to Consul from the environment. :return: the configuration derived from the environment :raises KeyError: if a required environment variable has not been set """ address = os.environ[...
[ "def", "get_consul_configuration_from_environment", "(", ")", "->", "ConsulConfiguration", ":", "address", "=", "os", ".", "environ", "[", "CONSUL_ADDRESS_ENVIRONMENT_VARIABLE", "]", "if", "\"://\"", "in", "address", ":", "raise", "EnvironmentError", "(", "f\"Invalid ho...
Gets configuration on how to connect to Consul from the environment. :return: the configuration derived from the environment :raises KeyError: if a required environment variable has not been set
[ "Gets", "configuration", "on", "how", "to", "connect", "to", "Consul", "from", "the", "environment", ".", ":", "return", ":", "the", "configuration", "derived", "from", "the", "environment", ":", "raises", "KeyError", ":", "if", "a", "required", "environment",...
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/configuration.py#L71-L98
train
Gets the configuration derived from the environment variable.
vaidik/incoming
incoming/incoming.py
PayloadErrors.to_dict
def to_dict(self): ''' Return a :class:`dict` of errors with keys as the type of error and values as a list of errors. :returns dict: a dictionary of errors ''' errors = copy.deepcopy(self._errors) for key, val in iteritems(self._errors): if not len(...
python
def to_dict(self): ''' Return a :class:`dict` of errors with keys as the type of error and values as a list of errors. :returns dict: a dictionary of errors ''' errors = copy.deepcopy(self._errors) for key, val in iteritems(self._errors): if not len(...
[ "def", "to_dict", "(", "self", ")", ":", "errors", "=", "copy", ".", "deepcopy", "(", "self", ".", "_errors", ")", "for", "key", ",", "val", "in", "iteritems", "(", "self", ".", "_errors", ")", ":", "if", "not", "len", "(", "val", ")", ":", "erro...
Return a :class:`dict` of errors with keys as the type of error and values as a list of errors. :returns dict: a dictionary of errors
[ "Return", "a", ":", "class", ":", "dict", "of", "errors", "with", "keys", "as", "the", "type", "of", "error", "and", "values", "as", "a", "list", "of", "errors", "." ]
c0dc26a17d49723315ef6cb28df10dcd39a8104b
https://github.com/vaidik/incoming/blob/c0dc26a17d49723315ef6cb28df10dcd39a8104b/incoming/incoming.py#L45-L57
train
Return a dictionary of errors with keys as the type of error and values as a list of errors.
vaidik/incoming
incoming/incoming.py
PayloadValidator._collect_fields
def _collect_fields(self): ''' Collects all the attributes that are instance of :class:`incoming.datatypes.Types`. These attributes are used for defining rules of validation for every field/key in the incoming JSON payload. :returns: a tuple of attribute names from an in...
python
def _collect_fields(self): ''' Collects all the attributes that are instance of :class:`incoming.datatypes.Types`. These attributes are used for defining rules of validation for every field/key in the incoming JSON payload. :returns: a tuple of attribute names from an in...
[ "def", "_collect_fields", "(", "self", ")", ":", "fields", "=", "[", "]", "for", "prop", "in", "dir", "(", "self", ")", ":", "if", "isinstance", "(", "getattr", "(", "self", ",", "prop", ")", ",", "Types", ")", ":", "fields", ".", "append", "(", ...
Collects all the attributes that are instance of :class:`incoming.datatypes.Types`. These attributes are used for defining rules of validation for every field/key in the incoming JSON payload. :returns: a tuple of attribute names from an instance of a sub-class of :cla...
[ "Collects", "all", "the", "attributes", "that", "are", "instance", "of", ":", "class", ":", "incoming", ".", "datatypes", ".", "Types", ".", "These", "attributes", "are", "used", "for", "defining", "rules", "of", "validation", "for", "every", "field", "/", ...
c0dc26a17d49723315ef6cb28df10dcd39a8104b
https://github.com/vaidik/incoming/blob/c0dc26a17d49723315ef6cb28df10dcd39a8104b/incoming/incoming.py#L110-L129
train
Collect all the attributes that are instance of and return a tuple of the names of the fields that are instance of .
vaidik/incoming
incoming/incoming.py
PayloadValidator._replace_string_args
def _replace_string_args(self): ''' A helper method that makes passing custom validators implemented as methods to :class:`incoming.datatypes.Function` instances. ''' if self._string_args_replaced: return for field in self._fields: field = getatt...
python
def _replace_string_args(self): ''' A helper method that makes passing custom validators implemented as methods to :class:`incoming.datatypes.Function` instances. ''' if self._string_args_replaced: return for field in self._fields: field = getatt...
[ "def", "_replace_string_args", "(", "self", ")", ":", "if", "self", ".", "_string_args_replaced", ":", "return", "for", "field", "in", "self", ".", "_fields", ":", "field", "=", "getattr", "(", "self", ",", "field", ")", "if", "isinstance", "(", "field", ...
A helper method that makes passing custom validators implemented as methods to :class:`incoming.datatypes.Function` instances.
[ "A", "helper", "method", "that", "makes", "passing", "custom", "validators", "implemented", "as", "methods", "to", ":", "class", ":", "incoming", ".", "datatypes", ".", "Function", "instances", "." ]
c0dc26a17d49723315ef6cb28df10dcd39a8104b
https://github.com/vaidik/incoming/blob/c0dc26a17d49723315ef6cb28df10dcd39a8104b/incoming/incoming.py#L131-L149
train
A helper method that makes passing custom validators implemented as methods to JSON instances.
vaidik/incoming
incoming/incoming.py
PayloadValidator.validate
def validate(self, payload, required=None, strict=None): ''' Validates a given JSON payload according to the rules defiined for all the fields/keys in the sub-class. :param dict payload: deserialized JSON object. :param bool required: if every field/key is required and must be ...
python
def validate(self, payload, required=None, strict=None): ''' Validates a given JSON payload according to the rules defiined for all the fields/keys in the sub-class. :param dict payload: deserialized JSON object. :param bool required: if every field/key is required and must be ...
[ "def", "validate", "(", "self", ",", "payload", ",", "required", "=", "None", ",", "strict", "=", "None", ")", ":", "# replace datatypes.Function.func if not already replaced", "self", ".", "_replace_string_args", "(", ")", "required", "=", "required", "if", "requ...
Validates a given JSON payload according to the rules defiined for all the fields/keys in the sub-class. :param dict payload: deserialized JSON object. :param bool required: if every field/key is required and must be present in the payload. :param bool stri...
[ "Validates", "a", "given", "JSON", "payload", "according", "to", "the", "rules", "defiined", "for", "all", "the", "fields", "/", "keys", "in", "the", "sub", "-", "class", "." ]
c0dc26a17d49723315ef6cb28df10dcd39a8104b
https://github.com/vaidik/incoming/blob/c0dc26a17d49723315ef6cb28df10dcd39a8104b/incoming/incoming.py#L151-L204
train
Validates a given JSON payload according to the rules defined for all the fields in the sub - class.
LeadPages/gcloud_requests
gcloud_requests/datastore.py
DatastoreRequestsProxy._max_retries_for_error
def _max_retries_for_error(self, error): """Handles Datastore response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: ...
python
def _max_retries_for_error(self, error): """Handles Datastore response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: ...
[ "def", "_max_retries_for_error", "(", "self", ",", "error", ")", ":", "status", "=", "error", ".", "get", "(", "\"status\"", ")", "if", "status", "==", "\"ABORTED\"", "and", "get_transactions", "(", ")", ">", "0", ":", "# Avoids retrying Conflicts when inside a ...
Handles Datastore response errors according to their documentation. Parameters: error(dict) Returns: int or None: The max number of times this error should be retried or None if it shouldn't. See also: https://cloud.google.com/datastore/docs/concepts/er...
[ "Handles", "Datastore", "response", "errors", "according", "to", "their", "documentation", "." ]
8933363c4e9fa1e5ec0e90d683fca8ef8a949752
https://github.com/LeadPages/gcloud_requests/blob/8933363c4e9fa1e5ec0e90d683fca8ef8a949752/gcloud_requests/datastore.py#L56-L73
train
Handles Datastore response errors according to their documentation.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
login
def login(credentials=None, app_name=None, services=None, client_id=None, make_clients=True, clear_old_tokens=False, token_dir=DEFAULT_CRED_PATH, **kwargs): """Log in to Globus services Arguments: credentials (str or dict): A string filename, string JSON, or dictionary with cr...
python
def login(credentials=None, app_name=None, services=None, client_id=None, make_clients=True, clear_old_tokens=False, token_dir=DEFAULT_CRED_PATH, **kwargs): """Log in to Globus services Arguments: credentials (str or dict): A string filename, string JSON, or dictionary with cr...
[ "def", "login", "(", "credentials", "=", "None", ",", "app_name", "=", "None", ",", "services", "=", "None", ",", "client_id", "=", "None", ",", "make_clients", "=", "True", ",", "clear_old_tokens", "=", "False", ",", "token_dir", "=", "DEFAULT_CRED_PATH", ...
Log in to Globus services Arguments: credentials (str or dict): A string filename, string JSON, or dictionary with credential and config information. By default, looks in ``~/mdf/credentials/globus_login.json``. Contains ``app_name``, ``services``, and ``clie...
[ "Log", "in", "to", "Globus", "services" ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L65-L254
train
Log in to Globus services.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
confidential_login
def confidential_login(credentials=None, client_id=None, client_secret=None, services=None, make_clients=True, token_dir=DEFAULT_CRED_PATH): """Log in to Globus services as a confidential client (a client with its own login information). Arguments: credentials (str or dict): ...
python
def confidential_login(credentials=None, client_id=None, client_secret=None, services=None, make_clients=True, token_dir=DEFAULT_CRED_PATH): """Log in to Globus services as a confidential client (a client with its own login information). Arguments: credentials (str or dict): ...
[ "def", "confidential_login", "(", "credentials", "=", "None", ",", "client_id", "=", "None", ",", "client_secret", "=", "None", ",", "services", "=", "None", ",", "make_clients", "=", "True", ",", "token_dir", "=", "DEFAULT_CRED_PATH", ")", ":", "DEFAULT_CRED_...
Log in to Globus services as a confidential client (a client with its own login information). Arguments: credentials (str or dict): A string filename, string JSON, or dictionary with credential and config information. By default, uses the ``DEFAULT_CRED_FILENAME`` and to...
[ "Log", "in", "to", "Globus", "services", "as", "a", "confidential", "client", "(", "a", "client", "with", "its", "own", "login", "information", ")", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L257-L361
train
Log in to Globus services as a confidential globus login.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
anonymous_login
def anonymous_login(services): """Initialize services without authenticating to Globus Auth. Note: Clients may have reduced functionality without authentication. Arguments: services (str or list of str): The services to initialize clients for. Returns: dict: The clients reques...
python
def anonymous_login(services): """Initialize services without authenticating to Globus Auth. Note: Clients may have reduced functionality without authentication. Arguments: services (str or list of str): The services to initialize clients for. Returns: dict: The clients reques...
[ "def", "anonymous_login", "(", "services", ")", ":", "if", "isinstance", "(", "services", ",", "str", ")", ":", "services", "=", "[", "services", "]", "clients", "=", "{", "}", "# Initialize valid services", "for", "serv", "in", "services", ":", "try", ":"...
Initialize services without authenticating to Globus Auth. Note: Clients may have reduced functionality without authentication. Arguments: services (str or list of str): The services to initialize clients for. Returns: dict: The clients requested, indexed by service name.
[ "Initialize", "services", "without", "authenticating", "to", "Globus", "Auth", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L364-L390
train
Initialize services without authenticating to Globus Auth.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
logout
def logout(token_dir=DEFAULT_CRED_PATH): """Remove ALL tokens in the token directory. This will force re-authentication to all services. Arguments: token_dir (str): The path to the directory to save tokens in and look for credentials by default. If this argument was given to a ``log...
python
def logout(token_dir=DEFAULT_CRED_PATH): """Remove ALL tokens in the token directory. This will force re-authentication to all services. Arguments: token_dir (str): The path to the directory to save tokens in and look for credentials by default. If this argument was given to a ``log...
[ "def", "logout", "(", "token_dir", "=", "DEFAULT_CRED_PATH", ")", ":", "for", "f", "in", "os", ".", "listdir", "(", "token_dir", ")", ":", "if", "f", ".", "endswith", "(", "\"tokens.json\"", ")", ":", "try", ":", "os", ".", "remove", "(", "os", ".", ...
Remove ALL tokens in the token directory. This will force re-authentication to all services. Arguments: token_dir (str): The path to the directory to save tokens in and look for credentials by default. If this argument was given to a ``login()`` function, the same value ...
[ "Remove", "ALL", "tokens", "in", "the", "token", "directory", ".", "This", "will", "force", "re", "-", "authentication", "to", "all", "services", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L393-L411
train
Removes all tokens in the token directory.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
uncompress_tree
def uncompress_tree(root, delete_archives=False): """Uncompress all tar, zip, and gzip archives under a given directory. Archives will be extracted to a sibling directory named after the archive (minus extension). This process can be slow, depending on the number and size of archives. Arguments: ...
python
def uncompress_tree(root, delete_archives=False): """Uncompress all tar, zip, and gzip archives under a given directory. Archives will be extracted to a sibling directory named after the archive (minus extension). This process can be slow, depending on the number and size of archives. Arguments: ...
[ "def", "uncompress_tree", "(", "root", ",", "delete_archives", "=", "False", ")", ":", "num_extracted", "=", "0", "error_files", "=", "[", "]", "# Start list of dirs to extract with root", "# Later, add newly-created dirs with extracted files, because os.walk will miss them", "...
Uncompress all tar, zip, and gzip archives under a given directory. Archives will be extracted to a sibling directory named after the archive (minus extension). This process can be slow, depending on the number and size of archives. Arguments: root (str): The path to the starting (root) directory. ...
[ "Uncompress", "all", "tar", "zip", "and", "gzip", "archives", "under", "a", "given", "directory", ".", "Archives", "will", "be", "extracted", "to", "a", "sibling", "directory", "named", "after", "the", "archive", "(", "minus", "extension", ")", ".", "This", ...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L418-L464
train
Uncompress all tar zip and gzip archives under a given directory.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
format_gmeta
def format_gmeta(data, acl=None, identifier=None): """Format input into GMeta format, suitable for ingesting into Globus Search. Formats a dictionary into a GMetaEntry. Formats a list of GMetaEntry into a GMetaList inside a GMetaIngest. **Example usage**:: glist = [] for document in al...
python
def format_gmeta(data, acl=None, identifier=None): """Format input into GMeta format, suitable for ingesting into Globus Search. Formats a dictionary into a GMetaEntry. Formats a list of GMetaEntry into a GMetaList inside a GMetaIngest. **Example usage**:: glist = [] for document in al...
[ "def", "format_gmeta", "(", "data", ",", "acl", "=", "None", ",", "identifier", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "if", "acl", "is", "None", "or", "identifier", "is", "None", ":", "raise", "ValueError", "(...
Format input into GMeta format, suitable for ingesting into Globus Search. Formats a dictionary into a GMetaEntry. Formats a list of GMetaEntry into a GMetaList inside a GMetaIngest. **Example usage**:: glist = [] for document in all_my_documents: gmeta_entry = format_gmeta(doc...
[ "Format", "input", "into", "GMeta", "format", "suitable", "for", "ingesting", "into", "Globus", "Search", ".", "Formats", "a", "dictionary", "into", "a", "GMetaEntry", ".", "Formats", "a", "list", "of", "GMetaEntry", "into", "a", "GMetaList", "inside", "a", ...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L471-L539
train
Format input into GMeta format suitable for ingesting into Globus Search.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
gmeta_pop
def gmeta_pop(gmeta, info=False): """Remove GMeta wrapping from a Globus Search result. This function can be called on the raw GlobusHTTPResponse that Search returns, or a string or dictionary representation of it. Arguments: gmeta (dict, str, or GlobusHTTPResponse): The Globus Search result to...
python
def gmeta_pop(gmeta, info=False): """Remove GMeta wrapping from a Globus Search result. This function can be called on the raw GlobusHTTPResponse that Search returns, or a string or dictionary representation of it. Arguments: gmeta (dict, str, or GlobusHTTPResponse): The Globus Search result to...
[ "def", "gmeta_pop", "(", "gmeta", ",", "info", "=", "False", ")", ":", "if", "type", "(", "gmeta", ")", "is", "GlobusHTTPResponse", ":", "gmeta", "=", "json", ".", "loads", "(", "gmeta", ".", "text", ")", "elif", "type", "(", "gmeta", ")", "is", "s...
Remove GMeta wrapping from a Globus Search result. This function can be called on the raw GlobusHTTPResponse that Search returns, or a string or dictionary representation of it. Arguments: gmeta (dict, str, or GlobusHTTPResponse): The Globus Search result to unwrap. info (bool): If ``False`...
[ "Remove", "GMeta", "wrapping", "from", "a", "Globus", "Search", "result", ".", "This", "function", "can", "be", "called", "on", "the", "raw", "GlobusHTTPResponse", "that", "Search", "returns", "or", "a", "string", "or", "dictionary", "representation", "of", "i...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L542-L574
train
Removes GMeta wrapping from a Globus Search result.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
translate_index
def translate_index(index_name): """Translate a known Globus Search index into the index UUID. The UUID is the proper way to access indices, and will eventually be the only way. This method will return names it cannot disambiguate. Arguments: index_name (str): The name of the index. Return...
python
def translate_index(index_name): """Translate a known Globus Search index into the index UUID. The UUID is the proper way to access indices, and will eventually be the only way. This method will return names it cannot disambiguate. Arguments: index_name (str): The name of the index. Return...
[ "def", "translate_index", "(", "index_name", ")", ":", "uuid", "=", "SEARCH_INDEX_UUIDS", ".", "get", "(", "index_name", ".", "strip", "(", ")", ".", "lower", "(", ")", ")", "if", "not", "uuid", ":", "try", ":", "index_info", "=", "globus_sdk", ".", "S...
Translate a known Globus Search index into the index UUID. The UUID is the proper way to access indices, and will eventually be the only way. This method will return names it cannot disambiguate. Arguments: index_name (str): The name of the index. Returns: str: The UUID of the index. I...
[ "Translate", "a", "known", "Globus", "Search", "index", "into", "the", "index", "UUID", ".", "The", "UUID", "is", "the", "proper", "way", "to", "access", "indices", "and", "will", "eventually", "be", "the", "only", "way", ".", "This", "method", "will", "...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L577-L598
train
Translate a known Globus Search index into the index UUID.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
custom_transfer
def custom_transfer(transfer_client, source_ep, dest_ep, path_list, interval=DEFAULT_INTERVAL, inactivity_time=DEFAULT_INACTIVITY_TIME, notify=True): """Perform a Globus Transfer. Arguments: transfer_client (TransferClient): An authenticated Transfer client. source_ep (str):...
python
def custom_transfer(transfer_client, source_ep, dest_ep, path_list, interval=DEFAULT_INTERVAL, inactivity_time=DEFAULT_INACTIVITY_TIME, notify=True): """Perform a Globus Transfer. Arguments: transfer_client (TransferClient): An authenticated Transfer client. source_ep (str):...
[ "def", "custom_transfer", "(", "transfer_client", ",", "source_ep", ",", "dest_ep", ",", "path_list", ",", "interval", "=", "DEFAULT_INTERVAL", ",", "inactivity_time", "=", "DEFAULT_INACTIVITY_TIME", ",", "notify", "=", "True", ")", ":", "# TODO: (LW) Handle transfers...
Perform a Globus Transfer. Arguments: transfer_client (TransferClient): An authenticated Transfer client. source_ep (str): The source Globus Endpoint ID. dest_ep (str): The destination Globus Endpoint ID. path_list (list of tuple of 2 str): A list of tuples containing the paths to t...
[ "Perform", "a", "Globus", "Transfer", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L605-L802
train
This function is used to perform a custom Globus Transfer.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
quick_transfer
def quick_transfer(transfer_client, source_ep, dest_ep, path_list, interval=None, retries=10, notify=True): """Perform a Globus Transfer and monitor for success. Arguments: transfer_client (TransferClient): An authenticated Transfer client. source_ep (str): The source Globus ...
python
def quick_transfer(transfer_client, source_ep, dest_ep, path_list, interval=None, retries=10, notify=True): """Perform a Globus Transfer and monitor for success. Arguments: transfer_client (TransferClient): An authenticated Transfer client. source_ep (str): The source Globus ...
[ "def", "quick_transfer", "(", "transfer_client", ",", "source_ep", ",", "dest_ep", ",", "path_list", ",", "interval", "=", "None", ",", "retries", "=", "10", ",", "notify", "=", "True", ")", ":", "if", "retries", "is", "None", ":", "retries", "=", "0", ...
Perform a Globus Transfer and monitor for success. Arguments: transfer_client (TransferClient): An authenticated Transfer client. source_ep (str): The source Globus Endpoint ID. dest_ep (str): The destination Globus Endpoint ID. path_list (list of tuple of 2 str): A list of tuples c...
[ "Perform", "a", "Globus", "Transfer", "and", "monitor", "for", "success", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L805-L863
train
Perform a Globus Transfer and monitor for success.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
get_local_ep
def get_local_ep(*args, **kwargs): """ Warning: DEPRECATED: Use ``globus_sdk.LocalGlobusConnectPersonal().endpoint_id`` instead. """ if kwargs.get("warn", True): raise DeprecationWarning("'get_local_ep()' has been deprecated in favor of " "'globus_sdk.Loc...
python
def get_local_ep(*args, **kwargs): """ Warning: DEPRECATED: Use ``globus_sdk.LocalGlobusConnectPersonal().endpoint_id`` instead. """ if kwargs.get("warn", True): raise DeprecationWarning("'get_local_ep()' has been deprecated in favor of " "'globus_sdk.Loc...
[ "def", "get_local_ep", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "\"warn\"", ",", "True", ")", ":", "raise", "DeprecationWarning", "(", "\"'get_local_ep()' has been deprecated in favor of \"", "\"'globus_sdk.LocalGlobusCon...
Warning: DEPRECATED: Use ``globus_sdk.LocalGlobusConnectPersonal().endpoint_id`` instead.
[ "Warning", ":", "DEPRECATED", ":", "Use", "globus_sdk", ".", "LocalGlobusConnectPersonal", "()", ".", "endpoint_id", "instead", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L866-L879
train
Deprecated. Use globus_sdk. LocalGlobusConnectPersonal. endpoint_id instead.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
dict_merge
def dict_merge(base, addition, append_lists=False): """Merge one dictionary with another, recursively. Fields present in addition will be added to base if not present or merged if both values are dictionaries or lists (with append_lists=True). If the values are different data types, the value in additio...
python
def dict_merge(base, addition, append_lists=False): """Merge one dictionary with another, recursively. Fields present in addition will be added to base if not present or merged if both values are dictionaries or lists (with append_lists=True). If the values are different data types, the value in additio...
[ "def", "dict_merge", "(", "base", ",", "addition", ",", "append_lists", "=", "False", ")", ":", "if", "not", "isinstance", "(", "base", ",", "dict", ")", "or", "not", "isinstance", "(", "addition", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"d...
Merge one dictionary with another, recursively. Fields present in addition will be added to base if not present or merged if both values are dictionaries or lists (with append_lists=True). If the values are different data types, the value in addition will be discarded. No data from base is deleted or ov...
[ "Merge", "one", "dictionary", "with", "another", "recursively", ".", "Fields", "present", "in", "addition", "will", "be", "added", "to", "base", "if", "not", "present", "or", "merged", "if", "both", "values", "are", "dictionaries", "or", "lists", "(", "with"...
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L886-L930
train
Merge one dictionary with another recursively.
materials-data-facility/toolbox
mdf_toolbox/toolbox.py
insensitive_comparison
def insensitive_comparison(item1, item2, type_insensitive=False, string_insensitive=False): """Compare two items without regard to order. The following rules are used to determine equivalence: * Items that are not of the same type can be equivalent only when ``type_insensitive=True``. * Mapping...
python
def insensitive_comparison(item1, item2, type_insensitive=False, string_insensitive=False): """Compare two items without regard to order. The following rules are used to determine equivalence: * Items that are not of the same type can be equivalent only when ``type_insensitive=True``. * Mapping...
[ "def", "insensitive_comparison", "(", "item1", ",", "item2", ",", "type_insensitive", "=", "False", ",", "string_insensitive", "=", "False", ")", ":", "# If type-sensitive, check types", "if", "not", "type_insensitive", "and", "type", "(", "item1", ")", "!=", "typ...
Compare two items without regard to order. The following rules are used to determine equivalence: * Items that are not of the same type can be equivalent only when ``type_insensitive=True``. * Mapping objects are equal iff the keys in each item exist in both items and have the same value ...
[ "Compare", "two", "items", "without", "regard", "to", "order", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/toolbox.py#L933-L1071
train
Compare two items without regard to order.
tapilab/brandelion
brandelion/cli/analyze.py
parse_json
def parse_json(json_file, include_date=False): """ Yield screen_name, text tuples from a json file. """ if json_file[-2:] == 'gz': fh = gzip.open(json_file, 'rt') else: fh = io.open(json_file, mode='rt', encoding='utf8') for line in fh: try: jj = json.loads(line) ...
python
def parse_json(json_file, include_date=False): """ Yield screen_name, text tuples from a json file. """ if json_file[-2:] == 'gz': fh = gzip.open(json_file, 'rt') else: fh = io.open(json_file, mode='rt', encoding='utf8') for line in fh: try: jj = json.loads(line) ...
[ "def", "parse_json", "(", "json_file", ",", "include_date", "=", "False", ")", ":", "if", "json_file", "[", "-", "2", ":", "]", "==", "'gz'", ":", "fh", "=", "gzip", ".", "open", "(", "json_file", ",", "'rt'", ")", "else", ":", "fh", "=", "io", "...
Yield screen_name, text tuples from a json file.
[ "Yield", "screen_name", "text", "tuples", "from", "a", "json", "file", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L50-L71
train
Parse a json file and yield screen_name text tuples.
tapilab/brandelion
brandelion/cli/analyze.py
extract_tweets
def extract_tweets(json_file): """ Yield screen_name, string tuples, where the string is the concatenation of all tweets of this user. """ for screen_name, tweet_iter in groupby(parse_json(json_file), lambda x: x[0]): tweets = [t[1] for t in tweet_iter] yield screen_name, ' '.join(tweets)
python
def extract_tweets(json_file): """ Yield screen_name, string tuples, where the string is the concatenation of all tweets of this user. """ for screen_name, tweet_iter in groupby(parse_json(json_file), lambda x: x[0]): tweets = [t[1] for t in tweet_iter] yield screen_name, ' '.join(tweets)
[ "def", "extract_tweets", "(", "json_file", ")", ":", "for", "screen_name", ",", "tweet_iter", "in", "groupby", "(", "parse_json", "(", "json_file", ")", ",", "lambda", "x", ":", "x", "[", "0", "]", ")", ":", "tweets", "=", "[", "t", "[", "1", "]", ...
Yield screen_name, string tuples, where the string is the concatenation of all tweets of this user.
[ "Yield", "screen_name", "string", "tuples", "where", "the", "string", "is", "the", "concatenation", "of", "all", "tweets", "of", "this", "user", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L74-L79
train
Yield screen_name string tuples where the string is the concatenation of all tweets of this user.
tapilab/brandelion
brandelion/cli/analyze.py
preprocess
def preprocess(s): """ >>> preprocess('#hi there http://www.foo.com @you isn"t RT &lt;&gt;') 'hashtaghi hashtaghi there isn"t' """ # s = re.sub('@\S+', 'thisisamention', s) # map all mentions to thisisamention s = re.sub(r'@\S+', ' ', s) # map all mentions to thisisamention # s = re.sub('h...
python
def preprocess(s): """ >>> preprocess('#hi there http://www.foo.com @you isn"t RT &lt;&gt;') 'hashtaghi hashtaghi there isn"t' """ # s = re.sub('@\S+', 'thisisamention', s) # map all mentions to thisisamention s = re.sub(r'@\S+', ' ', s) # map all mentions to thisisamention # s = re.sub('h...
[ "def", "preprocess", "(", "s", ")", ":", "# s = re.sub('@\\S+', 'thisisamention', s) # map all mentions to thisisamention", "s", "=", "re", ".", "sub", "(", "r'@\\S+'", ",", "' '", ",", "s", ")", "# map all mentions to thisisamention", "# s = re.sub('http\\S+', 'http', s) #...
>>> preprocess('#hi there http://www.foo.com @you isn"t RT &lt;&gt;') 'hashtaghi hashtaghi there isn"t'
[ ">>>", "preprocess", "(", "#hi", "there", "http", ":", "//", "www", ".", "foo", ".", "com" ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L82-L96
train
Preprocess a string for use in a hashtag.
tapilab/brandelion
brandelion/cli/analyze.py
vectorize
def vectorize(json_file, vec, dofit=True): """ Return a matrix where each row corresponds to a Twitter account, and each column corresponds to the number of times a term is used by that account. """ ## CountVectorizer, efficiently. screen_names = [x[0] for x in extract_tweets(json_file)] if dofi...
python
def vectorize(json_file, vec, dofit=True): """ Return a matrix where each row corresponds to a Twitter account, and each column corresponds to the number of times a term is used by that account. """ ## CountVectorizer, efficiently. screen_names = [x[0] for x in extract_tweets(json_file)] if dofi...
[ "def", "vectorize", "(", "json_file", ",", "vec", ",", "dofit", "=", "True", ")", ":", "## CountVectorizer, efficiently.", "screen_names", "=", "[", "x", "[", "0", "]", "for", "x", "in", "extract_tweets", "(", "json_file", ")", "]", "if", "dofit", ":", "...
Return a matrix where each row corresponds to a Twitter account, and each column corresponds to the number of times a term is used by that account.
[ "Return", "a", "matrix", "where", "each", "row", "corresponds", "to", "a", "Twitter", "account", "and", "each", "column", "corresponds", "to", "the", "number", "of", "times", "a", "term", "is", "used", "by", "that", "account", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L99-L109
train
Vectorize the Tweets in a Twitter account.
tapilab/brandelion
brandelion/cli/analyze.py
read_follower_file
def read_follower_file(fname, min_followers=0, max_followers=1e10, blacklist=set()): """ Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids. """ result = {} with open(fname, 'rt') as f: for line in f: parts = line.split() ...
python
def read_follower_file(fname, min_followers=0, max_followers=1e10, blacklist=set()): """ Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids. """ result = {} with open(fname, 'rt') as f: for line in f: parts = line.split() ...
[ "def", "read_follower_file", "(", "fname", ",", "min_followers", "=", "0", ",", "max_followers", "=", "1e10", ",", "blacklist", "=", "set", "(", ")", ")", ":", "result", "=", "{", "}", "with", "open", "(", "fname", ",", "'rt'", ")", "as", "f", ":", ...
Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids.
[ "Read", "a", "file", "of", "follower", "information", "and", "return", "a", "dictionary", "mapping", "screen_name", "to", "a", "set", "of", "follower", "ids", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L171-L184
train
Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids.
tapilab/brandelion
brandelion/cli/analyze.py
iter_follower_file
def iter_follower_file(fname): """ Iterator from a file of follower information and return a tuple of screen_name, follower ids. File format is: <iso timestamp> <screen_name> <follower_id1> <follower_ids2> ... """ with open(fname, 'rt') as f: for line in f: parts = line.split() ...
python
def iter_follower_file(fname): """ Iterator from a file of follower information and return a tuple of screen_name, follower ids. File format is: <iso timestamp> <screen_name> <follower_id1> <follower_ids2> ... """ with open(fname, 'rt') as f: for line in f: parts = line.split() ...
[ "def", "iter_follower_file", "(", "fname", ")", ":", "with", "open", "(", "fname", ",", "'rt'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "parts", "=", "line", ".", "split", "(", ")", "if", "len", "(", "parts", ")", ">", "3", ":", "yi...
Iterator from a file of follower information and return a tuple of screen_name, follower ids. File format is: <iso timestamp> <screen_name> <follower_id1> <follower_ids2> ...
[ "Iterator", "from", "a", "file", "of", "follower", "information", "and", "return", "a", "tuple", "of", "screen_name", "follower", "ids", ".", "File", "format", "is", ":", "<iso", "timestamp", ">", "<screen_name", ">", "<follower_id1", ">", "<follower_ids2", ">...
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L187-L196
train
Iterator from a file of follower information and return a tuple of screen_name follower ids.
tapilab/brandelion
brandelion/cli/analyze.py
jaccard_merge
def jaccard_merge(brands, exemplars): """ Return the average Jaccard similarity between a brand's followers and the followers of each exemplar. We merge all exemplar followers into one big pseudo-account.""" scores = {} exemplar_followers = set() for followers in exemplars.values(): exem...
python
def jaccard_merge(brands, exemplars): """ Return the average Jaccard similarity between a brand's followers and the followers of each exemplar. We merge all exemplar followers into one big pseudo-account.""" scores = {} exemplar_followers = set() for followers in exemplars.values(): exem...
[ "def", "jaccard_merge", "(", "brands", ",", "exemplars", ")", ":", "scores", "=", "{", "}", "exemplar_followers", "=", "set", "(", ")", "for", "followers", "in", "exemplars", ".", "values", "(", ")", ":", "exemplar_followers", "|=", "followers", "for", "br...
Return the average Jaccard similarity between a brand's followers and the followers of each exemplar. We merge all exemplar followers into one big pseudo-account.
[ "Return", "the", "average", "Jaccard", "similarity", "between", "a", "brand", "s", "followers", "and", "the", "followers", "of", "each", "exemplar", ".", "We", "merge", "all", "exemplar", "followers", "into", "one", "big", "pseudo", "-", "account", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L235-L246
train
Return the average Jaccard similarity between a brand s followers and an exemplar s followers and the followers of each exemplar. We merge all followers of each brand into one .
tapilab/brandelion
brandelion/cli/analyze.py
compute_log_degrees
def compute_log_degrees(brands, exemplars): """ For each follower, let Z be the total number of brands they follow. Return a dictionary of 1. / log(Z), for each follower. """ counts = Counter() for followers in brands.values(): # + exemplars.values(): # Include exemplars in these counts? No, don't...
python
def compute_log_degrees(brands, exemplars): """ For each follower, let Z be the total number of brands they follow. Return a dictionary of 1. / log(Z), for each follower. """ counts = Counter() for followers in brands.values(): # + exemplars.values(): # Include exemplars in these counts? No, don't...
[ "def", "compute_log_degrees", "(", "brands", ",", "exemplars", ")", ":", "counts", "=", "Counter", "(", ")", "for", "followers", "in", "brands", ".", "values", "(", ")", ":", "# + exemplars.values(): # Include exemplars in these counts? No, don't want to penalize people ...
For each follower, let Z be the total number of brands they follow. Return a dictionary of 1. / log(Z), for each follower.
[ "For", "each", "follower", "let", "Z", "be", "the", "total", "number", "of", "brands", "they", "follow", ".", "Return", "a", "dictionary", "of", "1", ".", "/", "log", "(", "Z", ")", "for", "each", "follower", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L249-L259
train
Compute the log degrees of each follower.
tapilab/brandelion
brandelion/cli/analyze.py
proportion_merge
def proportion_merge(brands, exemplars): """ Return the proportion of a brand's followers who also follower an exemplar. We merge all exemplar followers into one big pseudo-account.""" scores = {} exemplar_followers = set() for followers in exemplars.values(): exemplar_followers |= followers...
python
def proportion_merge(brands, exemplars): """ Return the proportion of a brand's followers who also follower an exemplar. We merge all exemplar followers into one big pseudo-account.""" scores = {} exemplar_followers = set() for followers in exemplars.values(): exemplar_followers |= followers...
[ "def", "proportion_merge", "(", "brands", ",", "exemplars", ")", ":", "scores", "=", "{", "}", "exemplar_followers", "=", "set", "(", ")", "for", "followers", "in", "exemplars", ".", "values", "(", ")", ":", "exemplar_followers", "|=", "followers", "for", ...
Return the proportion of a brand's followers who also follower an exemplar. We merge all exemplar followers into one big pseudo-account.
[ "Return", "the", "proportion", "of", "a", "brand", "s", "followers", "who", "also", "follower", "an", "exemplar", ".", "We", "merge", "all", "exemplar", "followers", "into", "one", "big", "pseudo", "-", "account", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L298-L308
train
Return the proportion of a brand s followers who also follower an exemplar. We merge all followers who also follower an exemplar. We merge all exemplar followers into one big pseudo - account.
tapilab/brandelion
brandelion/cli/analyze.py
_cosine
def _cosine(a, b): """ Return the len(a & b) / len(a) """ return 1. * len(a & b) / (math.sqrt(len(a)) * math.sqrt(len(b)))
python
def _cosine(a, b): """ Return the len(a & b) / len(a) """ return 1. * len(a & b) / (math.sqrt(len(a)) * math.sqrt(len(b)))
[ "def", "_cosine", "(", "a", ",", "b", ")", ":", "return", "1.", "*", "len", "(", "a", "&", "b", ")", "/", "(", "math", ".", "sqrt", "(", "len", "(", "a", ")", ")", "*", "math", ".", "sqrt", "(", "len", "(", "b", ")", ")", ")" ]
Return the len(a & b) / len(a)
[ "Return", "the", "len", "(", "a", "&", "b", ")", "/", "len", "(", "a", ")" ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L314-L316
train
Return the cosine of two sequence elements.
tapilab/brandelion
brandelion/cli/analyze.py
cosine
def cosine(brands, exemplars, weighted_avg=False, sqrt=False): """ Return the cosine similarity betwee a brand's followers and the exemplars. """ scores = {} for brand, followers in brands: if weighted_avg: scores[brand] = np.average([_cosine(followers, others) for others in exem...
python
def cosine(brands, exemplars, weighted_avg=False, sqrt=False): """ Return the cosine similarity betwee a brand's followers and the exemplars. """ scores = {} for brand, followers in brands: if weighted_avg: scores[brand] = np.average([_cosine(followers, others) for others in exem...
[ "def", "cosine", "(", "brands", ",", "exemplars", ",", "weighted_avg", "=", "False", ",", "sqrt", "=", "False", ")", ":", "scores", "=", "{", "}", "for", "brand", ",", "followers", "in", "brands", ":", "if", "weighted_avg", ":", "scores", "[", "brand",...
Return the cosine similarity betwee a brand's followers and the exemplars.
[ "Return", "the", "cosine", "similarity", "betwee", "a", "brand", "s", "followers", "and", "the", "exemplars", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L319-L332
train
Return the cosine similarity betwee a brand s followers and the exemplars.
tapilab/brandelion
brandelion/cli/analyze.py
cosine_merge
def cosine_merge(brands, exemplars): """ Return the proportion of a brand's followers who also follower an exemplar. We merge all exemplar followers into one big pseudo-account.""" scores = {} exemplar_followers = set() for followers in exemplars.values(): exemplar_followers |= followers ...
python
def cosine_merge(brands, exemplars): """ Return the proportion of a brand's followers who also follower an exemplar. We merge all exemplar followers into one big pseudo-account.""" scores = {} exemplar_followers = set() for followers in exemplars.values(): exemplar_followers |= followers ...
[ "def", "cosine_merge", "(", "brands", ",", "exemplars", ")", ":", "scores", "=", "{", "}", "exemplar_followers", "=", "set", "(", ")", "for", "followers", "in", "exemplars", ".", "values", "(", ")", ":", "exemplar_followers", "|=", "followers", "for", "bra...
Return the proportion of a brand's followers who also follower an exemplar. We merge all exemplar followers into one big pseudo-account.
[ "Return", "the", "proportion", "of", "a", "brand", "s", "followers", "who", "also", "follower", "an", "exemplar", ".", "We", "merge", "all", "exemplar", "followers", "into", "one", "big", "pseudo", "-", "account", "." ]
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L347-L357
train
Return the proportion of a brand s followers who also follower an exemplar. We merge all followers who also follower an exemplar. We merge all exemplar followers into one big pseudo - account.
tapilab/brandelion
brandelion/cli/analyze.py
adamic
def adamic(brands, exemplars): """ Return the average Adamic/Adar similarity between a brand's followers and the followers of each exemplar. We approximate the number of followed accounts per user by only considering those in our brand set.""" print('adamic deprecated...requires loading all brands in me...
python
def adamic(brands, exemplars): """ Return the average Adamic/Adar similarity between a brand's followers and the followers of each exemplar. We approximate the number of followed accounts per user by only considering those in our brand set.""" print('adamic deprecated...requires loading all brands in me...
[ "def", "adamic", "(", "brands", ",", "exemplars", ")", ":", "print", "(", "'adamic deprecated...requires loading all brands in memory.'", ")", "return", "degrees", "=", "compute_log_degrees", "(", "brands", ",", "exemplars", ")", "scores", "=", "{", "}", "exemplar_s...
Return the average Adamic/Adar similarity between a brand's followers and the followers of each exemplar. We approximate the number of followed accounts per user by only considering those in our brand set.
[ "Return", "the", "average", "Adamic", "/", "Adar", "similarity", "between", "a", "brand", "s", "followers", "and", "the", "followers", "of", "each", "exemplar", ".", "We", "approximate", "the", "number", "of", "followed", "accounts", "per", "user", "by", "on...
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L360-L376
train
Return the average Adamic / Adar similarity between a brand s followers and the followers of each exemplar.
tapilab/brandelion
brandelion/cli/analyze.py
compute_rarity_scores
def compute_rarity_scores(exemplars): """ Compute a score for each follower that is sum_i (1/n_i), where n_i is the degree of the ith exemplar they follow. >>> compute_rarity_scores({'e1':{1,2,3,4}, 'e2':{4,5}}).items() [(1, 0.25), (2, 0.25), (3, 0.25), (4, 0.75), (5, 0.5)] """ scores = defaultd...
python
def compute_rarity_scores(exemplars): """ Compute a score for each follower that is sum_i (1/n_i), where n_i is the degree of the ith exemplar they follow. >>> compute_rarity_scores({'e1':{1,2,3,4}, 'e2':{4,5}}).items() [(1, 0.25), (2, 0.25), (3, 0.25), (4, 0.75), (5, 0.5)] """ scores = defaultd...
[ "def", "compute_rarity_scores", "(", "exemplars", ")", ":", "scores", "=", "defaultdict", "(", "lambda", ":", "0.", ")", "for", "followers", "in", "exemplars", ".", "values", "(", ")", ":", "score", "=", "1.", "/", "len", "(", "followers", ")", "for", ...
Compute a score for each follower that is sum_i (1/n_i), where n_i is the degree of the ith exemplar they follow. >>> compute_rarity_scores({'e1':{1,2,3,4}, 'e2':{4,5}}).items() [(1, 0.25), (2, 0.25), (3, 0.25), (4, 0.75), (5, 0.5)]
[ "Compute", "a", "score", "for", "each", "follower", "that", "is", "sum_i", "(", "1", "/", "n_i", ")", "where", "n_i", "is", "the", "degree", "of", "the", "ith", "exemplar", "they", "follow", ".", ">>>", "compute_rarity_scores", "(", "{", "e1", ":", "{"...
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L379-L390
train
Compute a score for each follower that is sum_i ( 1 / n_i ) where n_i is the degree of the ith exemplar they follow.
tapilab/brandelion
brandelion/cli/analyze.py
rarity
def rarity(brands, exemplars): """ Compute a score for each follower that is sum_i (1/n_i), where n_i is the degree of the ith exemplar they follow. The score for a brand is then the average of their follower scores.""" rarity = compute_rarity_scores(exemplars) scores = {} for brand, followers in br...
python
def rarity(brands, exemplars): """ Compute a score for each follower that is sum_i (1/n_i), where n_i is the degree of the ith exemplar they follow. The score for a brand is then the average of their follower scores.""" rarity = compute_rarity_scores(exemplars) scores = {} for brand, followers in br...
[ "def", "rarity", "(", "brands", ",", "exemplars", ")", ":", "rarity", "=", "compute_rarity_scores", "(", "exemplars", ")", "scores", "=", "{", "}", "for", "brand", ",", "followers", "in", "brands", ":", "scores", "[", "brand", "]", "=", "sum", "(", "ra...
Compute a score for each follower that is sum_i (1/n_i), where n_i is the degree of the ith exemplar they follow. The score for a brand is then the average of their follower scores.
[ "Compute", "a", "score", "for", "each", "follower", "that", "is", "sum_i", "(", "1", "/", "n_i", ")", "where", "n_i", "is", "the", "degree", "of", "the", "ith", "exemplar", "they", "follow", ".", "The", "score", "for", "a", "brand", "is", "then", "th...
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L393-L400
train
Compute a score for each follower that is sum_i ( 1 / n_i where n_i is the degree of the ith exemplar they follow.
tapilab/brandelion
brandelion/cli/analyze.py
compute_rarity_scores_log
def compute_rarity_scores_log(exemplars): """ Compute a score for each follower that is sum_i (1/n_i), where n_i is the degree of the ith exemplar they follow. >>> compute_rarity_scores({'e1':{1,2,3,4}, 'e2':{4,5}}).items() [(1, 0.25), (2, 0.25), (3, 0.25), (4, 0.75), (5, 0.5)] """ scores = defa...
python
def compute_rarity_scores_log(exemplars): """ Compute a score for each follower that is sum_i (1/n_i), where n_i is the degree of the ith exemplar they follow. >>> compute_rarity_scores({'e1':{1,2,3,4}, 'e2':{4,5}}).items() [(1, 0.25), (2, 0.25), (3, 0.25), (4, 0.75), (5, 0.5)] """ scores = defa...
[ "def", "compute_rarity_scores_log", "(", "exemplars", ")", ":", "scores", "=", "defaultdict", "(", "lambda", ":", "0.", ")", "for", "followers", "in", "exemplars", ".", "values", "(", ")", ":", "score", "=", "1.", "/", "math", ".", "log", "(", "len", "...
Compute a score for each follower that is sum_i (1/n_i), where n_i is the degree of the ith exemplar they follow. >>> compute_rarity_scores({'e1':{1,2,3,4}, 'e2':{4,5}}).items() [(1, 0.25), (2, 0.25), (3, 0.25), (4, 0.75), (5, 0.5)]
[ "Compute", "a", "score", "for", "each", "follower", "that", "is", "sum_i", "(", "1", "/", "n_i", ")", "where", "n_i", "is", "the", "degree", "of", "the", "ith", "exemplar", "they", "follow", ".", ">>>", "compute_rarity_scores", "(", "{", "e1", ":", "{"...
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L403-L414
train
Compute a score for each follower that is sum_i ( 1 / n_i ) where n_i is the degree of the ith exemplar they follow.
tapilab/brandelion
brandelion/cli/analyze.py
rarity_log
def rarity_log(brands, exemplars): """ Compute a score for each follower that is sum_i (1/log(n_i)), where n_i is the degree of the ith exemplar they follow. The score for a brand is then the average of their follower scores.""" rarity = compute_rarity_scores_log(exemplars) scores = {} for brand, fo...
python
def rarity_log(brands, exemplars): """ Compute a score for each follower that is sum_i (1/log(n_i)), where n_i is the degree of the ith exemplar they follow. The score for a brand is then the average of their follower scores.""" rarity = compute_rarity_scores_log(exemplars) scores = {} for brand, fo...
[ "def", "rarity_log", "(", "brands", ",", "exemplars", ")", ":", "rarity", "=", "compute_rarity_scores_log", "(", "exemplars", ")", "scores", "=", "{", "}", "for", "brand", ",", "followers", "in", "brands", ":", "scores", "[", "brand", "]", "=", "sum", "(...
Compute a score for each follower that is sum_i (1/log(n_i)), where n_i is the degree of the ith exemplar they follow. The score for a brand is then the average of their follower scores.
[ "Compute", "a", "score", "for", "each", "follower", "that", "is", "sum_i", "(", "1", "/", "log", "(", "n_i", "))", "where", "n_i", "is", "the", "degree", "of", "the", "ith", "exemplar", "they", "follow", ".", "The", "score", "for", "a", "brand", "is"...
40a5a5333cf704182c8666d1fbbbdadc7ff88546
https://github.com/tapilab/brandelion/blob/40a5a5333cf704182c8666d1fbbbdadc7ff88546/brandelion/cli/analyze.py#L417-L424
train
Compute a score for each follower that is sum_i ( 1 / log ( n_i ) where n_i is the degree of the ith exemplar they follow.
thebigmunch/google-music-utils
src/google_music_utils/misc.py
suggest_filename
def suggest_filename(metadata): """Generate a filename like Google for a song based on metadata. Parameters: metadata (~collections.abc.Mapping): A metadata dict. Returns: str: A filename string without an extension. """ if 'title' in metadata and 'track_number' in metadata: # Music Manager. suggested_fi...
python
def suggest_filename(metadata): """Generate a filename like Google for a song based on metadata. Parameters: metadata (~collections.abc.Mapping): A metadata dict. Returns: str: A filename string without an extension. """ if 'title' in metadata and 'track_number' in metadata: # Music Manager. suggested_fi...
[ "def", "suggest_filename", "(", "metadata", ")", ":", "if", "'title'", "in", "metadata", "and", "'track_number'", "in", "metadata", ":", "# Music Manager.", "suggested_filename", "=", "f\"{metadata['track_number']:0>2} {metadata['title']}\"", "elif", "'title'", "in", "met...
Generate a filename like Google for a song based on metadata. Parameters: metadata (~collections.abc.Mapping): A metadata dict. Returns: str: A filename string without an extension.
[ "Generate", "a", "filename", "like", "Google", "for", "a", "song", "based", "on", "metadata", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/misc.py#L25-L51
train
Suggest a filename based on metadata.
thebigmunch/google-music-utils
src/google_music_utils/misc.py
template_to_filepath
def template_to_filepath(template, metadata, template_patterns=None): """Create directory structure and file name based on metadata template. Note: A template meant to be a base directory for suggested names should have a trailing slash or backslash. Parameters: template (str or ~os.PathLike): A filepath whic...
python
def template_to_filepath(template, metadata, template_patterns=None): """Create directory structure and file name based on metadata template. Note: A template meant to be a base directory for suggested names should have a trailing slash or backslash. Parameters: template (str or ~os.PathLike): A filepath whic...
[ "def", "template_to_filepath", "(", "template", ",", "metadata", ",", "template_patterns", "=", "None", ")", ":", "path", "=", "Path", "(", "template", ")", "if", "template_patterns", "is", "None", ":", "template_patterns", "=", "TEMPLATE_PATTERNS", "suggested_fil...
Create directory structure and file name based on metadata template. Note: A template meant to be a base directory for suggested names should have a trailing slash or backslash. Parameters: template (str or ~os.PathLike): A filepath which can include template patterns as defined by :param template_patterns:. ...
[ "Create", "directory", "structure", "and", "file", "name", "based", "on", "metadata", "template", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/misc.py#L54-L138
train
Create a filepath based on a template.
thebigmunch/google-music-utils
src/google_music_utils/filter.py
_match_field
def _match_field(field_value, pattern, ignore_case=False, normalize_values=False): """Match an item metadata field value by pattern. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: field_value (list or str): A metad...
python
def _match_field(field_value, pattern, ignore_case=False, normalize_values=False): """Match an item metadata field value by pattern. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: field_value (list or str): A metad...
[ "def", "_match_field", "(", "field_value", ",", "pattern", ",", "ignore_case", "=", "False", ",", "normalize_values", "=", "False", ")", ":", "if", "normalize_values", ":", "ignore_case", "=", "True", "normalize", "=", "normalize_value", "if", "normalize_values", ...
Match an item metadata field value by pattern. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: field_value (list or str): A metadata field value to check. pattern (str): A regex pattern to check the field value(s) ...
[ "Match", "an", "item", "metadata", "field", "value", "by", "pattern", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/filter.py#L14-L43
train
Match an item metadata field value by pattern.
thebigmunch/google-music-utils
src/google_music_utils/filter.py
_match_item
def _match_item(item, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Match items by metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: item (~collections.abc.Mapping, str, os.PathLike):...
python
def _match_item(item, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Match items by metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: item (~collections.abc.Mapping, str, os.PathLike):...
[ "def", "_match_item", "(", "item", ",", "any_all", "=", "any", ",", "ignore_case", "=", "False", ",", "normalize_values", "=", "False", ",", "*", "*", "kwargs", ")", ":", "it", "=", "get_item_tags", "(", "item", ")", "return", "any_all", "(", "_match_fie...
Match items by metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: item (~collections.abc.Mapping, str, os.PathLike): Item dict or filepath. any_all (callable): A callable to determine if any or all filters m...
[ "Match", "items", "by", "metadata", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/filter.py#L46-L73
train
Match items by metadata.
thebigmunch/google-music-utils
src/google_music_utils/filter.py
exclude_items
def exclude_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Exclude items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts o...
python
def exclude_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Exclude items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts o...
[ "def", "exclude_items", "(", "items", ",", "any_all", "=", "any", ",", "ignore_case", "=", "False", ",", "normalize_values", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "match", "=", "functools", ".", "partial", "(", "_match_ite...
Exclude items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts or filepaths. any_all (callable): A callable to determine if any or all filters must match to e...
[ "Exclude", "items", "by", "matching", "metadata", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/filter.py#L76-L108
train
Exclude items from a list of dicts or filepaths.
thebigmunch/google-music-utils
src/google_music_utils/filter.py
include_items
def include_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Include items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts o...
python
def include_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs): """Include items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts o...
[ "def", "include_items", "(", "items", ",", "any_all", "=", "any", ",", "ignore_case", "=", "False", ",", "normalize_values", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ":", "match", "=", "functools", ".", "partial", "(", "_match_ite...
Include items by matching metadata. Note: Metadata values are lowercased when ``normalized_values`` is ``True``, so ``ignore_case`` is automatically set to ``True``. Parameters: items (list): A list of item dicts or filepaths. any_all (callable): A callable to determine if any or all filters must match to i...
[ "Include", "items", "by", "matching", "metadata", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/filter.py#L111-L143
train
Include items by matching metadata.
IRC-SPHERE/HyperStream
hyperstream/utils/statistics/percentile.py
percentile
def percentile(a, q): """ Compute the qth percentile of the data along the specified axis. Simpler version than the numpy version that always flattens input arrays. Examples -------- >>> a = [[10, 7, 4], [3, 2, 1]] >>> percentile(a, 20) 2.0 >>> percentile(a, 50) 3.5 >>> perc...
python
def percentile(a, q): """ Compute the qth percentile of the data along the specified axis. Simpler version than the numpy version that always flattens input arrays. Examples -------- >>> a = [[10, 7, 4], [3, 2, 1]] >>> percentile(a, 20) 2.0 >>> percentile(a, 50) 3.5 >>> perc...
[ "def", "percentile", "(", "a", ",", "q", ")", ":", "if", "not", "a", ":", "return", "None", "if", "isinstance", "(", "q", ",", "(", "float", ",", "int", ")", ")", ":", "qq", "=", "[", "q", "]", "elif", "isinstance", "(", "q", ",", "(", "tuple...
Compute the qth percentile of the data along the specified axis. Simpler version than the numpy version that always flattens input arrays. Examples -------- >>> a = [[10, 7, 4], [3, 2, 1]] >>> percentile(a, 20) 2.0 >>> percentile(a, 50) 3.5 >>> percentile(a, [20, 80]) [2.0, 7.0]...
[ "Compute", "the", "qth", "percentile", "of", "the", "data", "along", "the", "specified", "axis", ".", "Simpler", "version", "than", "the", "numpy", "version", "that", "always", "flattens", "input", "arrays", "." ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/statistics/percentile.py#L33-L90
train
Compute the qth percentile of the data along the specified axis.
dgomes/pyipma
pyipma/station.py
Station._filter_closest
def _filter_closest(self, lat, lon, stations): """Helper to filter the closest station to a given location.""" current_location = (lat, lon) closest = None closest_distance = None for station in stations: station_loc = (station.latitude, station.longitude) ...
python
def _filter_closest(self, lat, lon, stations): """Helper to filter the closest station to a given location.""" current_location = (lat, lon) closest = None closest_distance = None for station in stations: station_loc = (station.latitude, station.longitude) ...
[ "def", "_filter_closest", "(", "self", ",", "lat", ",", "lon", ",", "stations", ")", ":", "current_location", "=", "(", "lat", ",", "lon", ")", "closest", "=", "None", "closest_distance", "=", "None", "for", "station", "in", "stations", ":", "station_loc",...
Helper to filter the closest station to a given location.
[ "Helper", "to", "filter", "the", "closest", "station", "to", "a", "given", "location", "." ]
cd808abeb70dca0e336afdf55bef3f73973eaa71
https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/station.py#L20-L34
train
Helper to filter the closest station to a given location.
dgomes/pyipma
pyipma/station.py
Station.get
async def get(cls, websession, lat, lon): """Retrieve the nearest station.""" self = Station(websession) stations = await self.api.stations() self.station = self._filter_closest(lat, lon, stations) logger.info("Using %s as weather station", self.station.local) ...
python
async def get(cls, websession, lat, lon): """Retrieve the nearest station.""" self = Station(websession) stations = await self.api.stations() self.station = self._filter_closest(lat, lon, stations) logger.info("Using %s as weather station", self.station.local) ...
[ "async", "def", "get", "(", "cls", ",", "websession", ",", "lat", ",", "lon", ")", ":", "self", "=", "Station", "(", "websession", ")", "stations", "=", "await", "self", ".", "api", ".", "stations", "(", ")", "self", ".", "station", "=", "self", "....
Retrieve the nearest station.
[ "Retrieve", "the", "nearest", "station", "." ]
cd808abeb70dca0e336afdf55bef3f73973eaa71
https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/station.py#L37-L48
train
Retrieve the nearest station.
dgomes/pyipma
pyipma/station.py
Station.forecast
async def forecast(self): """Retrieve next 5 days forecast.""" _forecasts = await self.api.forecast(self.station.globalIdLocal) return _forecasts
python
async def forecast(self): """Retrieve next 5 days forecast.""" _forecasts = await self.api.forecast(self.station.globalIdLocal) return _forecasts
[ "async", "def", "forecast", "(", "self", ")", ":", "_forecasts", "=", "await", "self", ".", "api", ".", "forecast", "(", "self", ".", "station", ".", "globalIdLocal", ")", "return", "_forecasts" ]
Retrieve next 5 days forecast.
[ "Retrieve", "next", "5", "days", "forecast", "." ]
cd808abeb70dca0e336afdf55bef3f73973eaa71
https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/station.py#L70-L75
train
Retrieve next 5 days forecast.
dgomes/pyipma
pyipma/station.py
Station.observation
async def observation(self): """Retrieve current weather observation.""" try: observations = await self.api.observations() except: return self._last_observation closest = self._filter_closest(self.station.latitude, self.sta...
python
async def observation(self): """Retrieve current weather observation.""" try: observations = await self.api.observations() except: return self._last_observation closest = self._filter_closest(self.station.latitude, self.sta...
[ "async", "def", "observation", "(", "self", ")", ":", "try", ":", "observations", "=", "await", "self", ".", "api", ".", "observations", "(", ")", "except", ":", "return", "self", ".", "_last_observation", "closest", "=", "self", ".", "_filter_closest", "(...
Retrieve current weather observation.
[ "Retrieve", "current", "weather", "observation", "." ]
cd808abeb70dca0e336afdf55bef3f73973eaa71
https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/station.py#L77-L92
train
Retrieve current weather observation.
IRC-SPHERE/HyperStream
hyperstream/plugin_manager.py
Plugin.load_channels
def load_channels(self): """ Loads the channels and tools given the plugin path specified :return: The loaded channels, including a tool channel, for the tools found. """ channels = [] # Try to get channels for channel_name in self.channel_names: cha...
python
def load_channels(self): """ Loads the channels and tools given the plugin path specified :return: The loaded channels, including a tool channel, for the tools found. """ channels = [] # Try to get channels for channel_name in self.channel_names: cha...
[ "def", "load_channels", "(", "self", ")", ":", "channels", "=", "[", "]", "# Try to get channels", "for", "channel_name", "in", "self", ".", "channel_names", ":", "channel_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "\"channe...
Loads the channels and tools given the plugin path specified :return: The loaded channels, including a tool channel, for the tools found.
[ "Loads", "the", "channels", "and", "tools", "given", "the", "plugin", "path", "specified" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/plugin_manager.py#L38-L76
train
Loads the channels and tools given the plugin path specified
nsfmc/swatch
swatch/writer.py
chunk_count
def chunk_count(swatch): """return the number of byte-chunks in a swatch object this recursively walks the swatch list, returning 1 for a single color & returns 2 for each folder plus 1 for each color it contains """ if type(swatch) is dict: if 'data' in swatch: return 1 ...
python
def chunk_count(swatch): """return the number of byte-chunks in a swatch object this recursively walks the swatch list, returning 1 for a single color & returns 2 for each folder plus 1 for each color it contains """ if type(swatch) is dict: if 'data' in swatch: return 1 ...
[ "def", "chunk_count", "(", "swatch", ")", ":", "if", "type", "(", "swatch", ")", "is", "dict", ":", "if", "'data'", "in", "swatch", ":", "return", "1", "if", "'swatches'", "in", "swatch", ":", "return", "2", "+", "len", "(", "swatch", "[", "'swatches...
return the number of byte-chunks in a swatch object this recursively walks the swatch list, returning 1 for a single color & returns 2 for each folder plus 1 for each color it contains
[ "return", "the", "number", "of", "byte", "-", "chunks", "in", "a", "swatch", "object" ]
8654edf4f1aeef37d42211ff3fe6a3e9e4325859
https://github.com/nsfmc/swatch/blob/8654edf4f1aeef37d42211ff3fe6a3e9e4325859/swatch/writer.py#L18-L30
train
return the number of byte - chunks in a swatch object
nsfmc/swatch
swatch/writer.py
chunk_for_color
def chunk_for_color(obj): """builds up a byte-chunk for a color the format for this is b'\x00\x01' + Big-Endian Unsigned Int == len(bytes that follow in this block) • Big-Endian Unsigned Short == len(color_name) in practice, because utf-16 takes up 2 bytes per letter ...
python
def chunk_for_color(obj): """builds up a byte-chunk for a color the format for this is b'\x00\x01' + Big-Endian Unsigned Int == len(bytes that follow in this block) • Big-Endian Unsigned Short == len(color_name) in practice, because utf-16 takes up 2 bytes per letter ...
[ "def", "chunk_for_color", "(", "obj", ")", ":", "title", "=", "obj", "[", "'name'", "]", "+", "'\\0'", "title_length", "=", "len", "(", "title", ")", "chunk", "=", "struct", ".", "pack", "(", "'>H'", ",", "title_length", ")", "chunk", "+=", "title", ...
builds up a byte-chunk for a color the format for this is b'\x00\x01' + Big-Endian Unsigned Int == len(bytes that follow in this block) • Big-Endian Unsigned Short == len(color_name) in practice, because utf-16 takes up 2 bytes per letter this will be 2 * (len(...
[ "builds", "up", "a", "byte", "-", "chunk", "for", "a", "color" ]
8654edf4f1aeef37d42211ff3fe6a3e9e4325859
https://github.com/nsfmc/swatch/blob/8654edf4f1aeef37d42211ff3fe6a3e9e4325859/swatch/writer.py#L39-L83
train
builds up a byte - chunk for a color object