repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
google/grr | grr/server/grr_response_server/timeseries.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/timeseries.py#L73-L89 | def FilterRange(self, start_time=None, stop_time=None):
"""Filter the series to lie between start_time and stop_time.
Removes all values of the series which are outside of some time range.
Args:
start_time: If set, timestamps before start_time will be dropped.
stop_time: If set, timestamps at ... | [
"def",
"FilterRange",
"(",
"self",
",",
"start_time",
"=",
"None",
",",
"stop_time",
"=",
"None",
")",
":",
"start_time",
"=",
"self",
".",
"_NormalizeTime",
"(",
"start_time",
")",
"stop_time",
"=",
"self",
".",
"_NormalizeTime",
"(",
"stop_time",
")",
"s... | Filter the series to lie between start_time and stop_time.
Removes all values of the series which are outside of some time range.
Args:
start_time: If set, timestamps before start_time will be dropped.
stop_time: If set, timestamps at or past stop_time will be dropped. | [
"Filter",
"the",
"series",
"to",
"lie",
"between",
"start_time",
"and",
"stop_time",
"."
] | python | train |
ASMfreaK/habitipy | habitipy/api.py | https://github.com/ASMfreaK/habitipy/blob/555b8b20faf6d553353092614a8a0d612f0adbde/habitipy/api.py#L389-L397 | def render_docstring(self):
"""make a nice docstring for ipython"""
res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self)
if self.params:
for group, params in self.params.items():
res += '\n' + group + ' params:\n'
for param in params.v... | [
"def",
"render_docstring",
"(",
"self",
")",
":",
"res",
"=",
"'{{{self.method}}} {self.uri} {self.title}\\n'",
".",
"format",
"(",
"self",
"=",
"self",
")",
"if",
"self",
".",
"params",
":",
"for",
"group",
",",
"params",
"in",
"self",
".",
"params",
".",
... | make a nice docstring for ipython | [
"make",
"a",
"nice",
"docstring",
"for",
"ipython"
] | python | train |
murphy214/berrl | build/lib/berrl/pipegeohash.py | https://github.com/murphy214/berrl/blob/ce4d060cc7db74c32facc538fa1d7030f1a27467/build/lib/berrl/pipegeohash.py#L265-L331 | def make_geohash_tables(table,listofprecisions,**kwargs):
'''
sort_by - field to sort by for each group
return_squares - boolean arg if true returns a list of squares instead of writing out to table
'''
return_squares = False
sort_by = 'COUNT'
# logic for accepting kwarg inputs
for key,value in kwargs.iteritems... | [
"def",
"make_geohash_tables",
"(",
"table",
",",
"listofprecisions",
",",
"*",
"*",
"kwargs",
")",
":",
"return_squares",
"=",
"False",
"sort_by",
"=",
"'COUNT'",
"# logic for accepting kwarg inputs",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
... | sort_by - field to sort by for each group
return_squares - boolean arg if true returns a list of squares instead of writing out to table | [
"sort_by",
"-",
"field",
"to",
"sort",
"by",
"for",
"each",
"group",
"return_squares",
"-",
"boolean",
"arg",
"if",
"true",
"returns",
"a",
"list",
"of",
"squares",
"instead",
"of",
"writing",
"out",
"to",
"table"
] | python | train |
apache/incubator-heron | third_party/python/cpplint/cpplint.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L6299-L6305 | def PrintCategories():
"""Prints a list of all the error-categories used by error messages.
These are the categories used to filter messages via --filter.
"""
sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
sys.exit(0) | [
"def",
"PrintCategories",
"(",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"''",
".",
"join",
"(",
"' %s\\n'",
"%",
"cat",
"for",
"cat",
"in",
"_ERROR_CATEGORIES",
")",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | Prints a list of all the error-categories used by error messages.
These are the categories used to filter messages via --filter. | [
"Prints",
"a",
"list",
"of",
"all",
"the",
"error",
"-",
"categories",
"used",
"by",
"error",
"messages",
"."
] | python | valid |
manahl/arctic | arctic/store/_ndarray_store.py | https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/store/_ndarray_store.py#L198-L208 | def _fw_pointers_convert_append_to_write(previous_version):
"""
This method decides whether to convert an append to a full write in order to avoid data integrity errors
"""
# Switching from ENABLED --> DISABLED/HYBRID when appending can cause integrity errors for subsequent reads:
# - Assume the ... | [
"def",
"_fw_pointers_convert_append_to_write",
"(",
"previous_version",
")",
":",
"# Switching from ENABLED --> DISABLED/HYBRID when appending can cause integrity errors for subsequent reads:",
"# - Assume the last write was done with ENABLED (segments don't have parent references updated).",
"# ... | This method decides whether to convert an append to a full write in order to avoid data integrity errors | [
"This",
"method",
"decides",
"whether",
"to",
"convert",
"an",
"append",
"to",
"a",
"full",
"write",
"in",
"order",
"to",
"avoid",
"data",
"integrity",
"errors"
] | python | train |
mgoral/subconvert | src/subconvert/gui/tools/Synchronizer.py | https://github.com/mgoral/subconvert/blob/59701e5e69ef1ca26ce7d1d766c936664aa2cb32/src/subconvert/gui/tools/Synchronizer.py#L317-L325 | def _findRow(subNo, model):
"""Finds a row in a given model which has a column with a given
number."""
items = model.findItems(str(subNo))
if len(items) == 0:
return None
if len(items) > 1:
raise IndexError("Too many items with sub number %s" % subNo)
return items[0].row() | [
"def",
"_findRow",
"(",
"subNo",
",",
"model",
")",
":",
"items",
"=",
"model",
".",
"findItems",
"(",
"str",
"(",
"subNo",
")",
")",
"if",
"len",
"(",
"items",
")",
"==",
"0",
":",
"return",
"None",
"if",
"len",
"(",
"items",
")",
">",
"1",
":... | Finds a row in a given model which has a column with a given
number. | [
"Finds",
"a",
"row",
"in",
"a",
"given",
"model",
"which",
"has",
"a",
"column",
"with",
"a",
"given",
"number",
"."
] | python | train |
BetterWorks/django-anonymizer | anonymizer/replacers.py | https://github.com/BetterWorks/django-anonymizer/blob/2d25bb6e8b5e4230c58031c4b6d10cc536669b3e/anonymizer/replacers.py#L187-L191 | def unique_lorem(anon, obj, field, val):
"""
Generates a unique paragraph of lorem ipsum text
"""
return anon.faker.unique_lorem(field=field) | [
"def",
"unique_lorem",
"(",
"anon",
",",
"obj",
",",
"field",
",",
"val",
")",
":",
"return",
"anon",
".",
"faker",
".",
"unique_lorem",
"(",
"field",
"=",
"field",
")"
] | Generates a unique paragraph of lorem ipsum text | [
"Generates",
"a",
"unique",
"paragraph",
"of",
"lorem",
"ipsum",
"text"
] | python | train |
SoCo/SoCo | soco/core.py | https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1892-L1919 | def move_in_sonos_playlist(self, sonos_playlist, track, new_pos,
update_id=0):
"""Move a track to a new position within a Sonos Playlist.
This is a convenience method for :py:meth:`reorder_sonos_playlist`.
Example::
device.move_in_sonos_playlist(sonos... | [
"def",
"move_in_sonos_playlist",
"(",
"self",
",",
"sonos_playlist",
",",
"track",
",",
"new_pos",
",",
"update_id",
"=",
"0",
")",
":",
"return",
"self",
".",
"reorder_sonos_playlist",
"(",
"sonos_playlist",
",",
"int",
"(",
"track",
")",
",",
"int",
"(",
... | Move a track to a new position within a Sonos Playlist.
This is a convenience method for :py:meth:`reorder_sonos_playlist`.
Example::
device.move_in_sonos_playlist(sonos_playlist, track=0, new_pos=1)
Args:
sonos_playlist
(:py:class:`~.soco.data_structur... | [
"Move",
"a",
"track",
"to",
"a",
"new",
"position",
"within",
"a",
"Sonos",
"Playlist",
".",
"This",
"is",
"a",
"convenience",
"method",
"for",
":",
"py",
":",
"meth",
":",
"reorder_sonos_playlist",
"."
] | python | train |
materialsproject/pymatgen | pymatgen/core/surface.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/core/surface.py#L1834-L1880 | def center_slab(slab):
"""
The goal here is to ensure the center of the slab region
is centered close to c=0.5. This makes it easier to
find the surface sites and apply operations like doping.
There are three cases where the slab in not centered:
1. The slab region is completely between... | [
"def",
"center_slab",
"(",
"slab",
")",
":",
"# get a reasonable r cutoff to sample neighbors",
"bdists",
"=",
"sorted",
"(",
"[",
"nn",
"[",
"1",
"]",
"for",
"nn",
"in",
"slab",
".",
"get_neighbors",
"(",
"slab",
"[",
"0",
"]",
",",
"10",
")",
"if",
"nn... | The goal here is to ensure the center of the slab region
is centered close to c=0.5. This makes it easier to
find the surface sites and apply operations like doping.
There are three cases where the slab in not centered:
1. The slab region is completely between two vacuums in the
box but... | [
"The",
"goal",
"here",
"is",
"to",
"ensure",
"the",
"center",
"of",
"the",
"slab",
"region",
"is",
"centered",
"close",
"to",
"c",
"=",
"0",
".",
"5",
".",
"This",
"makes",
"it",
"easier",
"to",
"find",
"the",
"surface",
"sites",
"and",
"apply",
"ope... | python | train |
ergo/ziggurat_foundations | ziggurat_foundations/migrations/env.py | https://github.com/ergo/ziggurat_foundations/blob/9eeec894d08e8d7defa60ddc04b63f69cd4cbeba/ziggurat_foundations/migrations/env.py#L74-L95 | def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = create_engine(get_url())
connection = engine.connect()
context.configure(
connection=connection,
target_m... | [
"def",
"run_migrations_online",
"(",
")",
":",
"engine",
"=",
"create_engine",
"(",
"get_url",
"(",
")",
")",
"connection",
"=",
"engine",
".",
"connect",
"(",
")",
"context",
".",
"configure",
"(",
"connection",
"=",
"connection",
",",
"target_metadata",
"=... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. | [
"Run",
"migrations",
"in",
"online",
"mode",
"."
] | python | train |
apache/airflow | airflow/hooks/webhdfs_hook.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/webhdfs_hook.py#L56-L79 | def get_conn(self):
"""
Establishes a connection depending on the security mode set via config or environment variable.
:return: a hdfscli InsecureClient or KerberosClient object.
:rtype: hdfs.InsecureClient or hdfs.ext.kerberos.KerberosClient
"""
connections = self.get_... | [
"def",
"get_conn",
"(",
"self",
")",
":",
"connections",
"=",
"self",
".",
"get_connections",
"(",
"self",
".",
"webhdfs_conn_id",
")",
"for",
"connection",
"in",
"connections",
":",
"try",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Trying namenode %s'",
... | Establishes a connection depending on the security mode set via config or environment variable.
:return: a hdfscli InsecureClient or KerberosClient object.
:rtype: hdfs.InsecureClient or hdfs.ext.kerberos.KerberosClient | [
"Establishes",
"a",
"connection",
"depending",
"on",
"the",
"security",
"mode",
"set",
"via",
"config",
"or",
"environment",
"variable",
"."
] | python | test |
MKLab-ITI/reveal-graph-embedding | reveal_graph_embedding/datautil/score_rw_util.py | https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/datautil/score_rw_util.py#L76-L90 | def write_average_score_row(fp, score_name, scores):
"""
Simple utility function that writes an average score row in a file designated by a file pointer.
Inputs: - fp: A file pointer.
- score_name: What it says on the tin.
- scores: An array of average score values corresponding ... | [
"def",
"write_average_score_row",
"(",
"fp",
",",
"score_name",
",",
"scores",
")",
":",
"row",
"=",
"\"--\"",
"+",
"score_name",
"+",
"\"--\"",
"fp",
".",
"write",
"(",
"row",
")",
"for",
"vector",
"in",
"scores",
":",
"row",
"=",
"list",
"(",
"vector... | Simple utility function that writes an average score row in a file designated by a file pointer.
Inputs: - fp: A file pointer.
- score_name: What it says on the tin.
- scores: An array of average score values corresponding to each of the training set percentages. | [
"Simple",
"utility",
"function",
"that",
"writes",
"an",
"average",
"score",
"row",
"in",
"a",
"file",
"designated",
"by",
"a",
"file",
"pointer",
"."
] | python | train |
saltstack/salt | salt/state.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3809-L3844 | def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL Ord... | [
"def",
"_handle_iorder",
"(",
"self",
",",
"state",
")",
":",
"if",
"self",
".",
"opts",
"[",
"'state_auto_order'",
"]",
":",
"for",
"name",
"in",
"state",
":",
"for",
"s_dec",
"in",
"state",
"[",
"name",
"]",
":",
"if",
"not",
"isinstance",
"(",
"s_... | Take a state and apply the iorder system | [
"Take",
"a",
"state",
"and",
"apply",
"the",
"iorder",
"system"
] | python | train |
angr/angr | angr/analyses/decompiler/clinic.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/decompiler/clinic.py#L169-L179 | def _simplify_block(self, ail_block, stack_pointer_tracker=None):
"""
Simplify a single AIL block.
:param ailment.Block ail_block: The AIL block to simplify.
:param stack_pointer_tracker: The RegisterDeltaTracker analysis instance.
:return: A simplified ... | [
"def",
"_simplify_block",
"(",
"self",
",",
"ail_block",
",",
"stack_pointer_tracker",
"=",
"None",
")",
":",
"simp",
"=",
"self",
".",
"project",
".",
"analyses",
".",
"AILBlockSimplifier",
"(",
"ail_block",
",",
"stack_pointer_tracker",
"=",
"stack_pointer_track... | Simplify a single AIL block.
:param ailment.Block ail_block: The AIL block to simplify.
:param stack_pointer_tracker: The RegisterDeltaTracker analysis instance.
:return: A simplified AIL block. | [
"Simplify",
"a",
"single",
"AIL",
"block",
"."
] | python | train |
datastax/python-driver | cassandra/cluster.py | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L4187-L4206 | def get_query_trace(self, max_wait=None, query_cl=ConsistencyLevel.LOCAL_ONE):
"""
Fetches and returns the query trace of the last response, or `None` if tracing was
not enabled.
Note that this may raise an exception if there are problems retrieving the trace
details from Cassan... | [
"def",
"get_query_trace",
"(",
"self",
",",
"max_wait",
"=",
"None",
",",
"query_cl",
"=",
"ConsistencyLevel",
".",
"LOCAL_ONE",
")",
":",
"if",
"self",
".",
"_final_result",
"is",
"_NOT_SET",
"and",
"self",
".",
"_final_exception",
"is",
"None",
":",
"raise... | Fetches and returns the query trace of the last response, or `None` if tracing was
not enabled.
Note that this may raise an exception if there are problems retrieving the trace
details from Cassandra. If the trace is not available after `max_wait`,
:exc:`cassandra.query.TraceUnavailable... | [
"Fetches",
"and",
"returns",
"the",
"query",
"trace",
"of",
"the",
"last",
"response",
"or",
"None",
"if",
"tracing",
"was",
"not",
"enabled",
"."
] | python | train |
intelligenia/modeltranslation | modeltranslation/transcache.py | https://github.com/intelligenia/modeltranslation/blob/64d6adeb537747321d5020efedf5d7e0d135862d/modeltranslation/transcache.py#L34-L37 | def _create_key(lang, instance):
"""Crea la clave única de la caché"""
model_name = instance.__class__.__name__
return "{0}__{1}_{2}".format(lang,model_name,instance.id) | [
"def",
"_create_key",
"(",
"lang",
",",
"instance",
")",
":",
"model_name",
"=",
"instance",
".",
"__class__",
".",
"__name__",
"return",
"\"{0}__{1}_{2}\"",
".",
"format",
"(",
"lang",
",",
"model_name",
",",
"instance",
".",
"id",
")"
] | Crea la clave única de la caché | [
"Crea",
"la",
"clave",
"única",
"de",
"la",
"caché"
] | python | train |
mfcloud/python-zvm-sdk | smtLayer/generalUtils.py | https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/smtLayer/generalUtils.py#L25-L78 | def cvtToBlocks(rh, diskSize):
"""
Convert a disk storage value to a number of blocks.
Input:
Request Handle
Size of disk in bytes
Output:
Results structure:
overallRC - Overall return code for the function:
0 - Everything went ok
... | [
"def",
"cvtToBlocks",
"(",
"rh",
",",
"diskSize",
")",
":",
"rh",
".",
"printSysLog",
"(",
"\"Enter generalUtils.cvtToBlocks\"",
")",
"blocks",
"=",
"0",
"results",
"=",
"{",
"'overallRC'",
":",
"0",
",",
"'rc'",
":",
"0",
",",
"'rs'",
":",
"0",
",",
"... | Convert a disk storage value to a number of blocks.
Input:
Request Handle
Size of disk in bytes
Output:
Results structure:
overallRC - Overall return code for the function:
0 - Everything went ok
4 - Input validation error
... | [
"Convert",
"a",
"disk",
"storage",
"value",
"to",
"a",
"number",
"of",
"blocks",
"."
] | python | train |
edeposit/edeposit.amqp.ftp | src/edeposit/amqp/ftp/request_parser.py | https://github.com/edeposit/edeposit.amqp.ftp/blob/fcdcbffb6e5d194e1bb4f85f0b8eaa9dbb08aa71/src/edeposit/amqp/ftp/request_parser.py#L99-L111 | def _remove_files(files):
"""
Remove all given files.
Args:
files (list): List of filenames, which will be removed.
"""
logger.debug("Request for file removal (_remove_files()).")
for fn in files:
if os.path.exists(fn):
logger.debug("Removing '%s'." % fn)
... | [
"def",
"_remove_files",
"(",
"files",
")",
":",
"logger",
".",
"debug",
"(",
"\"Request for file removal (_remove_files()).\"",
")",
"for",
"fn",
"in",
"files",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"logger",
".",
"debug",
"(",
... | Remove all given files.
Args:
files (list): List of filenames, which will be removed. | [
"Remove",
"all",
"given",
"files",
"."
] | python | train |
JNRowe/upoints | upoints/nmea.py | https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/nmea.py#L70-L85 | def parse_latitude(latitude, hemisphere):
"""Parse a NMEA-formatted latitude pair.
Args:
latitude (str): Latitude in DDMM.MMMM
hemisphere (str): North or South
Returns:
float: Decimal representation of latitude
"""
latitude = int(latitude[:2]) + float(latitude[2:]) / 60
... | [
"def",
"parse_latitude",
"(",
"latitude",
",",
"hemisphere",
")",
":",
"latitude",
"=",
"int",
"(",
"latitude",
"[",
":",
"2",
"]",
")",
"+",
"float",
"(",
"latitude",
"[",
"2",
":",
"]",
")",
"/",
"60",
"if",
"hemisphere",
"==",
"'S'",
":",
"latit... | Parse a NMEA-formatted latitude pair.
Args:
latitude (str): Latitude in DDMM.MMMM
hemisphere (str): North or South
Returns:
float: Decimal representation of latitude | [
"Parse",
"a",
"NMEA",
"-",
"formatted",
"latitude",
"pair",
"."
] | python | train |
pandas-dev/pandas | pandas/plotting/_misc.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_misc.py#L452-L563 | def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
use_columns=False, xticks=None, colormap=None,
axvlines=True, axvlines_kwds=None, sort_labels=False,
**kwds):
"""Parallel coordinates plotting.
Parameters
... | [
"def",
"parallel_coordinates",
"(",
"frame",
",",
"class_column",
",",
"cols",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"color",
"=",
"None",
",",
"use_columns",
"=",
"False",
",",
"xticks",
"=",
"None",
",",
"colormap",
"=",
"None",
",",
"axvlines",
... | Parallel coordinates plotting.
Parameters
----------
frame : DataFrame
class_column : str
Column name containing class names
cols : list, optional
A list of column names to use
ax : matplotlib.axis, optional
matplotlib axis object
color : list or tuple, optional
... | [
"Parallel",
"coordinates",
"plotting",
"."
] | python | train |
pydata/numexpr | numexpr/necompiler.py | https://github.com/pydata/numexpr/blob/364bac13d84524e0e01db892301b2959d822dcff/numexpr/necompiler.py#L273-L306 | def stringToExpression(s, types, context):
"""Given a string, convert it to a tree of ExpressionNode's.
"""
old_ctx = expressions._context.get_current_context()
try:
expressions._context.set_new_context(context)
# first compile to a code object to determine the names
if context.g... | [
"def",
"stringToExpression",
"(",
"s",
",",
"types",
",",
"context",
")",
":",
"old_ctx",
"=",
"expressions",
".",
"_context",
".",
"get_current_context",
"(",
")",
"try",
":",
"expressions",
".",
"_context",
".",
"set_new_context",
"(",
"context",
")",
"# f... | Given a string, convert it to a tree of ExpressionNode's. | [
"Given",
"a",
"string",
"convert",
"it",
"to",
"a",
"tree",
"of",
"ExpressionNode",
"s",
"."
] | python | train |
rcsb/mmtf-python | mmtf/codecs/decoders/decoders.py | https://github.com/rcsb/mmtf-python/blob/899bb877ca1b32a9396803d38c5bf38a2520754e/mmtf/codecs/decoders/decoders.py#L1-L14 | def run_length_decode(in_array):
"""A function to run length decode an int array.
:param in_array: the input array of integers
:return the decoded array"""
switch=False
out_array=[]
for item in in_array:
if switch==False:
this_item = item
switch=True
else:... | [
"def",
"run_length_decode",
"(",
"in_array",
")",
":",
"switch",
"=",
"False",
"out_array",
"=",
"[",
"]",
"for",
"item",
"in",
"in_array",
":",
"if",
"switch",
"==",
"False",
":",
"this_item",
"=",
"item",
"switch",
"=",
"True",
"else",
":",
"switch",
... | A function to run length decode an int array.
:param in_array: the input array of integers
:return the decoded array | [
"A",
"function",
"to",
"run",
"length",
"decode",
"an",
"int",
"array",
".",
":",
"param",
"in_array",
":",
"the",
"input",
"array",
"of",
"integers",
":",
"return",
"the",
"decoded",
"array"
] | python | train |
greenbone/ospd | ospd/misc.py | https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L107-L113 | def set_progress(self, scan_id, progress):
""" Sets scan_id scan's progress. """
if progress > 0 and progress <= 100:
self.scans_table[scan_id]['progress'] = progress
if progress == 100:
self.scans_table[scan_id]['end_time'] = int(time.time()) | [
"def",
"set_progress",
"(",
"self",
",",
"scan_id",
",",
"progress",
")",
":",
"if",
"progress",
">",
"0",
"and",
"progress",
"<=",
"100",
":",
"self",
".",
"scans_table",
"[",
"scan_id",
"]",
"[",
"'progress'",
"]",
"=",
"progress",
"if",
"progress",
... | Sets scan_id scan's progress. | [
"Sets",
"scan_id",
"scan",
"s",
"progress",
"."
] | python | train |
bwohlberg/sporco | sporco/admm/admm.py | https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/admm.py#L578-L600 | def display_start(self):
"""Set up status display if option selected. NB: this method
assumes that the first entry is the iteration count and the last
is the rho value.
"""
if self.opt['Verbose']:
# If AutoRho option enabled rho is included in iteration status
... | [
"def",
"display_start",
"(",
"self",
")",
":",
"if",
"self",
".",
"opt",
"[",
"'Verbose'",
"]",
":",
"# If AutoRho option enabled rho is included in iteration status",
"if",
"self",
".",
"opt",
"[",
"'AutoRho'",
",",
"'Enabled'",
"]",
":",
"hdrtxt",
"=",
"type",... | Set up status display if option selected. NB: this method
assumes that the first entry is the iteration count and the last
is the rho value. | [
"Set",
"up",
"status",
"display",
"if",
"option",
"selected",
".",
"NB",
":",
"this",
"method",
"assumes",
"that",
"the",
"first",
"entry",
"is",
"the",
"iteration",
"count",
"and",
"the",
"last",
"is",
"the",
"rho",
"value",
"."
] | python | train |
twisted/mantissa | xmantissa/people.py | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/people.py#L2597-L2627 | def makeThumbnail(cls, inputFile, person, format, smaller):
"""
Make a thumbnail of a mugshot image and store it on disk.
@param inputFile: The image to thumbnail.
@type inputFile: C{file}
@param person: The person this mugshot thumbnail is associated with.
@type person... | [
"def",
"makeThumbnail",
"(",
"cls",
",",
"inputFile",
",",
"person",
",",
"format",
",",
"smaller",
")",
":",
"dirsegs",
"=",
"[",
"'mugshots'",
",",
"str",
"(",
"person",
".",
"storeID",
")",
"]",
"if",
"smaller",
":",
"dirsegs",
".",
"insert",
"(",
... | Make a thumbnail of a mugshot image and store it on disk.
@param inputFile: The image to thumbnail.
@type inputFile: C{file}
@param person: The person this mugshot thumbnail is associated with.
@type person: L{Person}
@param format: The format of the data in C{inputFile}.
... | [
"Make",
"a",
"thumbnail",
"of",
"a",
"mugshot",
"image",
"and",
"store",
"it",
"on",
"disk",
"."
] | python | train |
SheffieldML/GPy | GPy/kern/src/todo/poly.py | https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/kern/src/todo/poly.py#L102-L109 | def gradients_X(self, dL_dK, X, X2, target):
"""Derivative of the covariance matrix with respect to X"""
self._K_computations(X, X2)
arg = self._K_poly_arg
if X2 is None:
target += 2*self.weight_variance*self.degree*self.variance*(((X[None,:, :])) *(arg**(self.degree-1))[:, :... | [
"def",
"gradients_X",
"(",
"self",
",",
"dL_dK",
",",
"X",
",",
"X2",
",",
"target",
")",
":",
"self",
".",
"_K_computations",
"(",
"X",
",",
"X2",
")",
"arg",
"=",
"self",
".",
"_K_poly_arg",
"if",
"X2",
"is",
"None",
":",
"target",
"+=",
"2",
"... | Derivative of the covariance matrix with respect to X | [
"Derivative",
"of",
"the",
"covariance",
"matrix",
"with",
"respect",
"to",
"X"
] | python | train |
openearth/mmi-python | mmi/runner.py | https://github.com/openearth/mmi-python/blob/a2f4ac96b1e7f2fa903f668b3e05c4e86ad42e8d/mmi/runner.py#L329-L381 | def create_sockets(self):
"""create zmq sockets"""
ports = self.ports
context = zmq.Context()
poller = zmq.Poller()
# Socket to handle init data
rep = context.socket(zmq.REP)
# this was inconsequent: here REQ is for the client, we reply with REP.
# PULL... | [
"def",
"create_sockets",
"(",
"self",
")",
":",
"ports",
"=",
"self",
".",
"ports",
"context",
"=",
"zmq",
".",
"Context",
"(",
")",
"poller",
"=",
"zmq",
".",
"Poller",
"(",
")",
"# Socket to handle init data",
"rep",
"=",
"context",
".",
"socket",
"(",... | create zmq sockets | [
"create",
"zmq",
"sockets"
] | python | train |
f3at/feat | src/feat/models/model.py | https://github.com/f3at/feat/blob/15da93fc9d6ec8154f52a9172824e25821195ef8/src/feat/models/model.py#L1227-L1238 | def initiate(self):
"""If the returned deferred is fired with None,
the item will be disabled as if did not exists."""
if not self.model.officer.is_item_allowed(self.model, self._name):
return defer.succeed(None)
if not callable(self._enabled):
d = defer.succeed(... | [
"def",
"initiate",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"model",
".",
"officer",
".",
"is_item_allowed",
"(",
"self",
".",
"model",
",",
"self",
".",
"_name",
")",
":",
"return",
"defer",
".",
"succeed",
"(",
"None",
")",
"if",
"not",
"... | If the returned deferred is fired with None,
the item will be disabled as if did not exists. | [
"If",
"the",
"returned",
"deferred",
"is",
"fired",
"with",
"None",
"the",
"item",
"will",
"be",
"disabled",
"as",
"if",
"did",
"not",
"exists",
"."
] | python | train |
oanda/v20-python | src/v20/account.py | https://github.com/oanda/v20-python/blob/f28192f4a31bce038cf6dfa302f5878bec192fe5/src/v20/account.py#L1684-L1828 | def configure(
self,
accountID,
**kwargs
):
"""
Set the client-configurable portions of an Account.
Args:
accountID:
Account Identifier
alias:
Client-defined alias (name) for the Account
marginRate:
... | [
"def",
"configure",
"(",
"self",
",",
"accountID",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"Request",
"(",
"'PATCH'",
",",
"'/v3/accounts/{accountID}/configuration'",
")",
"request",
".",
"set_path_param",
"(",
"'accountID'",
",",
"accountID",
")",
... | Set the client-configurable portions of an Account.
Args:
accountID:
Account Identifier
alias:
Client-defined alias (name) for the Account
marginRate:
The string representation of a decimal number.
Returns:
... | [
"Set",
"the",
"client",
"-",
"configurable",
"portions",
"of",
"an",
"Account",
"."
] | python | train |
log2timeline/plaso | plaso/analysis/tagging.py | https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/tagging.py#L35-L56 | def _AttemptAutoDetectTagFile(self, analysis_mediator):
"""Detects which tag file is most appropriate.
Args:
analysis_mediator (AnalysisMediator): analysis mediator.
Returns:
bool: True if a tag file is autodetected.
"""
self._autodetect_tag_file_attempt = True
if not analysis_medi... | [
"def",
"_AttemptAutoDetectTagFile",
"(",
"self",
",",
"analysis_mediator",
")",
":",
"self",
".",
"_autodetect_tag_file_attempt",
"=",
"True",
"if",
"not",
"analysis_mediator",
".",
"data_location",
":",
"return",
"False",
"operating_system",
"=",
"analysis_mediator",
... | Detects which tag file is most appropriate.
Args:
analysis_mediator (AnalysisMediator): analysis mediator.
Returns:
bool: True if a tag file is autodetected. | [
"Detects",
"which",
"tag",
"file",
"is",
"most",
"appropriate",
"."
] | python | train |
asweigart/pytweening | pytweening/__init__.py | https://github.com/asweigart/pytweening/blob/20d74368e53dc7d0f77c810b624b2c90994f099d/pytweening/__init__.py#L498-L508 | def easeInBack(n, s=1.70158):
"""A tween function that backs up first at the start and then goes to the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnL... | [
"def",
"easeInBack",
"(",
"n",
",",
"s",
"=",
"1.70158",
")",
":",
"_checkRange",
"(",
"n",
")",
"return",
"n",
"*",
"n",
"*",
"(",
"(",
"s",
"+",
"1",
")",
"*",
"n",
"-",
"s",
")"
] | A tween function that backs up first at the start and then goes to the destination.
Args:
n (float): The time progress, starting at 0.0 and ending at 1.0.
Returns:
(float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine(). | [
"A",
"tween",
"function",
"that",
"backs",
"up",
"first",
"at",
"the",
"start",
"and",
"then",
"goes",
"to",
"the",
"destination",
"."
] | python | train |
bwengals/ccsnmultivar | ccsnmultivar/designmatrix.py | https://github.com/bwengals/ccsnmultivar/blob/dbadf52e728e0ce922cbc147864e693c2c2d305c/ccsnmultivar/designmatrix.py#L273-L339 | def _parse_formula(formula):
"""
Parse formula into a dictionary
formula_dict[variable_name] = [encoding, dropped_name]
Parse interactions into a list
inter_list = [[A,B], [A,C], [A,B,C]]
formula = "A + beta + A*beta | Dev(A,drop=1), Poly(beta,degree=3)"
"""
#TODO: DEAL WITH BSPLINE HAS... | [
"def",
"_parse_formula",
"(",
"formula",
")",
":",
"#TODO: DEAL WITH BSPLINE HAS MULTIPLE ARGUEMENTS (NOT JUST ONE)",
"# break formula apart from encoding instructions",
"formula",
",",
"instr",
"=",
"formula",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"split",
"("... | Parse formula into a dictionary
formula_dict[variable_name] = [encoding, dropped_name]
Parse interactions into a list
inter_list = [[A,B], [A,C], [A,B,C]]
formula = "A + beta + A*beta | Dev(A,drop=1), Poly(beta,degree=3)" | [
"Parse",
"formula",
"into",
"a",
"dictionary",
"formula_dict",
"[",
"variable_name",
"]",
"=",
"[",
"encoding",
"dropped_name",
"]",
"Parse",
"interactions",
"into",
"a",
"list",
"inter_list",
"=",
"[[",
"A",
"B",
"]",
"[",
"A",
"C",
"]",
"[",
"A",
"B",
... | python | train |
cimatosa/progression | progression/terminal.py | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/terminal.py#L95-L131 | def terminal_reserve(progress_obj, terminal_obj=None, identifier=None):
""" Registers the terminal (stdout) for printing.
Useful to prevent multiple processes from writing progress bars
to stdout.
One process (server) prints to stdout and a couple of subprocesses
do not print to the same stdout, b... | [
"def",
"terminal_reserve",
"(",
"progress_obj",
",",
"terminal_obj",
"=",
"None",
",",
"identifier",
"=",
"None",
")",
":",
"if",
"terminal_obj",
"is",
"None",
":",
"terminal_obj",
"=",
"sys",
".",
"stdout",
"if",
"identifier",
"is",
"None",
":",
"identifier... | Registers the terminal (stdout) for printing.
Useful to prevent multiple processes from writing progress bars
to stdout.
One process (server) prints to stdout and a couple of subprocesses
do not print to the same stdout, because the server has reserved it.
Of course, the clients have to be nice an... | [
"Registers",
"the",
"terminal",
"(",
"stdout",
")",
"for",
"printing",
"."
] | python | train |
nickoala/telepot | telepot/__init__.py | https://github.com/nickoala/telepot/blob/3792fde251d0f1d5a6ca16c8ad1a71f89360c41d/telepot/__init__.py#L890-L901 | def editMessageCaption(self, msg_identifier,
caption=None,
parse_mode=None,
reply_markup=None):
"""
See: https://core.telegram.org/bots/api#editmessagecaption
:param msg_identifier: Same as ``msg_identifier`` in :m... | [
"def",
"editMessageCaption",
"(",
"self",
",",
"msg_identifier",
",",
"caption",
"=",
"None",
",",
"parse_mode",
"=",
"None",
",",
"reply_markup",
"=",
"None",
")",
":",
"p",
"=",
"_strip",
"(",
"locals",
"(",
")",
",",
"more",
"=",
"[",
"'msg_identifier... | See: https://core.telegram.org/bots/api#editmessagecaption
:param msg_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessageText` | [
"See",
":",
"https",
":",
"//",
"core",
".",
"telegram",
".",
"org",
"/",
"bots",
"/",
"api#editmessagecaption"
] | python | train |
DLR-RM/RAFCON | source/rafcon/gui/controllers/state_machine_tree.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/state_machine_tree.py#L300-L336 | def update(self, changed_state_model=None, with_expand=False):
"""Checks if all states are in tree and if tree has states which were deleted
:param changed_state_model: Model that row has to be updated
:param with_expand: The expand flag for the tree
"""
if not self.view_is_regi... | [
"def",
"update",
"(",
"self",
",",
"changed_state_model",
"=",
"None",
",",
"with_expand",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"view_is_registered",
":",
"return",
"# define initial state-model for update",
"if",
"changed_state_model",
"is",
"None",
... | Checks if all states are in tree and if tree has states which were deleted
:param changed_state_model: Model that row has to be updated
:param with_expand: The expand flag for the tree | [
"Checks",
"if",
"all",
"states",
"are",
"in",
"tree",
"and",
"if",
"tree",
"has",
"states",
"which",
"were",
"deleted"
] | python | train |
fprimex/zdesk | zdesk/zdesk_api.py | https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L599-L603 | def channels_voice_agent_ticket_display_create(self, agent_id, ticket_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/voice-api/partner_edition#open-ticket-in-agents-browser"
api_path = "/api/v2/channels/voice/agents/{agent_id}/tickets/{ticket_id}/display.json"
api_path = api_p... | [
"def",
"channels_voice_agent_ticket_display_create",
"(",
"self",
",",
"agent_id",
",",
"ticket_id",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/channels/voice/agents/{agent_id}/tickets/{ticket_id}/display.json\"",
"api_path",
"=",
"api_path"... | https://developer.zendesk.com/rest_api/docs/voice-api/partner_edition#open-ticket-in-agents-browser | [
"https",
":",
"//",
"developer",
".",
"zendesk",
".",
"com",
"/",
"rest_api",
"/",
"docs",
"/",
"voice",
"-",
"api",
"/",
"partner_edition#open",
"-",
"ticket",
"-",
"in",
"-",
"agents",
"-",
"browser"
] | python | train |
box/rotunicode | rotunicode/rotunicode.py | https://github.com/box/rotunicode/blob/6149b6bb5bb50d322db248acfdb910dc3cb1bcc2/rotunicode/rotunicode.py#L50-L73 | def encode(cls, string, errors='strict'):
"""Return the encoded version of a string.
:param string:
The input string to encode.
:type string:
`basestring`
:param errors:
The error handling scheme. Only 'strict' is supported.
:type errors:
... | [
"def",
"encode",
"(",
"cls",
",",
"string",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"errors",
"!=",
"'strict'",
":",
"raise",
"UnicodeError",
"(",
"'Unsupported error handling {0}'",
".",
"format",
"(",
"errors",
")",
")",
"unicode_string",
"=",
"cls... | Return the encoded version of a string.
:param string:
The input string to encode.
:type string:
`basestring`
:param errors:
The error handling scheme. Only 'strict' is supported.
:type errors:
`basestring`
:return:
T... | [
"Return",
"the",
"encoded",
"version",
"of",
"a",
"string",
"."
] | python | train |
sibirrer/lenstronomy | lenstronomy/Plots/output_plots.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/Plots/output_plots.py#L639-L655 | def plot_main(self, with_caustics=False, image_names=False):
"""
print the main plots together in a joint frame
:return:
"""
f, axes = plt.subplots(2, 3, figsize=(16, 8))
self.data_plot(ax=axes[0, 0])
self.model_plot(ax=axes[0, 1], image_names=True)
self... | [
"def",
"plot_main",
"(",
"self",
",",
"with_caustics",
"=",
"False",
",",
"image_names",
"=",
"False",
")",
":",
"f",
",",
"axes",
"=",
"plt",
".",
"subplots",
"(",
"2",
",",
"3",
",",
"figsize",
"=",
"(",
"16",
",",
"8",
")",
")",
"self",
".",
... | print the main plots together in a joint frame
:return: | [
"print",
"the",
"main",
"plots",
"together",
"in",
"a",
"joint",
"frame"
] | python | train |
wonambi-python/wonambi | wonambi/ioeeg/openephys.py | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/openephys.py#L194-L219 | def _read_date(settings_file):
"""Get the data from the settings.xml file
Parameters
----------
settings_file : Path
path to settings.xml inside open-ephys folder
Returns
-------
datetime
start time of the recordings
Notes
-----
The start time is present in the... | [
"def",
"_read_date",
"(",
"settings_file",
")",
":",
"root",
"=",
"ElementTree",
".",
"parse",
"(",
"settings_file",
")",
".",
"getroot",
"(",
")",
"for",
"e0",
"in",
"root",
":",
"if",
"e0",
".",
"tag",
"==",
"'INFO'",
":",
"for",
"e1",
"in",
"e0",
... | Get the data from the settings.xml file
Parameters
----------
settings_file : Path
path to settings.xml inside open-ephys folder
Returns
-------
datetime
start time of the recordings
Notes
-----
The start time is present in the header of each file. This might be us... | [
"Get",
"the",
"data",
"from",
"the",
"settings",
".",
"xml",
"file"
] | python | train |
devricks/soft_drf | soft_drf/auth/utilities.py | https://github.com/devricks/soft_drf/blob/1869b13f9341bfcebd931059e93de2bc38570da3/soft_drf/auth/utilities.py#L13-L27 | def jwt_get_secret_key(payload=None):
"""
For enchanced security you may use secret key on user itself.
This way you have an option to logout only this user if:
- token is compromised
- password is changed
- etc.
"""
User = get_user_model() # noqa
if api_settings.JWT_GET... | [
"def",
"jwt_get_secret_key",
"(",
"payload",
"=",
"None",
")",
":",
"User",
"=",
"get_user_model",
"(",
")",
"# noqa",
"if",
"api_settings",
".",
"JWT_GET_USER_SECRET_KEY",
":",
"user",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"payload",
".... | For enchanced security you may use secret key on user itself.
This way you have an option to logout only this user if:
- token is compromised
- password is changed
- etc. | [
"For",
"enchanced",
"security",
"you",
"may",
"use",
"secret",
"key",
"on",
"user",
"itself",
".",
"This",
"way",
"you",
"have",
"an",
"option",
"to",
"logout",
"only",
"this",
"user",
"if",
":",
"-",
"token",
"is",
"compromised",
"-",
"password",
"is",
... | python | train |
zhanglab/psamm | psamm/datasource/native.py | https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/datasource/native.py#L547-L614 | def create_metabolic_model(self):
"""Create a :class:`psamm.metabolicmodel.MetabolicModel`."""
def _translate_compartments(reaction, compartment):
"""Translate compound with missing compartments.
These compounds will have the specified compartment in the output.
"""... | [
"def",
"create_metabolic_model",
"(",
"self",
")",
":",
"def",
"_translate_compartments",
"(",
"reaction",
",",
"compartment",
")",
":",
"\"\"\"Translate compound with missing compartments.\n\n These compounds will have the specified compartment in the output.\n \"\... | Create a :class:`psamm.metabolicmodel.MetabolicModel`. | [
"Create",
"a",
":",
"class",
":",
"psamm",
".",
"metabolicmodel",
".",
"MetabolicModel",
"."
] | python | train |
pytorch/text | torchtext/datasets/imdb.py | https://github.com/pytorch/text/blob/26bfce6869dc704f1d86792f9a681d453d7e7bb8/torchtext/datasets/imdb.py#L40-L55 | def splits(cls, text_field, label_field, root='.data',
train='train', test='test', **kwargs):
"""Create dataset objects for splits of the IMDB dataset.
Arguments:
text_field: The field that will be used for the sentence.
label_field: The field that will be used fo... | [
"def",
"splits",
"(",
"cls",
",",
"text_field",
",",
"label_field",
",",
"root",
"=",
"'.data'",
",",
"train",
"=",
"'train'",
",",
"test",
"=",
"'test'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"IMDB",
",",
"cls",
")",
".",
"spl... | Create dataset objects for splits of the IMDB dataset.
Arguments:
text_field: The field that will be used for the sentence.
label_field: The field that will be used for label data.
root: Root dataset storage directory. Default is '.data'.
train: The directory tha... | [
"Create",
"dataset",
"objects",
"for",
"splits",
"of",
"the",
"IMDB",
"dataset",
"."
] | python | train |
spyder-ide/spyder | spyder/preferences/layoutdialog.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/layoutdialog.py#L156-L161 | def check_text(self, text):
"""Disable empty layout name possibility"""
if to_text_string(text) == u'':
self.button_ok.setEnabled(False)
else:
self.button_ok.setEnabled(True) | [
"def",
"check_text",
"(",
"self",
",",
"text",
")",
":",
"if",
"to_text_string",
"(",
"text",
")",
"==",
"u''",
":",
"self",
".",
"button_ok",
".",
"setEnabled",
"(",
"False",
")",
"else",
":",
"self",
".",
"button_ok",
".",
"setEnabled",
"(",
"True",
... | Disable empty layout name possibility | [
"Disable",
"empty",
"layout",
"name",
"possibility"
] | python | train |
Chilipp/psyplot | psyplot/data.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L4328-L4352 | def next_available_name(self, fmt_str='arr{0}', counter=None):
"""Create a new array out of the given format string
Parameters
----------
format_str: str
The base string to use. ``'{0}'`` will be replaced by a counter
counter: iterable
An iterable where t... | [
"def",
"next_available_name",
"(",
"self",
",",
"fmt_str",
"=",
"'arr{0}'",
",",
"counter",
"=",
"None",
")",
":",
"names",
"=",
"self",
".",
"arr_names",
"counter",
"=",
"counter",
"or",
"iter",
"(",
"range",
"(",
"1000",
")",
")",
"try",
":",
"new_na... | Create a new array out of the given format string
Parameters
----------
format_str: str
The base string to use. ``'{0}'`` will be replaced by a counter
counter: iterable
An iterable where the numbers should be drawn from. If None,
``range(100)`` is us... | [
"Create",
"a",
"new",
"array",
"out",
"of",
"the",
"given",
"format",
"string"
] | python | train |
opennode/waldur-core | waldur_core/cost_tracking/handlers.py | https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/cost_tracking/handlers.py#L16-L35 | def scope_deletion(sender, instance, **kwargs):
""" Run different actions on price estimate scope deletion.
If scope is a customer - delete all customer estimates and their children.
If scope is a deleted resource - redefine consumption details, recalculate
... | [
"def",
"scope_deletion",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"is_resource",
"=",
"isinstance",
"(",
"instance",
",",
"structure_models",
".",
"ResourceMixin",
")",
"if",
"is_resource",
"and",
"getattr",
"(",
"instance",
",",
"'... | Run different actions on price estimate scope deletion.
If scope is a customer - delete all customer estimates and their children.
If scope is a deleted resource - redefine consumption details, recalculate
ancestors estimates and update estimate details.
... | [
"Run",
"different",
"actions",
"on",
"price",
"estimate",
"scope",
"deletion",
"."
] | python | train |
odrling/peony-twitter | examples/birthday.py | https://github.com/odrling/peony-twitter/blob/967f98e16e1889389540f2e6acbf7cc7a1a80203/examples/birthday.py#L23-L33 | async def set_tz(self):
"""
set the environment timezone to the timezone
set in your twitter settings
"""
settings = await self.api.account.settings.get()
tz = settings.time_zone.tzinfo_name
os.environ['TZ'] = tz
time.tzset() | [
"async",
"def",
"set_tz",
"(",
"self",
")",
":",
"settings",
"=",
"await",
"self",
".",
"api",
".",
"account",
".",
"settings",
".",
"get",
"(",
")",
"tz",
"=",
"settings",
".",
"time_zone",
".",
"tzinfo_name",
"os",
".",
"environ",
"[",
"'TZ'",
"]",... | set the environment timezone to the timezone
set in your twitter settings | [
"set",
"the",
"environment",
"timezone",
"to",
"the",
"timezone",
"set",
"in",
"your",
"twitter",
"settings"
] | python | valid |
bykof/billomapy | billomapy/billomapy.py | https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L3612-L3626 | def get_items_of_delivery_note_per_page(self, delivery_note_id, per_page=1000, page=1):
"""
Get items of delivery note per page
:param delivery_note_id: the delivery note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:re... | [
"def",
"get_items_of_delivery_note_per_page",
"(",
"self",
",",
"delivery_note_id",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"DELIVERY_NOTE_ITEMS",
",",
"per_page",
"=",
... | Get items of delivery note per page
:param delivery_note_id: the delivery note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list | [
"Get",
"items",
"of",
"delivery",
"note",
"per",
"page"
] | python | train |
ic-labs/django-icekit | icekit/templatetags/icekit_tags.py | https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/templatetags/icekit_tags.py#L250-L271 | def admin_link(obj):
"""
Returns a link to the admin URL of an object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_link }}
renders as::
<a href='/admin/foo/123'>Foo</a>
:param obj:... | [
"def",
"admin_link",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'get_admin_link'",
")",
":",
"return",
"mark_safe",
"(",
"obj",
".",
"get_admin_link",
"(",
")",
")",
"return",
"mark_safe",
"(",
"admin_link_fn",
"(",
"obj",
")",
")"
] | Returns a link to the admin URL of an object.
No permissions checking is involved, so use with caution to avoid exposing
the link to unauthorised users.
Example::
{{ foo_obj|admin_link }}
renders as::
<a href='/admin/foo/123'>Foo</a>
:param obj: A Django model instance.
:re... | [
"Returns",
"a",
"link",
"to",
"the",
"admin",
"URL",
"of",
"an",
"object",
"."
] | python | train |
walchko/pyrk | pyrk/pyrk.py | https://github.com/walchko/pyrk/blob/f75dce843e795343d37cfe20d780989f56f0c418/pyrk/pyrk.py#L44-L58 | def step(self, y, u, t, h):
"""
This is called by solve, but can be called by the user who wants to
run through an integration with a control force.
y - state at t
u - control inputs at t
t - time
h - step size
"""
k1 = h * self.func(t, y, u)
k2 = h * self.func(t + .5*h, y + .5*h*k1, u)
k3 = h * ... | [
"def",
"step",
"(",
"self",
",",
"y",
",",
"u",
",",
"t",
",",
"h",
")",
":",
"k1",
"=",
"h",
"*",
"self",
".",
"func",
"(",
"t",
",",
"y",
",",
"u",
")",
"k2",
"=",
"h",
"*",
"self",
".",
"func",
"(",
"t",
"+",
".5",
"*",
"h",
",",
... | This is called by solve, but can be called by the user who wants to
run through an integration with a control force.
y - state at t
u - control inputs at t
t - time
h - step size | [
"This",
"is",
"called",
"by",
"solve",
"but",
"can",
"be",
"called",
"by",
"the",
"user",
"who",
"wants",
"to",
"run",
"through",
"an",
"integration",
"with",
"a",
"control",
"force",
"."
] | python | train |
bapakode/OmMongo | ommongo/query.py | https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query.py#L381-L394 | def query_bypass(self, query, raw_output=True):
''' Bypass query meaning that field check and validation is skipped, then query object directly executed by pymongo.
:param raw_output: Skip OmMongo ORM layer (default: True)
'''
if not isinstance(query, dict):
rais... | [
"def",
"query_bypass",
"(",
"self",
",",
"query",
",",
"raw_output",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"query",
",",
"dict",
")",
":",
"raise",
"BadQueryException",
"(",
"'Query must be dict.'",
")",
"self",
".",
"__query",
"=",
"query... | Bypass query meaning that field check and validation is skipped, then query object directly executed by pymongo.
:param raw_output: Skip OmMongo ORM layer (default: True) | [
"Bypass",
"query",
"meaning",
"that",
"field",
"check",
"and",
"validation",
"is",
"skipped",
"then",
"query",
"object",
"directly",
"executed",
"by",
"pymongo",
".",
":",
"param",
"raw_output",
":",
"Skip",
"OmMongo",
"ORM",
"layer",
"(",
"default",
":",
"T... | python | train |
portfoliome/foil | foil/compose.py | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/compose.py#L53-L58 | def flip_iterable_dict(d: dict) -> dict:
"""Transform dictionary to unpack values to map to respective key."""
value_keys = disjoint_union((cartesian_product((v, k))
for k, v in d.items()))
return dict(value_keys) | [
"def",
"flip_iterable_dict",
"(",
"d",
":",
"dict",
")",
"->",
"dict",
":",
"value_keys",
"=",
"disjoint_union",
"(",
"(",
"cartesian_product",
"(",
"(",
"v",
",",
"k",
")",
")",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
")",
")",
... | Transform dictionary to unpack values to map to respective key. | [
"Transform",
"dictionary",
"to",
"unpack",
"values",
"to",
"map",
"to",
"respective",
"key",
"."
] | python | train |
alerta/python-alerta-client | alertaclient/commands/cmd_heartbeats.py | https://github.com/alerta/python-alerta-client/blob/7eb367b5fe87d5fc20b54dea8cddd7f09e251afa/alertaclient/commands/cmd_heartbeats.py#L16-L93 | def cli(obj, alert, severity, timeout, purge):
"""List heartbeats."""
client = obj['client']
if obj['output'] == 'json':
r = client.http.get('/heartbeats')
click.echo(json.dumps(r['heartbeats'], sort_keys=True, indent=4, ensure_ascii=False))
else:
timezone = obj['timezone']
... | [
"def",
"cli",
"(",
"obj",
",",
"alert",
",",
"severity",
",",
"timeout",
",",
"purge",
")",
":",
"client",
"=",
"obj",
"[",
"'client'",
"]",
"if",
"obj",
"[",
"'output'",
"]",
"==",
"'json'",
":",
"r",
"=",
"client",
".",
"http",
".",
"get",
"(",... | List heartbeats. | [
"List",
"heartbeats",
"."
] | python | train |
blackecho/Deep-Learning-TensorFlow | yadlt/utils/utilities.py | https://github.com/blackecho/Deep-Learning-TensorFlow/blob/ddeb1f2848da7b7bee166ad2152b4afc46bb2086/yadlt/utils/utilities.py#L46-L57 | def xavier_init(fan_in, fan_out, const=1):
"""Xavier initialization of network weights.
https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow
:param fan_in: fan in of the network (n_features)
:param fan_out: fan out of the network (n_components)
:param const: m... | [
"def",
"xavier_init",
"(",
"fan_in",
",",
"fan_out",
",",
"const",
"=",
"1",
")",
":",
"low",
"=",
"-",
"const",
"*",
"np",
".",
"sqrt",
"(",
"6.0",
"/",
"(",
"fan_in",
"+",
"fan_out",
")",
")",
"high",
"=",
"const",
"*",
"np",
".",
"sqrt",
"("... | Xavier initialization of network weights.
https://stackoverflow.com/questions/33640581/how-to-do-xavier-initialization-on-tensorflow
:param fan_in: fan in of the network (n_features)
:param fan_out: fan out of the network (n_components)
:param const: multiplicative constant | [
"Xavier",
"initialization",
"of",
"network",
"weights",
"."
] | python | train |
saltstack/salt | salt/states/pcs.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L900-L936 | def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None):
'''
Ensure a resource operation default in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
... | [
"def",
"resource_op_defaults_to",
"(",
"name",
",",
"op_default",
",",
"value",
",",
"extra_args",
"=",
"None",
",",
"cibname",
"=",
"None",
")",
":",
"return",
"_item_present",
"(",
"name",
"=",
"name",
",",
"item",
"=",
"'resource'",
",",
"item_id",
"=",... | Ensure a resource operation default in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: pcs_properties__resource_op_defaults_to_{{op_default}})
... | [
"Ensure",
"a",
"resource",
"operation",
"default",
"in",
"the",
"cluster",
"is",
"set",
"to",
"a",
"given",
"value"
] | python | train |
lehins/python-wepay | wepay/calls/user.py | https://github.com/lehins/python-wepay/blob/414d25a1a8d0ecb22a3ddd1f16c60b805bb52a1f/wepay/calls/user.py#L59-L89 | def __register(self, client_id, client_secret, email, scope, first_name,
last_name, original_ip, original_device, **kwargs):
"""Call documentation: `/user/register
<https://www.wepay.com/developer/reference/user#register>`_, plus
extra keyword parameter:
:keyw... | [
"def",
"__register",
"(",
"self",
",",
"client_id",
",",
"client_secret",
",",
"email",
",",
"scope",
",",
"first_name",
",",
"last_name",
",",
"original_ip",
",",
"original_device",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'client_id'",
":"... | Call documentation: `/user/register
<https://www.wepay.com/developer/reference/user#register>`_, plus
extra keyword parameter:
:keyword bool batch_mode: turn on/off the batch_mode, see
:class:`wepay.api.WePay`
:keyword str batch_reference_id: `reference_id` param fo... | [
"Call",
"documentation",
":",
"/",
"user",
"/",
"register",
"<https",
":",
"//",
"www",
".",
"wepay",
".",
"com",
"/",
"developer",
"/",
"reference",
"/",
"user#register",
">",
"_",
"plus",
"extra",
"keyword",
"parameter",
":",
":",
"keyword",
"bool",
"b... | python | train |
boriel/zxbasic | zxblex.py | https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxblex.py#L643-L670 | def is_label(token):
""" Return whether the token is a label (an integer number or id
at the beginning of a line.
To do so, we compute find_column() and moves back to the beginning
of the line if previous chars are spaces or tabs. If column 0 is
reached, it's a label.
"""
if not LABELS_ALLO... | [
"def",
"is_label",
"(",
"token",
")",
":",
"if",
"not",
"LABELS_ALLOWED",
":",
"return",
"False",
"c",
"=",
"i",
"=",
"token",
".",
"lexpos",
"input",
"=",
"token",
".",
"lexer",
".",
"lexdata",
"c",
"-=",
"1",
"while",
"c",
">",
"0",
"and",
"input... | Return whether the token is a label (an integer number or id
at the beginning of a line.
To do so, we compute find_column() and moves back to the beginning
of the line if previous chars are spaces or tabs. If column 0 is
reached, it's a label. | [
"Return",
"whether",
"the",
"token",
"is",
"a",
"label",
"(",
"an",
"integer",
"number",
"or",
"id",
"at",
"the",
"beginning",
"of",
"a",
"line",
"."
] | python | train |
Chilipp/psyplot | psyplot/data.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L216-L245 | def get_index_from_coord(coord, base_index):
"""Function to return the coordinate as integer, integer array or slice
If `coord` is zero-dimensional, the corresponding integer in `base_index`
will be supplied. Otherwise it is first tried to return a slice, if that
does not work an integer array with the... | [
"def",
"get_index_from_coord",
"(",
"coord",
",",
"base_index",
")",
":",
"try",
":",
"values",
"=",
"coord",
".",
"values",
"except",
"AttributeError",
":",
"values",
"=",
"coord",
"if",
"values",
".",
"ndim",
"==",
"0",
":",
"return",
"base_index",
".",
... | Function to return the coordinate as integer, integer array or slice
If `coord` is zero-dimensional, the corresponding integer in `base_index`
will be supplied. Otherwise it is first tried to return a slice, if that
does not work an integer array with the corresponding indices is returned.
Parameters
... | [
"Function",
"to",
"return",
"the",
"coordinate",
"as",
"integer",
"integer",
"array",
"or",
"slice"
] | python | train |
learningequality/ricecooker | examples/sample_program.py | https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/examples/sample_program.py#L317-L415 | def _build_tree(node, sourcetree):
"""
Parse nodes given in `sourcetree` and add as children of `node`.
"""
for child_source_node in sourcetree:
try:
main_file = child_source_node['files'][0] if 'files' in child_source_node else {}
kind = guess_content_kind(path=main_file... | [
"def",
"_build_tree",
"(",
"node",
",",
"sourcetree",
")",
":",
"for",
"child_source_node",
"in",
"sourcetree",
":",
"try",
":",
"main_file",
"=",
"child_source_node",
"[",
"'files'",
"]",
"[",
"0",
"]",
"if",
"'files'",
"in",
"child_source_node",
"else",
"{... | Parse nodes given in `sourcetree` and add as children of `node`. | [
"Parse",
"nodes",
"given",
"in",
"sourcetree",
"and",
"add",
"as",
"children",
"of",
"node",
"."
] | python | train |
JoseAntFer/pyny3d | pyny3d/geoms.py | https://github.com/JoseAntFer/pyny3d/blob/fb81684935a24f7e50c975cb4383c81a63ab56df/pyny3d/geoms.py#L993-L1051 | def plot2d(self, c_poly='default', alpha=1, cmap='default', ret=False,
title=' ', colorbar=False, cbar_label=''):
"""
Generates a 2D plot for the z=0 Surface projection.
:param c_poly: Polygons color.
:type c_poly: matplotlib color
:param alpha: Op... | [
"def",
"plot2d",
"(",
"self",
",",
"c_poly",
"=",
"'default'",
",",
"alpha",
"=",
"1",
",",
"cmap",
"=",
"'default'",
",",
"ret",
"=",
"False",
",",
"title",
"=",
"' '",
",",
"colorbar",
"=",
"False",
",",
"cbar_label",
"=",
"''",
")",
":",
"import... | Generates a 2D plot for the z=0 Surface projection.
:param c_poly: Polygons color.
:type c_poly: matplotlib color
:param alpha: Opacity.
:type alpha: float
:param cmap: colormap
:type cmap: matplotlib.cm
:param ret: If True, returns the figure. It... | [
"Generates",
"a",
"2D",
"plot",
"for",
"the",
"z",
"=",
"0",
"Surface",
"projection",
".",
":",
"param",
"c_poly",
":",
"Polygons",
"color",
".",
":",
"type",
"c_poly",
":",
"matplotlib",
"color",
":",
"param",
"alpha",
":",
"Opacity",
".",
":",
"type"... | python | train |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/bases.py | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/bases.py#L424-L445 | def from_dir(cls, ID, datadir, parser, pattern='*.fcs', recursive=False,
readdata_kwargs={}, readmeta_kwargs={}, **ID_kwargs):
"""
Create a Collection of measurements from data files contained in a directory.
Parameters
----------
ID : hashable
Colle... | [
"def",
"from_dir",
"(",
"cls",
",",
"ID",
",",
"datadir",
",",
"parser",
",",
"pattern",
"=",
"'*.fcs'",
",",
"recursive",
"=",
"False",
",",
"readdata_kwargs",
"=",
"{",
"}",
",",
"readmeta_kwargs",
"=",
"{",
"}",
",",
"*",
"*",
"ID_kwargs",
")",
":... | Create a Collection of measurements from data files contained in a directory.
Parameters
----------
ID : hashable
Collection ID
datadir : str
Path of directory containing the data files.
pattern : str
Only files matching the pattern will be us... | [
"Create",
"a",
"Collection",
"of",
"measurements",
"from",
"data",
"files",
"contained",
"in",
"a",
"directory",
"."
] | python | train |
partofthething/ace | ace/smoother.py | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/smoother.py#L249-L254 | def _remove_observation_from_means(self, xj, yj):
"""Update the means without recalculating for the deletion of one observation."""
self._mean_x_in_window = ((self.window_size * self._mean_x_in_window - xj) /
(self.window_size - 1.0))
self._mean_y_in_window = ((... | [
"def",
"_remove_observation_from_means",
"(",
"self",
",",
"xj",
",",
"yj",
")",
":",
"self",
".",
"_mean_x_in_window",
"=",
"(",
"(",
"self",
".",
"window_size",
"*",
"self",
".",
"_mean_x_in_window",
"-",
"xj",
")",
"/",
"(",
"self",
".",
"window_size",
... | Update the means without recalculating for the deletion of one observation. | [
"Update",
"the",
"means",
"without",
"recalculating",
"for",
"the",
"deletion",
"of",
"one",
"observation",
"."
] | python | train |
polyaxon/polyaxon-cli | polyaxon_cli/cli/project.py | https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/project.py#L47-L51 | def project(ctx, project): # pylint:disable=redefined-outer-name
"""Commands for projects."""
if ctx.invoked_subcommand not in ['create', 'list']:
ctx.obj = ctx.obj or {}
ctx.obj['project'] = project | [
"def",
"project",
"(",
"ctx",
",",
"project",
")",
":",
"# pylint:disable=redefined-outer-name",
"if",
"ctx",
".",
"invoked_subcommand",
"not",
"in",
"[",
"'create'",
",",
"'list'",
"]",
":",
"ctx",
".",
"obj",
"=",
"ctx",
".",
"obj",
"or",
"{",
"}",
"ct... | Commands for projects. | [
"Commands",
"for",
"projects",
"."
] | python | valid |
apache/incubator-heron | heronpy/api/bolt/window_bolt.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heronpy/api/bolt/window_bolt.py#L86-L94 | def process(self, tup):
"""Process a single tuple of input
We add the (time, tuple) pair into our current_tuples. And then look for expiring
elemnents
"""
curtime = int(time.time())
self.current_tuples.append((tup, curtime))
self._expire(curtime) | [
"def",
"process",
"(",
"self",
",",
"tup",
")",
":",
"curtime",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"self",
".",
"current_tuples",
".",
"append",
"(",
"(",
"tup",
",",
"curtime",
")",
")",
"self",
".",
"_expire",
"(",
"curtime",
... | Process a single tuple of input
We add the (time, tuple) pair into our current_tuples. And then look for expiring
elemnents | [
"Process",
"a",
"single",
"tuple",
"of",
"input"
] | python | valid |
MrYsLab/pymata-aio | pymata_aio/pymata_iot.py | https://github.com/MrYsLab/pymata-aio/blob/015081a4628b9d47dfe3f8d6c698ff903f107810/pymata_aio/pymata_iot.py#L577-L586 | def analog_latch_callback(self, data):
"""
This method handles analog_latch data received from pymata_core
:param data: analog latch callback message
:returns:{"method": "analog_latch_data_reply", "params": [ANALOG_PIN, VALUE_AT_TRIGGER, TIME_STAMP_STRING]}
"""
ts = data[... | [
"def",
"analog_latch_callback",
"(",
"self",
",",
"data",
")",
":",
"ts",
"=",
"data",
"[",
"2",
"]",
"st",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"ts",
")",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
")",
"reply",
"=",
"json",
... | This method handles analog_latch data received from pymata_core
:param data: analog latch callback message
:returns:{"method": "analog_latch_data_reply", "params": [ANALOG_PIN, VALUE_AT_TRIGGER, TIME_STAMP_STRING]} | [
"This",
"method",
"handles",
"analog_latch",
"data",
"received",
"from",
"pymata_core",
":",
"param",
"data",
":",
"analog",
"latch",
"callback",
"message",
":",
"returns",
":",
"{",
"method",
":",
"analog_latch_data_reply",
"params",
":",
"[",
"ANALOG_PIN",
"VA... | python | train |
Peter-Slump/python-keycloak-client | src/keycloak/admin/users.py | https://github.com/Peter-Slump/python-keycloak-client/blob/379ae58f3c65892327b0c98c06d4982aa83f357e/src/keycloak/admin/users.py#L60-L70 | def all(self):
"""
Return all registered users
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource
"""
return self._client.get(
url=self._client.get_full_url(
self.get_path('collection', realm=self._realm_name)
)
... | [
"def",
"all",
"(",
"self",
")",
":",
"return",
"self",
".",
"_client",
".",
"get",
"(",
"url",
"=",
"self",
".",
"_client",
".",
"get_full_url",
"(",
"self",
".",
"get_path",
"(",
"'collection'",
",",
"realm",
"=",
"self",
".",
"_realm_name",
")",
")... | Return all registered users
http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource | [
"Return",
"all",
"registered",
"users"
] | python | train |
viralogic/py-enumerable | py_linq/py_linq.py | https://github.com/viralogic/py-enumerable/blob/63363649bccef223379e1e87056747240c83aa9d/py_linq/py_linq.py#L212-L220 | def where(self, predicate):
"""
Returns new Enumerable where elements matching predicate are selected
:param predicate: predicate as a lambda expression
:return: new Enumerable object
"""
if predicate is None:
raise NullArgumentError("No predicate given for wh... | [
"def",
"where",
"(",
"self",
",",
"predicate",
")",
":",
"if",
"predicate",
"is",
"None",
":",
"raise",
"NullArgumentError",
"(",
"\"No predicate given for where clause\"",
")",
"return",
"Enumerable",
"(",
"itertools",
".",
"ifilter",
"(",
"predicate",
",",
"se... | Returns new Enumerable where elements matching predicate are selected
:param predicate: predicate as a lambda expression
:return: new Enumerable object | [
"Returns",
"new",
"Enumerable",
"where",
"elements",
"matching",
"predicate",
"are",
"selected",
":",
"param",
"predicate",
":",
"predicate",
"as",
"a",
"lambda",
"expression",
":",
"return",
":",
"new",
"Enumerable",
"object"
] | python | train |
DarkEnergySurvey/ugali | ugali/utils/bayesian_efficiency.py | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/bayesian_efficiency.py#L24-L76 | def confidenceInterval(n, k, alpha = 0.68, errorbar=False):
"""
Given n tests and k successes, return efficiency and confidence interval.
"""
try:
e = float(k) / float(n)
except ZeroDivisionError:
return np.nan, [np.nan, np.nan]
bins = 1000001
dx = 1. / bins
efficiency ... | [
"def",
"confidenceInterval",
"(",
"n",
",",
"k",
",",
"alpha",
"=",
"0.68",
",",
"errorbar",
"=",
"False",
")",
":",
"try",
":",
"e",
"=",
"float",
"(",
"k",
")",
"/",
"float",
"(",
"n",
")",
"except",
"ZeroDivisionError",
":",
"return",
"np",
".",... | Given n tests and k successes, return efficiency and confidence interval. | [
"Given",
"n",
"tests",
"and",
"k",
"successes",
"return",
"efficiency",
"and",
"confidence",
"interval",
"."
] | python | train |
rbuffat/pyepw | pyepw/epw.py | https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L3894-L3915 | def depth_soil_conductivity(self, value=None):
"""Corresponds to IDD Field `depth_soil_conductivity`
Args:
value (float): value for IDD Field `depth_soil_conductivity`
Unit: W/m-K,
if `value` is None it will not be checked against the
specific... | [
"def",
"depth_soil_conductivity",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to b... | Corresponds to IDD Field `depth_soil_conductivity`
Args:
value (float): value for IDD Field `depth_soil_conductivity`
Unit: W/m-K,
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises... | [
"Corresponds",
"to",
"IDD",
"Field",
"depth_soil_conductivity"
] | python | train |
Kortemme-Lab/klab | klab/db/sqlalchemy_interface.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/sqlalchemy_interface.py#L48-L61 | def row_to_dict(r, keep_relationships = False):
'''Converts an SQLAlchemy record to a Python dict. We assume that _sa_instance_state exists and is the only value we do not care about.
If DeclarativeBase is passed then all DeclarativeBase objects (e.g. those created by relationships) are also removed.
'''... | [
"def",
"row_to_dict",
"(",
"r",
",",
"keep_relationships",
"=",
"False",
")",
":",
"d",
"=",
"{",
"}",
"if",
"not",
"keep_relationships",
":",
"# only returns the table columns",
"t",
"=",
"r",
".",
"__table__",
"for",
"c",
"in",
"[",
"c",
".",
"name",
"... | Converts an SQLAlchemy record to a Python dict. We assume that _sa_instance_state exists and is the only value we do not care about.
If DeclarativeBase is passed then all DeclarativeBase objects (e.g. those created by relationships) are also removed. | [
"Converts",
"an",
"SQLAlchemy",
"record",
"to",
"a",
"Python",
"dict",
".",
"We",
"assume",
"that",
"_sa_instance_state",
"exists",
"and",
"is",
"the",
"only",
"value",
"we",
"do",
"not",
"care",
"about",
".",
"If",
"DeclarativeBase",
"is",
"passed",
"then",... | python | train |
CivicSpleen/ambry | ambry/library/search_backends/postgres_backend.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/library/search_backends/postgres_backend.py#L623-L634 | def _delete(self, identifier=None):
""" Deletes given identifier from index.
Args:
identifier (str): identifier of the document to delete.
"""
query = text("""
DELETE FROM identifier_index
WHERE identifier = :identifier;
""")
self.exe... | [
"def",
"_delete",
"(",
"self",
",",
"identifier",
"=",
"None",
")",
":",
"query",
"=",
"text",
"(",
"\"\"\"\n DELETE FROM identifier_index\n WHERE identifier = :identifier;\n \"\"\"",
")",
"self",
".",
"execute",
"(",
"query",
",",
"identifier... | Deletes given identifier from index.
Args:
identifier (str): identifier of the document to delete. | [
"Deletes",
"given",
"identifier",
"from",
"index",
"."
] | python | train |
raamana/pyradigm | pyradigm/multiple.py | https://github.com/raamana/pyradigm/blob/8ffb7958329c88b09417087b86887a3c92f438c2/pyradigm/multiple.py#L195-L217 | def _get_data(self, id_list, format='MLDataset'):
"""Returns the data, from all modalities, for a given list of IDs"""
format = format.lower()
features = list() # returning a dict would be better if AutoMKL() can handle it
for modality, data in self._modalities.items():
if... | [
"def",
"_get_data",
"(",
"self",
",",
"id_list",
",",
"format",
"=",
"'MLDataset'",
")",
":",
"format",
"=",
"format",
".",
"lower",
"(",
")",
"features",
"=",
"list",
"(",
")",
"# returning a dict would be better if AutoMKL() can handle it",
"for",
"modality",
... | Returns the data, from all modalities, for a given list of IDs | [
"Returns",
"the",
"data",
"from",
"all",
"modalities",
"for",
"a",
"given",
"list",
"of",
"IDs"
] | python | train |
robotools/fontParts | Lib/fontParts/base/contour.py | https://github.com/robotools/fontParts/blob/d2ff106fe95f9d566161d936a645157626568712/Lib/fontParts/base/contour.py#L639-L678 | def _setStartSegment(self, segmentIndex, **kwargs):
"""
Subclasses may override this method.
"""
segments = self.segments
oldStart = segments[-1]
oldLast = segments[0]
# If the contour ends with a curve on top of a move,
# delete the move.
if oldLa... | [
"def",
"_setStartSegment",
"(",
"self",
",",
"segmentIndex",
",",
"*",
"*",
"kwargs",
")",
":",
"segments",
"=",
"self",
".",
"segments",
"oldStart",
"=",
"segments",
"[",
"-",
"1",
"]",
"oldLast",
"=",
"segments",
"[",
"0",
"]",
"# If the contour ends wit... | Subclasses may override this method. | [
"Subclasses",
"may",
"override",
"this",
"method",
"."
] | python | train |
saltstack/salt | salt/utils/cloud.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cloud.py#L956-L973 | def run_psexec_command(cmd, args, host, username, password, port=445):
'''
Run a command remotly using the psexec protocol
'''
if has_winexe() and not HAS_PSEXEC:
ret_code = run_winexe_command(cmd, args, host, username, password, port)
return None, None, ret_code
service_name = 'PS-E... | [
"def",
"run_psexec_command",
"(",
"cmd",
",",
"args",
",",
"host",
",",
"username",
",",
"password",
",",
"port",
"=",
"445",
")",
":",
"if",
"has_winexe",
"(",
")",
"and",
"not",
"HAS_PSEXEC",
":",
"ret_code",
"=",
"run_winexe_command",
"(",
"cmd",
",",... | Run a command remotly using the psexec protocol | [
"Run",
"a",
"command",
"remotly",
"using",
"the",
"psexec",
"protocol"
] | python | train |
erocarrera/pefile | pefile.py | https://github.com/erocarrera/pefile/blob/8a78a2e251a3f2336c232bf411133927b479edf2/pefile.py#L1089-L1120 | def contains_rva(self, rva):
"""Check whether the section contains the address provided."""
# Check if the SizeOfRawData is realistic. If it's bigger than the size of
# the whole PE file minus the start address of the section it could be
# either truncated or the SizeOfRawData contains ... | [
"def",
"contains_rva",
"(",
"self",
",",
"rva",
")",
":",
"# Check if the SizeOfRawData is realistic. If it's bigger than the size of",
"# the whole PE file minus the start address of the section it could be",
"# either truncated or the SizeOfRawData contains a misleading value.",
"# In either... | Check whether the section contains the address provided. | [
"Check",
"whether",
"the",
"section",
"contains",
"the",
"address",
"provided",
"."
] | python | train |
peterservice-rnd/robotframework-jsonvalidator | src/JsonValidator.py | https://github.com/peterservice-rnd/robotframework-jsonvalidator/blob/acde5045c04d0a7b9079f22707c3e71a5d3fa724/src/JsonValidator.py#L329-L345 | def element_should_not_exist(self, json_string, expr):
"""
Check that one or more elements, matching [ http://jsonselect.org/ | JSONSelect] expression, don't exist.
*DEPRECATED* JSON Select query language is outdated and not supported any more.
Use other keywords of this library to quer... | [
"def",
"element_should_not_exist",
"(",
"self",
",",
"json_string",
",",
"expr",
")",
":",
"value",
"=",
"self",
".",
"select_elements",
"(",
"json_string",
",",
"expr",
")",
"if",
"value",
"is",
"not",
"None",
":",
"raise",
"JsonValidatorError",
"(",
"'Elem... | Check that one or more elements, matching [ http://jsonselect.org/ | JSONSelect] expression, don't exist.
*DEPRECATED* JSON Select query language is outdated and not supported any more.
Use other keywords of this library to query JSON.
*Args:*\n
_json_string_ - JSON string;\n
_... | [
"Check",
"that",
"one",
"or",
"more",
"elements",
"matching",
"[",
"http",
":",
"//",
"jsonselect",
".",
"org",
"/",
"|",
"JSONSelect",
"]",
"expression",
"don",
"t",
"exist",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/resource/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/resource/managers.py#L809-L824 | def get_bin_hierarchy_design_session(self):
"""Gets the bin hierarchy design session.
return: (osid.resource.BinHierarchyDesignSession) - a
``BinHierarchyDesignSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_bin_hierarchy... | [
"def",
"get_bin_hierarchy_design_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_bin_hierarchy_design",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"sessions",
".",
"BinHierarchyDesign... | Gets the bin hierarchy design session.
return: (osid.resource.BinHierarchyDesignSession) - a
``BinHierarchyDesignSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_bin_hierarchy_design()`` is
``false``
*compl... | [
"Gets",
"the",
"bin",
"hierarchy",
"design",
"session",
"."
] | python | train |
ghukill/pyfc4 | pyfc4/models.py | https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/models.py#L1433-L1452 | def children(self, as_resources=False):
'''
method to return hierarchical children of this resource
Args:
as_resources (bool): if True, opens each as appropriate resource type instead of return URI only
Returns:
(list): list of resources
'''
children = [o for s,p,o in self.rdf.graph.triples((None... | [
"def",
"children",
"(",
"self",
",",
"as_resources",
"=",
"False",
")",
":",
"children",
"=",
"[",
"o",
"for",
"s",
",",
"p",
",",
"o",
"in",
"self",
".",
"rdf",
".",
"graph",
".",
"triples",
"(",
"(",
"None",
",",
"self",
".",
"rdf",
".",
"pre... | method to return hierarchical children of this resource
Args:
as_resources (bool): if True, opens each as appropriate resource type instead of return URI only
Returns:
(list): list of resources | [
"method",
"to",
"return",
"hierarchical",
"children",
"of",
"this",
"resource"
] | python | train |
fraoustin/flaskserver | flaskserver/main.py | https://github.com/fraoustin/flaskserver/blob/27ce6ead523ae42286993cab04406d17a92c6535/flaskserver/main.py#L250-L270 | def log(host=None, port=None, limit=0):
"""view log of web server"""
app.config['HOST'] = first_value(host, app.config.get('HOST',None), '0.0.0.0')
app.config['PORT'] = int(first_value(port, app.config.get('PORT',None), 5001))
if app.config['HOST'] == "0.0.0.0":
host="127.0.0.1"
else:... | [
"def",
"log",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"limit",
"=",
"0",
")",
":",
"app",
".",
"config",
"[",
"'HOST'",
"]",
"=",
"first_value",
"(",
"host",
",",
"app",
".",
"config",
".",
"get",
"(",
"'HOST'",
",",
"None",
")... | view log of web server | [
"view",
"log",
"of",
"web",
"server"
] | python | train |
openego/ding0 | ding0/grid/mv_grid/models/models.py | https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/grid/mv_grid/models/models.py#L208-L231 | def insert(self, nodes, pos):
# TODO: check docstring
"""Inserts all nodes from `nodes` list into this route at position `pos`
Parameters
----------
nodes : type
Desc
pos : type
Desc
"""
node_list = []
... | [
"def",
"insert",
"(",
"self",
",",
"nodes",
",",
"pos",
")",
":",
"# TODO: check docstring",
"node_list",
"=",
"[",
"]",
"nodes_demand",
"=",
"0",
"for",
"node",
"in",
"[",
"node",
"for",
"node",
"in",
"nodes",
"]",
":",
"if",
"node",
".",
"_allocation... | Inserts all nodes from `nodes` list into this route at position `pos`
Parameters
----------
nodes : type
Desc
pos : type
Desc | [
"Inserts",
"all",
"nodes",
"from",
"nodes",
"list",
"into",
"this",
"route",
"at",
"position",
"pos",
"Parameters",
"----------",
"nodes",
":",
"type",
"Desc",
"pos",
":",
"type",
"Desc"
] | python | train |
cloud-custodian/cloud-custodian | tools/c7n_traildb/c7n_traildb/trailes.py | https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_traildb/c7n_traildb/trailes.py#L214-L268 | def index(
config, date=None, directory=None, concurrency=5, accounts=None,
tag=None, verbose=False):
"""index traildbs directly from s3 for multiple accounts.
context: assumes a daily traildb file in s3 with dated key path
"""
logging.basicConfig(level=(verbose and logging.DEBUG or lo... | [
"def",
"index",
"(",
"config",
",",
"date",
"=",
"None",
",",
"directory",
"=",
"None",
",",
"concurrency",
"=",
"5",
",",
"accounts",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"logging",
".",
"basicConfig",
"(",
... | index traildbs directly from s3 for multiple accounts.
context: assumes a daily traildb file in s3 with dated key path | [
"index",
"traildbs",
"directly",
"from",
"s3",
"for",
"multiple",
"accounts",
"."
] | python | train |
adafruit/Adafruit_Python_PN532 | Adafruit_PN532/PN532.py | https://github.com/adafruit/Adafruit_Python_PN532/blob/343521a8ec842ea82f680a5ed868fee16e9609bd/Adafruit_PN532/PN532.py#L363-L381 | def read_passive_target(self, card_baud=PN532_MIFARE_ISO14443A, timeout_sec=1):
"""Wait for a MiFare card to be available and return its UID when found.
Will wait up to timeout_sec seconds and return None if no card is found,
otherwise a bytearray with the UID of the found card is returned.
... | [
"def",
"read_passive_target",
"(",
"self",
",",
"card_baud",
"=",
"PN532_MIFARE_ISO14443A",
",",
"timeout_sec",
"=",
"1",
")",
":",
"# Send passive read command for 1 card. Expect at most a 7 byte UUID.",
"response",
"=",
"self",
".",
"call_function",
"(",
"PN532_COMMAND_I... | Wait for a MiFare card to be available and return its UID when found.
Will wait up to timeout_sec seconds and return None if no card is found,
otherwise a bytearray with the UID of the found card is returned. | [
"Wait",
"for",
"a",
"MiFare",
"card",
"to",
"be",
"available",
"and",
"return",
"its",
"UID",
"when",
"found",
".",
"Will",
"wait",
"up",
"to",
"timeout_sec",
"seconds",
"and",
"return",
"None",
"if",
"no",
"card",
"is",
"found",
"otherwise",
"a",
"bytea... | python | train |
googledatalab/pydatalab | solutionbox/structured_data/mltoolbox/_structured_data/_package.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L87-L105 | def _package_to_staging(staging_package_url):
"""Repackage this package from local installed location and copy it to GCS.
Args:
staging_package_url: GCS path.
"""
import google.datalab.ml as ml
# Find the package root. __file__ is under [package_root]/mltoolbox/_structured_data/this_file
... | [
"def",
"_package_to_staging",
"(",
"staging_package_url",
")",
":",
"import",
"google",
".",
"datalab",
".",
"ml",
"as",
"ml",
"# Find the package root. __file__ is under [package_root]/mltoolbox/_structured_data/this_file",
"package_root",
"=",
"os",
".",
"path",
".",
"abs... | Repackage this package from local installed location and copy it to GCS.
Args:
staging_package_url: GCS path. | [
"Repackage",
"this",
"package",
"from",
"local",
"installed",
"location",
"and",
"copy",
"it",
"to",
"GCS",
"."
] | python | train |
emin63/eyap | eyap/core/comments.py | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/core/comments.py#L398-L402 | def lookup_thread_id(self):
"Lookup the thread id as path to comment file."
path = os.path.join(self.realm, self.topic + '.csv')
return path | [
"def",
"lookup_thread_id",
"(",
"self",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"realm",
",",
"self",
".",
"topic",
"+",
"'.csv'",
")",
"return",
"path"
] | Lookup the thread id as path to comment file. | [
"Lookup",
"the",
"thread",
"id",
"as",
"path",
"to",
"comment",
"file",
"."
] | python | train |
pyroscope/pyrocore | src/pyrocore/util/matching.py | https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/util/matching.py#L281-L302 | def validate(self):
""" Validate filter condition (template method).
"""
from pyrocore.torrent import formatting
super(PatternFilter, self).validate()
self._value = self._value.lower()
self._template = None
self._is_regex = self._value.startswith('/') and self._v... | [
"def",
"validate",
"(",
"self",
")",
":",
"from",
"pyrocore",
".",
"torrent",
"import",
"formatting",
"super",
"(",
"PatternFilter",
",",
"self",
")",
".",
"validate",
"(",
")",
"self",
".",
"_value",
"=",
"self",
".",
"_value",
".",
"lower",
"(",
")",... | Validate filter condition (template method). | [
"Validate",
"filter",
"condition",
"(",
"template",
"method",
")",
"."
] | python | train |
JoelBender/bacpypes | py25/bacpypes/local/schedule.py | https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py25/bacpypes/local/schedule.py#L447-L558 | def eval(self, edate, etime):
"""Evaluate the schedule according to the provided date and time and
return the appropriate present value, or None if not in the effective
period."""
if _debug: LocalScheduleInterpreter._debug("eval %r %r", edate, etime)
# reference the schedule obj... | [
"def",
"eval",
"(",
"self",
",",
"edate",
",",
"etime",
")",
":",
"if",
"_debug",
":",
"LocalScheduleInterpreter",
".",
"_debug",
"(",
"\"eval %r %r\"",
",",
"edate",
",",
"etime",
")",
"# reference the schedule object",
"sched_obj",
"=",
"self",
".",
"sched_o... | Evaluate the schedule according to the provided date and time and
return the appropriate present value, or None if not in the effective
period. | [
"Evaluate",
"the",
"schedule",
"according",
"to",
"the",
"provided",
"date",
"and",
"time",
"and",
"return",
"the",
"appropriate",
"present",
"value",
"or",
"None",
"if",
"not",
"in",
"the",
"effective",
"period",
"."
] | python | train |
andersinno/python-database-sanitizer | database_sanitizer/utils/mysql.py | https://github.com/andersinno/python-database-sanitizer/blob/742bc1f43526b60f322a48f18c900f94fd446ed4/database_sanitizer/utils/mysql.py#L110-L131 | def decode_mysql_string_literal(text):
"""
Removes quotes and decodes escape sequences from given MySQL string literal
returning the result.
:param text: MySQL string literal, with the quotes still included.
:type text: str
:return: Given string literal with quotes removed and escape sequences... | [
"def",
"decode_mysql_string_literal",
"(",
"text",
")",
":",
"assert",
"text",
".",
"startswith",
"(",
"\"'\"",
")",
"assert",
"text",
".",
"endswith",
"(",
"\"'\"",
")",
"# Ditch quotes from the string literal.",
"text",
"=",
"text",
"[",
"1",
":",
"-",
"1",
... | Removes quotes and decodes escape sequences from given MySQL string literal
returning the result.
:param text: MySQL string literal, with the quotes still included.
:type text: str
:return: Given string literal with quotes removed and escape sequences
decoded.
:rtype: str | [
"Removes",
"quotes",
"and",
"decodes",
"escape",
"sequences",
"from",
"given",
"MySQL",
"string",
"literal",
"returning",
"the",
"result",
"."
] | python | train |
albahnsen/CostSensitiveClassification | costcla/models/regression.py | https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/regression.py#L20-L40 | def _intercept_dot(w, X):
"""Computes y * np.dot(X, w).
It takes into consideration if the intercept should be fit or not.
Parameters
----------
w : ndarray, shape (n_features,) or (n_features + 1,)
Coefficient vector.
X : {array-like, sparse matrix}, shape (n_samples, n_features)
... | [
"def",
"_intercept_dot",
"(",
"w",
",",
"X",
")",
":",
"c",
"=",
"0.",
"if",
"w",
".",
"size",
"==",
"X",
".",
"shape",
"[",
"1",
"]",
"+",
"1",
":",
"c",
"=",
"w",
"[",
"-",
"1",
"]",
"w",
"=",
"w",
"[",
":",
"-",
"1",
"]",
"z",
"=",... | Computes y * np.dot(X, w).
It takes into consideration if the intercept should be fit or not.
Parameters
----------
w : ndarray, shape (n_features,) or (n_features + 1,)
Coefficient vector.
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data. | [
"Computes",
"y",
"*",
"np",
".",
"dot",
"(",
"X",
"w",
")",
"."
] | python | train |
tomnor/channelpack | channelpack/pulltxt.py | https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pulltxt.py#L139-L173 | def rows2skip(self, decdel):
"""
Return the number of rows to skip based on the decimal delimiter
decdel.
When each record start to have the same number of matches, this
is where the data starts. This is the idea. And the number of
consecutive records to have the same nu... | [
"def",
"rows2skip",
"(",
"self",
",",
"decdel",
")",
":",
"if",
"decdel",
"==",
"'.'",
":",
"ms",
"=",
"self",
".",
"matches_p",
"elif",
"decdel",
"==",
"','",
":",
"ms",
"=",
"self",
".",
"matches_c",
"# else make error...",
"cnt",
"=",
"row",
"=",
... | Return the number of rows to skip based on the decimal delimiter
decdel.
When each record start to have the same number of matches, this
is where the data starts. This is the idea. And the number of
consecutive records to have the same number of matches is to be
EQUAL_CNT_REQ. | [
"Return",
"the",
"number",
"of",
"rows",
"to",
"skip",
"based",
"on",
"the",
"decimal",
"delimiter",
"decdel",
"."
] | python | train |
fp12/achallonge | challonge/match.py | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/match.py#L205-L222 | async def attach_url(self, url: str, description: str = None) -> Attachment:
""" add an url as an attachment
|methcoro|
Args:
url: url you want to add
description: *optional* description for your attachment
Returns:
Attachment:
Raises:
... | [
"async",
"def",
"attach_url",
"(",
"self",
",",
"url",
":",
"str",
",",
"description",
":",
"str",
"=",
"None",
")",
"->",
"Attachment",
":",
"return",
"await",
"self",
".",
"_attach",
"(",
"url",
"=",
"url",
",",
"description",
"=",
"description",
")"... | add an url as an attachment
|methcoro|
Args:
url: url you want to add
description: *optional* description for your attachment
Returns:
Attachment:
Raises:
ValueError: url must not be None
APIException | [
"add",
"an",
"url",
"as",
"an",
"attachment"
] | python | train |
pschmitt/python-opsview | opsview/opsview.py | https://github.com/pschmitt/python-opsview/blob/720acc06c491db32d18c79d20f04cae16e57a7fb/opsview/opsview.py#L441-L497 | def get_args():
'''
Parse CLI args
'''
parser = argparse.ArgumentParser(description='Process args')
parser.Add_argument(
'-H', '--host',
required=True,
action='store',
help='Remote host to connect to'
)
parser.add_argument(
'-P', '--port',
type... | [
"def",
"get_args",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Process args'",
")",
"parser",
".",
"Add_argument",
"(",
"'-H'",
",",
"'--host'",
",",
"required",
"=",
"True",
",",
"action",
"=",
"'store'",
",... | Parse CLI args | [
"Parse",
"CLI",
"args"
] | python | train |
PythonCharmers/python-future | src/future/standard_library/__init__.py | https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/standard_library/__init__.py#L701-L736 | def from_import(module_name, *symbol_names, **kwargs):
"""
Example use:
>>> HTTPConnection = from_import('http.client', 'HTTPConnection')
>>> HTTPServer = from_import('http.server', 'HTTPServer')
>>> urlopen, urlparse = from_import('urllib.request', 'urlopen', 'urlparse')
Equivalent... | [
"def",
"from_import",
"(",
"module_name",
",",
"*",
"symbol_names",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"PY3",
":",
"return",
"__import__",
"(",
"module_name",
")",
"else",
":",
"if",
"'backport'",
"in",
"kwargs",
"and",
"bool",
"(",
"kwargs",
"[",
... | Example use:
>>> HTTPConnection = from_import('http.client', 'HTTPConnection')
>>> HTTPServer = from_import('http.server', 'HTTPServer')
>>> urlopen, urlparse = from_import('urllib.request', 'urlopen', 'urlparse')
Equivalent to this on Py3:
>>> from module_name import symbol_names[... | [
"Example",
"use",
":",
">>>",
"HTTPConnection",
"=",
"from_import",
"(",
"http",
".",
"client",
"HTTPConnection",
")",
">>>",
"HTTPServer",
"=",
"from_import",
"(",
"http",
".",
"server",
"HTTPServer",
")",
">>>",
"urlopen",
"urlparse",
"=",
"from_import",
"("... | python | train |
SBRG/ssbio | ssbio/pipeline/gempro.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/pipeline/gempro.py#L278-L280 | def genes_with_a_representative_sequence(self):
"""DictList: All genes with a representative sequence."""
return DictList(x for x in self.genes if x.protein.representative_sequence) | [
"def",
"genes_with_a_representative_sequence",
"(",
"self",
")",
":",
"return",
"DictList",
"(",
"x",
"for",
"x",
"in",
"self",
".",
"genes",
"if",
"x",
".",
"protein",
".",
"representative_sequence",
")"
] | DictList: All genes with a representative sequence. | [
"DictList",
":",
"All",
"genes",
"with",
"a",
"representative",
"sequence",
"."
] | python | train |
mrcagney/kml2geojson | kml2geojson/main.py | https://github.com/mrcagney/kml2geojson/blob/6c4720f2b1327d636e15ce397dd808c9df8580a5/kml2geojson/main.py#L539-L589 | def convert(kml_path, output_dir, separate_folders=False,
style_type=None, style_filename='style.json'):
"""
Given a path to a KML file, convert it to one or several GeoJSON FeatureCollection files and save the result(s) to the given output directory.
If not ``separate_folders`` (the default), then creat... | [
"def",
"convert",
"(",
"kml_path",
",",
"output_dir",
",",
"separate_folders",
"=",
"False",
",",
"style_type",
"=",
"None",
",",
"style_filename",
"=",
"'style.json'",
")",
":",
"# Create absolute paths",
"kml_path",
"=",
"Path",
"(",
"kml_path",
")",
".",
"r... | Given a path to a KML file, convert it to one or several GeoJSON FeatureCollection files and save the result(s) to the given output directory.
If not ``separate_folders`` (the default), then create one GeoJSON file.
Otherwise, create several GeoJSON files, one for each folder in the KML file that contains geod... | [
"Given",
"a",
"path",
"to",
"a",
"KML",
"file",
"convert",
"it",
"to",
"one",
"or",
"several",
"GeoJSON",
"FeatureCollection",
"files",
"and",
"save",
"the",
"result",
"(",
"s",
")",
"to",
"the",
"given",
"output",
"directory",
"."
] | python | train |
i3visio/osrframework | osrframework/utils/configuration.py | https://github.com/i3visio/osrframework/blob/83437f4c14c9c08cb80a896bd9834c77f6567871/osrframework/utils/configuration.py#L106-L195 | def returnListOfConfigurationValues(util):
"""
Method that recovers the configuration information about each program
TODO: Grab the default file from the package data instead of storing it in
the main folder.
Args:
-----
util: Any of the utils that are contained in the framework: domai... | [
"def",
"returnListOfConfigurationValues",
"(",
"util",
")",
":",
"VALUES",
"=",
"{",
"}",
"# If a api_keys.cfg has not been found, creating it by copying from default",
"configPath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"getConfigPath",
"(",
")",
"[",
"\"appPath\""... | Method that recovers the configuration information about each program
TODO: Grab the default file from the package data instead of storing it in
the main folder.
Args:
-----
util: Any of the utils that are contained in the framework: domainfy,
entify, mailfy, phonefy, searchfy, usu... | [
"Method",
"that",
"recovers",
"the",
"configuration",
"information",
"about",
"each",
"program"
] | python | train |
pkgw/pwkit | pwkit/synphot.py | https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/synphot.py#L485-L493 | def register_bpass(self, telescope, klass):
"""Register a Bandpass class."""
if telescope in self._bpass_classes:
raise AlreadyDefinedError('bandpass class for %s already '
'defined', telescope)
self._note(telescope, None)
self._bpass_cl... | [
"def",
"register_bpass",
"(",
"self",
",",
"telescope",
",",
"klass",
")",
":",
"if",
"telescope",
"in",
"self",
".",
"_bpass_classes",
":",
"raise",
"AlreadyDefinedError",
"(",
"'bandpass class for %s already '",
"'defined'",
",",
"telescope",
")",
"self",
".",
... | Register a Bandpass class. | [
"Register",
"a",
"Bandpass",
"class",
"."
] | python | train |
quintusdias/glymur | glymur/codestream.py | https://github.com/quintusdias/glymur/blob/8b8fb091130fff00f1028dc82219e69e3f9baf6d/glymur/codestream.py#L244-L268 | def _parse_reserved_segment(self, fptr):
"""Parse valid marker segment, segment description is unknown.
Parameters
----------
fptr : file object
The file to parse.
Returns
-------
Segment
The current segment.
"""
offset = ... | [
"def",
"_parse_reserved_segment",
"(",
"self",
",",
"fptr",
")",
":",
"offset",
"=",
"fptr",
".",
"tell",
"(",
")",
"-",
"2",
"read_buffer",
"=",
"fptr",
".",
"read",
"(",
"2",
")",
"length",
",",
"=",
"struct",
".",
"unpack",
"(",
"'>H'",
",",
"re... | Parse valid marker segment, segment description is unknown.
Parameters
----------
fptr : file object
The file to parse.
Returns
-------
Segment
The current segment. | [
"Parse",
"valid",
"marker",
"segment",
"segment",
"description",
"is",
"unknown",
"."
] | python | train |
spyder-ide/spyder | spyder/utils/syntaxhighlighters.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/syntaxhighlighters.py#L1220-L1230 | def highlightBlock(self, text):
""" Actually highlight the block"""
# Note that an undefined blockstate is equal to -1, so the first block
# will have the correct behaviour of starting at 0.
if self._allow_highlight:
start = self.previousBlockState() + 1
end... | [
"def",
"highlightBlock",
"(",
"self",
",",
"text",
")",
":",
"# Note that an undefined blockstate is equal to -1, so the first block\r",
"# will have the correct behaviour of starting at 0.\r",
"if",
"self",
".",
"_allow_highlight",
":",
"start",
"=",
"self",
".",
"previousBloc... | Actually highlight the block | [
"Actually",
"highlight",
"the",
"block"
] | python | train |
jmcgeheeiv/pyfakefs | pyfakefs/fake_filesystem.py | https://github.com/jmcgeheeiv/pyfakefs/blob/6c36fb8987108107fc861fc3013620d46c7d2f9c/pyfakefs/fake_filesystem.py#L703-L740 | def remove_entry(self, pathname_name, recursive=True):
"""Removes the specified child file or directory.
Args:
pathname_name: Basename of the child object to remove.
recursive: If True (default), the entries in contained directories
are deleted first. Used to pro... | [
"def",
"remove_entry",
"(",
"self",
",",
"pathname_name",
",",
"recursive",
"=",
"True",
")",
":",
"pathname_name",
"=",
"self",
".",
"_normalized_entryname",
"(",
"pathname_name",
")",
"entry",
"=",
"self",
".",
"get_entry",
"(",
"pathname_name",
")",
"if",
... | Removes the specified child file or directory.
Args:
pathname_name: Basename of the child object to remove.
recursive: If True (default), the entries in contained directories
are deleted first. Used to propagate removal errors
(e.g. permission problems) f... | [
"Removes",
"the",
"specified",
"child",
"file",
"or",
"directory",
"."
] | python | train |
sbjorn/vici | vici/session.py | https://github.com/sbjorn/vici/blob/147135905b68892734b09ec8a569c71733648090/vici/session.py#L357-L373 | def _read(self):
"""Get next packet from transport.
:return: parsed packet in a tuple with message type and payload
:rtype: :py:class:`collections.namedtuple`
"""
raw_response = self.transport.receive()
response = Packet.parse(raw_response)
# FIXME
if re... | [
"def",
"_read",
"(",
"self",
")",
":",
"raw_response",
"=",
"self",
".",
"transport",
".",
"receive",
"(",
")",
"response",
"=",
"Packet",
".",
"parse",
"(",
"raw_response",
")",
"# FIXME",
"if",
"response",
".",
"response_type",
"==",
"Packet",
".",
"EV... | Get next packet from transport.
:return: parsed packet in a tuple with message type and payload
:rtype: :py:class:`collections.namedtuple` | [
"Get",
"next",
"packet",
"from",
"transport",
"."
] | python | train |
intake/intake | intake/config.py | https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/config.py#L79-L90 | def intake_path_dirs(path):
"""Return a list of directories from the intake path.
If a string, perhaps taken from an environment variable, then the
list of paths will be split on the character ":" for posix of ";" for
windows. Protocol indicators ("protocol://") will be ignored.
"""
if isinstan... | [
"def",
"intake_path_dirs",
"(",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"path",
"import",
"re",
"pattern",
"=",
"re",
".",
"compile",
"(",
"\";\"",
"if",
"os",
".",
"name",
"==",
"... | Return a list of directories from the intake path.
If a string, perhaps taken from an environment variable, then the
list of paths will be split on the character ":" for posix of ";" for
windows. Protocol indicators ("protocol://") will be ignored. | [
"Return",
"a",
"list",
"of",
"directories",
"from",
"the",
"intake",
"path",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.