repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
Kortemme-Lab/klab | klab/box_backup.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/box_backup.py#L282-L321 | def _upload_in_splits( self, destination_folder_id, source_path, preflight_check, verbose = True, chunked_upload_threads = 5 ):
'''
Since Box has a maximum file size limit (15 GB at time of writing),
we need to split files larger than this into smaller parts, and chunk upload each part
'... | [
"def",
"_upload_in_splits",
"(",
"self",
",",
"destination_folder_id",
",",
"source_path",
",",
"preflight_check",
",",
"verbose",
"=",
"True",
",",
"chunked_upload_threads",
"=",
"5",
")",
":",
"file_size",
"=",
"os",
".",
"stat",
"(",
"source_path",
")",
"."... | Since Box has a maximum file size limit (15 GB at time of writing),
we need to split files larger than this into smaller parts, and chunk upload each part | [
"Since",
"Box",
"has",
"a",
"maximum",
"file",
"size",
"limit",
"(",
"15",
"GB",
"at",
"time",
"of",
"writing",
")",
"we",
"need",
"to",
"split",
"files",
"larger",
"than",
"this",
"into",
"smaller",
"parts",
"and",
"chunk",
"upload",
"each",
"part"
] | python | train | 53.625 |
expfactory/expfactory | expfactory/variables.py | https://github.com/expfactory/expfactory/blob/27ce6cc93e17231df8a8024f18e631336afd3501/expfactory/variables.py#L227-L249 | def _validate_row(row, sep=',', required_length=None):
'''validate_row will ensure that a row has the proper length, and is
not empty and cleaned of extra spaces.
Parameters
==========
row: a single row, not yet parsed.
Returns a valid row, or None if not valid
'''
if ... | [
"def",
"_validate_row",
"(",
"row",
",",
"sep",
"=",
"','",
",",
"required_length",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"row",
",",
"list",
")",
":",
"row",
"=",
"_parse_row",
"(",
"row",
",",
"sep",
")",
"if",
"required_length",
"... | validate_row will ensure that a row has the proper length, and is
not empty and cleaned of extra spaces.
Parameters
==========
row: a single row, not yet parsed.
Returns a valid row, or None if not valid | [
"validate_row",
"will",
"ensure",
"that",
"a",
"row",
"has",
"the",
"proper",
"length",
"and",
"is",
"not",
"empty",
"and",
"cleaned",
"of",
"extra",
"spaces",
".",
"Parameters",
"==========",
"row",
":",
"a",
"single",
"row",
"not",
"yet",
"parsed",
"."
] | python | train | 29.086957 |
awacha/credolib | credolib/utils.py | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/utils.py#L16-L30 | def putlogo(figure=None):
"""Puts the CREDO logo at the bottom right of the current figure (or
the figure given by the ``figure`` argument if supplied).
"""
ip = get_ipython()
if figure is None:
figure=plt.gcf()
curraxis= figure.gca()
logoaxis = figure.add_axes([0.89, 0.01, 0.1, 0.1]... | [
"def",
"putlogo",
"(",
"figure",
"=",
"None",
")",
":",
"ip",
"=",
"get_ipython",
"(",
")",
"if",
"figure",
"is",
"None",
":",
"figure",
"=",
"plt",
".",
"gcf",
"(",
")",
"curraxis",
"=",
"figure",
".",
"gca",
"(",
")",
"logoaxis",
"=",
"figure",
... | Puts the CREDO logo at the bottom right of the current figure (or
the figure given by the ``figure`` argument if supplied). | [
"Puts",
"the",
"CREDO",
"logo",
"at",
"the",
"bottom",
"right",
"of",
"the",
"current",
"figure",
"(",
"or",
"the",
"figure",
"given",
"by",
"the",
"figure",
"argument",
"if",
"supplied",
")",
"."
] | python | train | 34.666667 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_interface_ext.py#L1222-L1238 | def get_interface_detail_output_interface_ifHCOutOctets(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")... | [
"def",
"get_interface_detail_output_interface_ifHCOutOctets",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_detail\"",
")",
"con... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 49.588235 |
clalancette/pycdlib | pycdlib/udf.py | https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/udf.py#L312-L325 | def record(self):
# type: () -> bytes
'''
A method to generate the string representing this UDF NSR Volume
Structure.
Parameters:
None.
Returns:
A string representing this UDF BEA Volume Strucutre.
'''
if not self._initialized:
... | [
"def",
"record",
"(",
"self",
")",
":",
"# type: () -> bytes",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'UDF NSR Volume Structure not initialized'",
")",
"return",
"struct",
".",
"pack",
"(",
"sel... | A method to generate the string representing this UDF NSR Volume
Structure.
Parameters:
None.
Returns:
A string representing this UDF BEA Volume Strucutre. | [
"A",
"method",
"to",
"generate",
"the",
"string",
"representing",
"this",
"UDF",
"NSR",
"Volume",
"Structure",
"."
] | python | train | 34.071429 |
assamite/creamas | creamas/math.py | https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/math.py#L25-L38 | def logistic(x, x0, k, L):
'''Logistic function.
See, e.g `Wikipedia <https://en.wikipedia.org/wiki/Logistic_function>`_.
:param x: point in x-axis
:type x: float or numpy.ndarray
:param float x0: sigmoid's midpoint
:param float k: steepness of the curve
:param float L: maximum value of th... | [
"def",
"logistic",
"(",
"x",
",",
"x0",
",",
"k",
",",
"L",
")",
":",
"return",
"L",
"/",
"(",
"1",
"+",
"exp",
"(",
"-",
"k",
"*",
"(",
"x",
"-",
"x0",
")",
")",
")"
] | Logistic function.
See, e.g `Wikipedia <https://en.wikipedia.org/wiki/Logistic_function>`_.
:param x: point in x-axis
:type x: float or numpy.ndarray
:param float x0: sigmoid's midpoint
:param float k: steepness of the curve
:param float L: maximum value of the curve
:returns: function's v... | [
"Logistic",
"function",
"."
] | python | train | 31.857143 |
jobovy/galpy | galpy/orbit/FullOrbit.py | https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/FullOrbit.py#L468-L485 | def plotER(self,*args,**kwargs):
"""
NAME:
plotER
PURPOSE:
plot ER(.) along the orbit
INPUT:
bovy_plot.bovy_plot inputs
OUTPUT:
figure to output device
HISTORY:
2014-06-16 - Written - Bovy (IAS)
"""
if... | [
"def",
"plotER",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"pop",
"(",
"'normed'",
",",
"False",
")",
":",
"kwargs",
"[",
"'d2'",
"]",
"=",
"'ERnorm'",
"else",
":",
"kwargs",
"[",
"'d2'",
"]",
"=",
"... | NAME:
plotER
PURPOSE:
plot ER(.) along the orbit
INPUT:
bovy_plot.bovy_plot inputs
OUTPUT:
figure to output device
HISTORY:
2014-06-16 - Written - Bovy (IAS) | [
"NAME",
":",
"plotER",
"PURPOSE",
":",
"plot",
"ER",
"(",
".",
")",
"along",
"the",
"orbit",
"INPUT",
":",
"bovy_plot",
".",
"bovy_plot",
"inputs",
"OUTPUT",
":",
"figure",
"to",
"output",
"device",
"HISTORY",
":",
"2014",
"-",
"06",
"-",
"16",
"-",
... | python | train | 25.111111 |
inasafe/inasafe | safe/defaults.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/defaults.py#L18-L28 | def default_provenance():
"""The provenance for the default values.
:return: default provenance.
:rtype: str
"""
field = TextParameter()
field.name = tr('Provenance')
field.description = tr('The provenance of minimum needs')
field.value = 'The minimum needs are based on BNPB Perka 7/200... | [
"def",
"default_provenance",
"(",
")",
":",
"field",
"=",
"TextParameter",
"(",
")",
"field",
".",
"name",
"=",
"tr",
"(",
"'Provenance'",
")",
"field",
".",
"description",
"=",
"tr",
"(",
"'The provenance of minimum needs'",
")",
"field",
".",
"value",
"=",... | The provenance for the default values.
:return: default provenance.
:rtype: str | [
"The",
"provenance",
"for",
"the",
"default",
"values",
"."
] | python | train | 30 |
apache/airflow | airflow/settings.py | https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/settings.py#L220-L235 | def prepare_classpath():
"""
Ensures that certain subfolders of AIRFLOW_HOME are on the classpath
"""
if DAGS_FOLDER not in sys.path:
sys.path.append(DAGS_FOLDER)
# Add ./config/ for loading custom log parsers etc, or
# airflow_local_settings etc.
config_path = os.path.join(AIRFLOW... | [
"def",
"prepare_classpath",
"(",
")",
":",
"if",
"DAGS_FOLDER",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"append",
"(",
"DAGS_FOLDER",
")",
"# Add ./config/ for loading custom log parsers etc, or",
"# airflow_local_settings etc.",
"config_path",
... | Ensures that certain subfolders of AIRFLOW_HOME are on the classpath | [
"Ensures",
"that",
"certain",
"subfolders",
"of",
"AIRFLOW_HOME",
"are",
"on",
"the",
"classpath"
] | python | test | 29.625 |
Microsoft/ApplicationInsights-Python | applicationinsights/flask/ext.py | https://github.com/Microsoft/ApplicationInsights-Python/blob/8452ab7126f9bb6964637d4aa1258c2af17563d6/applicationinsights/flask/ext.py#L137-L153 | def _init_trace_logging(self, app):
"""
Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is
set in the Flask config.
Args:
app (flask.Flask). the Flask application for which to initialize the extension.
"""
enabled = not app.config.get(CONF_... | [
"def",
"_init_trace_logging",
"(",
"self",
",",
"app",
")",
":",
"enabled",
"=",
"not",
"app",
".",
"config",
".",
"get",
"(",
"CONF_DISABLE_TRACE_LOGGING",
",",
"False",
")",
"if",
"not",
"enabled",
":",
"return",
"self",
".",
"_trace_log_handler",
"=",
"... | Sets up trace logging unless ``APPINSIGHTS_DISABLE_TRACE_LOGGING`` is
set in the Flask config.
Args:
app (flask.Flask). the Flask application for which to initialize the extension. | [
"Sets",
"up",
"trace",
"logging",
"unless",
"APPINSIGHTS_DISABLE_TRACE_LOGGING",
"is",
"set",
"in",
"the",
"Flask",
"config",
"."
] | python | train | 31.764706 |
Rikanishu/static-bundle | static_bundle/builders.py | https://github.com/Rikanishu/static-bundle/blob/2f6458cb9d9d9049b4fd829f7d6951a45d547c68/static_bundle/builders.py#L63-L74 | def collect_files(self):
"""
Return collected files links
:rtype: list[static_bundle.files.StaticFileResult]
"""
self.files = []
for bundle in self.bundles:
bundle.init_build(self, self.builder)
bundle_files = bundle.prepare()
self.fil... | [
"def",
"collect_files",
"(",
"self",
")",
":",
"self",
".",
"files",
"=",
"[",
"]",
"for",
"bundle",
"in",
"self",
".",
"bundles",
":",
"bundle",
".",
"init_build",
"(",
"self",
",",
"self",
".",
"builder",
")",
"bundle_files",
"=",
"bundle",
".",
"p... | Return collected files links
:rtype: list[static_bundle.files.StaticFileResult] | [
"Return",
"collected",
"files",
"links"
] | python | valid | 29.333333 |
saltstack/salt | salt/utils/github.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/github.py#L20-L71 | def get_user_pubkeys(users):
'''
Retrieve a set of public keys from GitHub for the specified list of users.
Expects input in list format. Optionally, a value in the list may be a dict
whose value is a list of key IDs to be returned. If this is not done, then
all keys will be returned.
Some exam... | [
"def",
"get_user_pubkeys",
"(",
"users",
")",
":",
"if",
"not",
"isinstance",
"(",
"users",
",",
"list",
")",
":",
"return",
"{",
"'Error'",
":",
"'A list of users is expected'",
"}",
"ret",
"=",
"{",
"}",
"for",
"user",
"in",
"users",
":",
"key_ids",
"=... | Retrieve a set of public keys from GitHub for the specified list of users.
Expects input in list format. Optionally, a value in the list may be a dict
whose value is a list of key IDs to be returned. If this is not done, then
all keys will be returned.
Some example data structures that coupld be passed... | [
"Retrieve",
"a",
"set",
"of",
"public",
"keys",
"from",
"GitHub",
"for",
"the",
"specified",
"list",
"of",
"users",
".",
"Expects",
"input",
"in",
"list",
"format",
".",
"Optionally",
"a",
"value",
"in",
"the",
"list",
"may",
"be",
"a",
"dict",
"whose",
... | python | train | 26.423077 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/djitemdata.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/djitemdata.py#L522-L535 | def taskfile_created_data(file_, role):
"""Return the data for created date
:param file_: the file that holds the data
:type file_: :class:`jukeboxcore.djadapter.models.File`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the created date
:rtype: depending... | [
"def",
"taskfile_created_data",
"(",
"file_",
",",
"role",
")",
":",
"if",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"DisplayRole",
"or",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"EditRole",
":",
"dt",
"=",
"file_",
".",
"date_created",
"return",
"dt_to_qda... | Return the data for created date
:param file_: the file that holds the data
:type file_: :class:`jukeboxcore.djadapter.models.File`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the created date
:rtype: depending on role
:raises: None | [
"Return",
"the",
"data",
"for",
"created",
"date"
] | python | train | 34 |
numberoverzero/bloop | bloop/transactions.py | https://github.com/numberoverzero/bloop/blob/4c95f5a0ff0802443a1c258bfaccecd1758363e7/bloop/transactions.py#L186-L194 | def prepare(self, engine, mode, items) -> None:
"""
Create a unique transaction id and dumps the items into a cached request object.
"""
self.tx_id = str(uuid.uuid4()).replace("-", "")
self.engine = engine
self.mode = mode
self.items = items
self._prepare_... | [
"def",
"prepare",
"(",
"self",
",",
"engine",
",",
"mode",
",",
"items",
")",
"->",
"None",
":",
"self",
".",
"tx_id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
"self",
".",
"engine",
... | Create a unique transaction id and dumps the items into a cached request object. | [
"Create",
"a",
"unique",
"transaction",
"id",
"and",
"dumps",
"the",
"items",
"into",
"a",
"cached",
"request",
"object",
"."
] | python | train | 35.666667 |
bitesofcode/projexui | projexui/widgets/xtoolbar.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtoolbar.py#L138-L194 | def refreshButton(self):
"""
Refreshes the button for this toolbar.
"""
collapsed = self.isCollapsed()
btn = self._collapseButton
if not btn:
return
btn.setMaximumSize(MAX_SIZE, MAX_SIZE)
# set up a vertical... | [
"def",
"refreshButton",
"(",
"self",
")",
":",
"collapsed",
"=",
"self",
".",
"isCollapsed",
"(",
")",
"btn",
"=",
"self",
".",
"_collapseButton",
"if",
"not",
"btn",
":",
"return",
"btn",
".",
"setMaximumSize",
"(",
"MAX_SIZE",
",",
"MAX_SIZE",
")",
"# ... | Refreshes the button for this toolbar. | [
"Refreshes",
"the",
"button",
"for",
"this",
"toolbar",
"."
] | python | train | 30.947368 |
Azure/azure-cosmos-python | azure/cosmos/cosmos_client.py | https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L2816-L2844 | def __CheckAndUnifyQueryFormat(self, query_body):
"""Checks and unifies the format of the query body.
:raises TypeError: If query_body is not of expected type (depending on the query compatibility mode).
:raises ValueError: If query_body is a dict but doesn\'t have valid query text.
:ra... | [
"def",
"__CheckAndUnifyQueryFormat",
"(",
"self",
",",
"query_body",
")",
":",
"if",
"(",
"self",
".",
"_query_compatibility_mode",
"==",
"CosmosClient",
".",
"_QueryCompatibilityMode",
".",
"Default",
"or",
"self",
".",
"_query_compatibility_mode",
"==",
"CosmosClien... | Checks and unifies the format of the query body.
:raises TypeError: If query_body is not of expected type (depending on the query compatibility mode).
:raises ValueError: If query_body is a dict but doesn\'t have valid query text.
:raises SystemError: If the query compatibility mode is undefine... | [
"Checks",
"and",
"unifies",
"the",
"format",
"of",
"the",
"query",
"body",
"."
] | python | train | 50.586207 |
pyviz/holoviews | holoviews/plotting/util.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/util.py#L868-L906 | def process_cmap(cmap, ncolors=None, provider=None, categorical=False):
"""
Convert valid colormap specifications to a list of colors.
"""
providers_checked="matplotlib, bokeh, or colorcet" if provider is None else provider
if isinstance(cmap, Cycle):
palette = [rgb2hex(c) if isinstance(c, ... | [
"def",
"process_cmap",
"(",
"cmap",
",",
"ncolors",
"=",
"None",
",",
"provider",
"=",
"None",
",",
"categorical",
"=",
"False",
")",
":",
"providers_checked",
"=",
"\"matplotlib, bokeh, or colorcet\"",
"if",
"provider",
"is",
"None",
"else",
"provider",
"if",
... | Convert valid colormap specifications to a list of colors. | [
"Convert",
"valid",
"colormap",
"specifications",
"to",
"a",
"list",
"of",
"colors",
"."
] | python | train | 46.666667 |
blockadeio/analyst_toolbench | blockade/cli/aws_serverless.py | https://github.com/blockadeio/analyst_toolbench/blob/159b6f8cf8a91c5ff050f1579636ea90ab269863/blockade/cli/aws_serverless.py#L592-L617 | def generate_dynamodb_tables():
"""Create the Blockade DynamoDB tables."""
logger.debug("[#] Setting up DynamoDB tables")
client = boto3.client('dynamodb', region_name=PRIMARY_REGION)
existing_tables = client.list_tables()['TableNames']
responses = list()
for label in DYNAMODB_TABLES:
i... | [
"def",
"generate_dynamodb_tables",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"[#] Setting up DynamoDB tables\"",
")",
"client",
"=",
"boto3",
".",
"client",
"(",
"'dynamodb'",
",",
"region_name",
"=",
"PRIMARY_REGION",
")",
"existing_tables",
"=",
"client",
".... | Create the Blockade DynamoDB tables. | [
"Create",
"the",
"Blockade",
"DynamoDB",
"tables",
"."
] | python | train | 34.230769 |
sawcordwell/pymdptoolbox | src/mdptoolbox/util.py | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/mdptoolbox/util.py#L146-L160 | def isStochastic(matrix):
"""Check that ``matrix`` is row stochastic.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is row stochastic, ``False`` otherwise.
"""
try:
absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0])))
except AttributeError:
... | [
"def",
"isStochastic",
"(",
"matrix",
")",
":",
"try",
":",
"absdiff",
"=",
"(",
"_np",
".",
"abs",
"(",
"matrix",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"-",
"_np",
".",
"ones",
"(",
"matrix",
".",
"shape",
"[",
"0",
"]",
")",
")",
")",
"ex... | Check that ``matrix`` is row stochastic.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is row stochastic, ``False`` otherwise. | [
"Check",
"that",
"matrix",
"is",
"row",
"stochastic",
"."
] | python | train | 31.533333 |
reingart/pyafipws | padron.py | https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/padron.py#L422-L443 | def ObtenerTablaParametros(self, tipo_recurso, sep="||"):
"Devuelve un array de elementos que tienen id y descripción"
if not self.client:
self.Conectar()
self.response = self.client("parametros", "v1", tipo_recurso)
result = json.loads(self.response)
ret = {}... | [
"def",
"ObtenerTablaParametros",
"(",
"self",
",",
"tipo_recurso",
",",
"sep",
"=",
"\"||\"",
")",
":",
"if",
"not",
"self",
".",
"client",
":",
"self",
".",
"Conectar",
"(",
")",
"self",
".",
"response",
"=",
"self",
".",
"client",
"(",
"\"parametros\""... | Devuelve un array de elementos que tienen id y descripción | [
"Devuelve",
"un",
"array",
"de",
"elementos",
"que",
"tienen",
"id",
"y",
"descripción"
] | python | train | 40.909091 |
softlayer/softlayer-python | SoftLayer/managers/vs.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L269-L305 | def reload_instance(self, instance_id,
post_uri=None,
ssh_keys=None,
image_id=None):
"""Perform an OS reload of an instance.
:param integer instance_id: the instance ID to reload
:param string post_url: The URI of the post-... | [
"def",
"reload_instance",
"(",
"self",
",",
"instance_id",
",",
"post_uri",
"=",
"None",
",",
"ssh_keys",
"=",
"None",
",",
"image_id",
"=",
"None",
")",
":",
"config",
"=",
"{",
"}",
"if",
"post_uri",
":",
"config",
"[",
"'customProvisionScriptUri'",
"]",... | Perform an OS reload of an instance.
:param integer instance_id: the instance ID to reload
:param string post_url: The URI of the post-install script to run
after reload
:param list ssh_keys: The SSH keys to add to the root user
:param int image_id: The G... | [
"Perform",
"an",
"OS",
"reload",
"of",
"an",
"instance",
"."
] | python | train | 36.189189 |
Netflix-Skunkworks/historical | historical/attributes.py | https://github.com/Netflix-Skunkworks/historical/blob/c3ebaa8388a3fe67e23a6c9c6b04c3e618497c4a/historical/attributes.py#L45-L49 | def serialize(self, value):
"""Takes a datetime object and returns a string"""
if isinstance(value, str):
return value
return value.strftime(DATETIME_FORMAT) | [
"def",
"serialize",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"value",
"return",
"value",
".",
"strftime",
"(",
"DATETIME_FORMAT",
")"
] | Takes a datetime object and returns a string | [
"Takes",
"a",
"datetime",
"object",
"and",
"returns",
"a",
"string"
] | python | train | 37.8 |
tensorflow/tensor2tensor | tensor2tensor/envs/gym_spaces_utils.py | https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/gym_spaces_utils.py#L41-L69 | def gym_space_spec(gym_space):
"""Returns a reading spec of a gym space.
NOTE: Only implemented currently for Box and Discrete.
Args:
gym_space: instance of gym.spaces whose spec we want.
Returns:
Reading spec for that space.
Raises:
NotImplementedError: For spaces whose reading spec we haven'... | [
"def",
"gym_space_spec",
"(",
"gym_space",
")",
":",
"# First try to determine the type.",
"try",
":",
"tf_dtype",
"=",
"tf",
".",
"as_dtype",
"(",
"gym_space",
".",
"dtype",
")",
"except",
"TypeError",
"as",
"e",
":",
"tf",
".",
"logging",
".",
"error",
"("... | Returns a reading spec of a gym space.
NOTE: Only implemented currently for Box and Discrete.
Args:
gym_space: instance of gym.spaces whose spec we want.
Returns:
Reading spec for that space.
Raises:
NotImplementedError: For spaces whose reading spec we haven't implemented. | [
"Returns",
"a",
"reading",
"spec",
"of",
"a",
"gym",
"space",
"."
] | python | train | 27.793103 |
proteanhq/protean | src/protean/core/field/base.py | https://github.com/proteanhq/protean/blob/0e29873f4aa634aa93cc08ed675dd749c7ed4b0f/src/protean/core/field/base.py#L169-L211 | def _load(self, value: Any):
"""
Load the value for the field, run validators and return the value.
Subclasses can override this to provide custom load logic.
:param value: value of the field
"""
if value in self.empty_values:
# If a default has been set fo... | [
"def",
"_load",
"(",
"self",
",",
"value",
":",
"Any",
")",
":",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"# If a default has been set for the field return it",
"if",
"self",
".",
"default",
"is",
"not",
"None",
":",
"default",
"=",
"self",
"."... | Load the value for the field, run validators and return the value.
Subclasses can override this to provide custom load logic.
:param value: value of the field | [
"Load",
"the",
"value",
"for",
"the",
"field",
"run",
"validators",
"and",
"return",
"the",
"value",
".",
"Subclasses",
"can",
"override",
"this",
"to",
"provide",
"custom",
"load",
"logic",
"."
] | python | train | 33.55814 |
inasafe/inasafe | safe/gis/vector/prepare_vector_layer.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gis/vector/prepare_vector_layer.py#L64-L128 | def prepare_vector_layer(layer):
"""This function will prepare the layer to be used in InaSAFE :
* Make a local copy of the layer.
* Make sure that we have an InaSAFE ID column.
* Rename fields according to our definitions.
* Remove fields which are not used.
:param layer: The layer to prep... | [
"def",
"prepare_vector_layer",
"(",
"layer",
")",
":",
"output_layer_name",
"=",
"prepare_vector_steps",
"[",
"'output_layer_name'",
"]",
"output_layer_name",
"=",
"output_layer_name",
"%",
"layer",
".",
"keywords",
"[",
"'layer_purpose'",
"]",
"if",
"not",
"layer",
... | This function will prepare the layer to be used in InaSAFE :
* Make a local copy of the layer.
* Make sure that we have an InaSAFE ID column.
* Rename fields according to our definitions.
* Remove fields which are not used.
:param layer: The layer to prepare.
:type layer: QgsVectorLayer
... | [
"This",
"function",
"will",
"prepare",
"the",
"layer",
"to",
"be",
"used",
"in",
"InaSAFE",
":",
"*",
"Make",
"a",
"local",
"copy",
"of",
"the",
"layer",
".",
"*",
"Make",
"sure",
"that",
"we",
"have",
"an",
"InaSAFE",
"ID",
"column",
".",
"*",
"Rena... | python | train | 35.338462 |
mgraffg/EvoDAG | EvoDAG/gp.py | https://github.com/mgraffg/EvoDAG/blob/e11fa1fd1ca9e69cca92696c86661a3dc7b3a1d5/EvoDAG/gp.py#L37-L41 | def decision_function(self, X):
"Decision function i.e. the raw data of the prediction"
self._X = Model.convert_features(X)
self._eval()
return self._ind[0].hy | [
"def",
"decision_function",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"_X",
"=",
"Model",
".",
"convert_features",
"(",
"X",
")",
"self",
".",
"_eval",
"(",
")",
"return",
"self",
".",
"_ind",
"[",
"0",
"]",
".",
"hy"
] | Decision function i.e. the raw data of the prediction | [
"Decision",
"function",
"i",
".",
"e",
".",
"the",
"raw",
"data",
"of",
"the",
"prediction"
] | python | train | 37.4 |
exoscale/cs | cs/client.py | https://github.com/exoscale/cs/blob/3a0b05559c1f9f3c5bda34920d4497dfd8b9290a/cs/client.py#L104-L143 | def transform(params):
"""
Transforms an heterogeneous map of params into a CloudStack
ready mapping of parameter to values.
It handles lists and dicts.
>>> p = {"a": 1, "b": "foo", "c": ["eggs", "spam"], "d": {"key": "value"}}
>>> transform(p)
>>> print(p)
{'a': '1', 'b': 'foo', 'c': ... | [
"def",
"transform",
"(",
"params",
")",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"params",
".",
"items",
"(",
")",
")",
":",
"if",
"value",
"is",
"None",
":",
"params",
".",
"pop",
"(",
"key",
")",
"continue",
"if",
"isinstance",
"(",
... | Transforms an heterogeneous map of params into a CloudStack
ready mapping of parameter to values.
It handles lists and dicts.
>>> p = {"a": 1, "b": "foo", "c": ["eggs", "spam"], "d": {"key": "value"}}
>>> transform(p)
>>> print(p)
{'a': '1', 'b': 'foo', 'c': 'eggs,spam', 'd[0].key': 'value'} | [
"Transforms",
"an",
"heterogeneous",
"map",
"of",
"params",
"into",
"a",
"CloudStack",
"ready",
"mapping",
"of",
"parameter",
"to",
"values",
"."
] | python | train | 33.7 |
KelSolaar/Umbra | umbra/ui/input_accelerators.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/input_accelerators.py#L90-L125 | def perform_completion(editor):
"""
Performs the completion on given editor.
:param editor: Document editor.
:type editor: QWidget
:return: Method success.
:rtype: bool
"""
completion_prefix = editor.get_partial_word_under_cursor()
if not completion_prefix:
return
word... | [
"def",
"perform_completion",
"(",
"editor",
")",
":",
"completion_prefix",
"=",
"editor",
".",
"get_partial_word_under_cursor",
"(",
")",
"if",
"not",
"completion_prefix",
":",
"return",
"words",
"=",
"editor",
".",
"get_words",
"(",
")",
"completion_prefix",
"in"... | Performs the completion on given editor.
:param editor: Document editor.
:type editor: QWidget
:return: Method success.
:rtype: bool | [
"Performs",
"the",
"completion",
"on",
"given",
"editor",
"."
] | python | train | 40.805556 |
jasonbot/arcrest | arcrest/server.py | https://github.com/jasonbot/arcrest/blob/b1ba71fd59bb6349415e7879d753d307dbc0da26/arcrest/server.py#L1883-L1887 | def save(self, outfile):
"""Save the image data to a file or file-like object"""
if isinstance(outfile, compat.string_type):
outfile = open(outfile, 'wb')
outfile.write(compat.urllib2.urlopen(self.href).read()) | [
"def",
"save",
"(",
"self",
",",
"outfile",
")",
":",
"if",
"isinstance",
"(",
"outfile",
",",
"compat",
".",
"string_type",
")",
":",
"outfile",
"=",
"open",
"(",
"outfile",
",",
"'wb'",
")",
"outfile",
".",
"write",
"(",
"compat",
".",
"urllib2",
"... | Save the image data to a file or file-like object | [
"Save",
"the",
"image",
"data",
"to",
"a",
"file",
"or",
"file",
"-",
"like",
"object"
] | python | train | 48.4 |
manns/pyspread | pyspread/src/gui/_dialogs.py | https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/gui/_dialogs.py#L979-L999 | def _do_layout(self):
"""Layout sizers"""
label_style = wx.LEFT | wx.ALIGN_CENTER_VERTICAL
button_style = wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | \
wx.ALIGN_CENTER_VERTICAL | wx.FIXED_MINSIZE
grid_sizer_1 = wx.GridSizer(4, 2, 3, 3)
grid_sizer_1.Add(self.R... | [
"def",
"_do_layout",
"(",
"self",
")",
":",
"label_style",
"=",
"wx",
".",
"LEFT",
"|",
"wx",
".",
"ALIGN_CENTER_VERTICAL",
"button_style",
"=",
"wx",
".",
"ALL",
"|",
"wx",
".",
"EXPAND",
"|",
"wx",
".",
"ALIGN_CENTER_HORIZONTAL",
"|",
"wx",
".",
"ALIGN... | Layout sizers | [
"Layout",
"sizers"
] | python | train | 43.285714 |
xtrementl/focus | focus/plugin/modules/sounds.py | https://github.com/xtrementl/focus/blob/cbbbc0b49a7409f9e0dc899de5b7e057f50838e4/focus/plugin/modules/sounds.py#L66-L91 | def _play_sound(self, filename):
""" Shells player with the provided filename.
`filename`
Filename for sound file.
"""
command = self._get_external_player()
if not command:
return # no player found
if common.IS_MACOSX:
c... | [
"def",
"_play_sound",
"(",
"self",
",",
"filename",
")",
":",
"command",
"=",
"self",
".",
"_get_external_player",
"(",
")",
"if",
"not",
"command",
":",
"return",
"# no player found",
"if",
"common",
".",
"IS_MACOSX",
":",
"command",
"+=",
"' \"{0}\"'",
"."... | Shells player with the provided filename.
`filename`
Filename for sound file. | [
"Shells",
"player",
"with",
"the",
"provided",
"filename",
"."
] | python | train | 32.153846 |
benfred/implicit | implicit/als.py | https://github.com/benfred/implicit/blob/6b16c50d1d514a814f2e5b8cf2a829ff23dbba63/implicit/als.py#L311-L322 | def least_squares(Cui, X, Y, regularization, num_threads=0):
""" For each user in Cui, calculate factors Xu for them
using least squares on Y.
Note: this is at least 10 times slower than the cython version included
here.
"""
users, n_factors = X.shape
YtY = Y.T.dot(Y)
for u in range(us... | [
"def",
"least_squares",
"(",
"Cui",
",",
"X",
",",
"Y",
",",
"regularization",
",",
"num_threads",
"=",
"0",
")",
":",
"users",
",",
"n_factors",
"=",
"X",
".",
"shape",
"YtY",
"=",
"Y",
".",
"T",
".",
"dot",
"(",
"Y",
")",
"for",
"u",
"in",
"r... | For each user in Cui, calculate factors Xu for them
using least squares on Y.
Note: this is at least 10 times slower than the cython version included
here. | [
"For",
"each",
"user",
"in",
"Cui",
"calculate",
"factors",
"Xu",
"for",
"them",
"using",
"least",
"squares",
"on",
"Y",
"."
] | python | train | 32 |
awslabs/mxboard | python/mxboard/summary.py | https://github.com/awslabs/mxboard/blob/36057ff0f05325c9dc2fe046521325bf9d563a88/python/mxboard/summary.py#L67-L94 | def _clean_tag(name):
"""Cleans a tag. Removes illegal characters for instance.
Adapted from the TensorFlow function `clean_tag()` at
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/summary_op_util.py
Parameters
----------
name : str
The original tag n... | [
"def",
"_clean_tag",
"(",
"name",
")",
":",
"# In the past, the first argument to summary ops was a tag, which allowed",
"# arbitrary characters. Now we are changing the first argument to be the node",
"# name. This has a number of advantages (users of summary ops now can",
"# take advantage of th... | Cleans a tag. Removes illegal characters for instance.
Adapted from the TensorFlow function `clean_tag()` at
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/summary_op_util.py
Parameters
----------
name : str
The original tag name to be processed.
Ret... | [
"Cleans",
"a",
"tag",
".",
"Removes",
"illegal",
"characters",
"for",
"instance",
".",
"Adapted",
"from",
"the",
"TensorFlow",
"function",
"clean_tag",
"()",
"at",
"https",
":",
"//",
"github",
".",
"com",
"/",
"tensorflow",
"/",
"tensorflow",
"/",
"blob",
... | python | train | 43.464286 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/utils/io.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L306-L311 | def raw_print(*args, **kw):
"""Raw print to sys.__stdout__, otherwise identical interface to print()."""
print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
file=sys.__stdout__)
sys.__stdout__.flush() | [
"def",
"raw_print",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"print",
"(",
"*",
"args",
",",
"sep",
"=",
"kw",
".",
"get",
"(",
"'sep'",
",",
"' '",
")",
",",
"end",
"=",
"kw",
".",
"get",
"(",
"'end'",
",",
"'\\n'",
")",
",",
"file... | Raw print to sys.__stdout__, otherwise identical interface to print(). | [
"Raw",
"print",
"to",
"sys",
".",
"__stdout__",
"otherwise",
"identical",
"interface",
"to",
"print",
"()",
"."
] | python | test | 38 |
bmweiner/skillful | skillful/validate.py | https://github.com/bmweiner/skillful/blob/8646f54faf62cb63f165f7699b8ace5b4a08233c/skillful/validate.py#L220-L258 | def sender(self, body, stamp, url, sig):
"""Validate request is from Alexa.
Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5.
Checking the Signature of the Request: https://goo.gl/FDkjBN.
Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ
Args:
... | [
"def",
"sender",
"(",
"self",
",",
"body",
",",
"stamp",
",",
"url",
",",
"sig",
")",
":",
"if",
"not",
"timestamp",
"(",
"stamp",
")",
":",
"return",
"False",
"if",
"self",
".",
"url",
"!=",
"url",
":",
"if",
"not",
"signature_cert_chain_url",
"(",
... | Validate request is from Alexa.
Verifying that the Request was Sent by Alexa: https://goo.gl/AcrzB5.
Checking the Signature of the Request: https://goo.gl/FDkjBN.
Checking the Timestamp of the Request: https://goo.gl/Z5JhqZ
Args:
body: str. HTTPS request body.
s... | [
"Validate",
"request",
"is",
"from",
"Alexa",
"."
] | python | train | 29.128205 |
VisTrails/tej | tej/submission.py | https://github.com/VisTrails/tej/blob/b8dedaeb6bdeb650b46cfe6d85e5aa9284fc7f0b/tej/submission.py#L286-L293 | def check_output(self, cmd):
"""Calls a command through SSH and returns its output.
"""
ret, output = self._call(cmd, True)
if ret != 0: # pragma: no cover
raise RemoteCommandFailure(command=cmd, ret=ret)
logger.debug("Output: %r", output)
return output | [
"def",
"check_output",
"(",
"self",
",",
"cmd",
")",
":",
"ret",
",",
"output",
"=",
"self",
".",
"_call",
"(",
"cmd",
",",
"True",
")",
"if",
"ret",
"!=",
"0",
":",
"# pragma: no cover",
"raise",
"RemoteCommandFailure",
"(",
"command",
"=",
"cmd",
","... | Calls a command through SSH and returns its output. | [
"Calls",
"a",
"command",
"through",
"SSH",
"and",
"returns",
"its",
"output",
"."
] | python | train | 38.375 |
twisted/mantissa | xmantissa/fulltext.py | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/fulltext.py#L735-L747 | def pyLuceneIndexer4to5(old):
"""
Copy attributes, reset index due because information about deleted
documents has been lost, and power up for IFulltextIndexer so other code
can find this item.
"""
new = old.upgradeVersion(PyLuceneIndexer.typeName, 4, 5,
indexCount=o... | [
"def",
"pyLuceneIndexer4to5",
"(",
"old",
")",
":",
"new",
"=",
"old",
".",
"upgradeVersion",
"(",
"PyLuceneIndexer",
".",
"typeName",
",",
"4",
",",
"5",
",",
"indexCount",
"=",
"old",
".",
"indexCount",
",",
"installedOn",
"=",
"old",
".",
"installedOn",... | Copy attributes, reset index due because information about deleted
documents has been lost, and power up for IFulltextIndexer so other code
can find this item. | [
"Copy",
"attributes",
"reset",
"index",
"due",
"because",
"information",
"about",
"deleted",
"documents",
"has",
"been",
"lost",
"and",
"power",
"up",
"for",
"IFulltextIndexer",
"so",
"other",
"code",
"can",
"find",
"this",
"item",
"."
] | python | train | 40.846154 |
pschmitt/zhue | zhue/model/basemodel.py | https://github.com/pschmitt/zhue/blob/4a3f4ddf12ceeedcb2157f92d93ff1c6438a7d59/zhue/model/basemodel.py#L65-L75 | def address(self):
'''
Return the address of this "object", minus the scheme, hostname
and port of the bridge
'''
return self.API.replace(
'http://{}:{}'.format(
self._bridge.hostname,
self._bridge.port
), ''
) | [
"def",
"address",
"(",
"self",
")",
":",
"return",
"self",
".",
"API",
".",
"replace",
"(",
"'http://{}:{}'",
".",
"format",
"(",
"self",
".",
"_bridge",
".",
"hostname",
",",
"self",
".",
"_bridge",
".",
"port",
")",
",",
"''",
")"
] | Return the address of this "object", minus the scheme, hostname
and port of the bridge | [
"Return",
"the",
"address",
"of",
"this",
"object",
"minus",
"the",
"scheme",
"hostname",
"and",
"port",
"of",
"the",
"bridge"
] | python | train | 27.636364 |
ageitgey/face_recognition | examples/face_recognition_knn.py | https://github.com/ageitgey/face_recognition/blob/c96b010c02f15e8eeb0f71308c641179ac1f19bb/examples/face_recognition_knn.py#L46-L108 | def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False):
"""
Trains a k-nearest neighbors classifier for face recognition.
:param train_dir: directory that contains a sub-directory for each known person, with its name.
(View in source code to see train_dir ex... | [
"def",
"train",
"(",
"train_dir",
",",
"model_save_path",
"=",
"None",
",",
"n_neighbors",
"=",
"None",
",",
"knn_algo",
"=",
"'ball_tree'",
",",
"verbose",
"=",
"False",
")",
":",
"X",
"=",
"[",
"]",
"y",
"=",
"[",
"]",
"# Loop through each person in the ... | Trains a k-nearest neighbors classifier for face recognition.
:param train_dir: directory that contains a sub-directory for each known person, with its name.
(View in source code to see train_dir example tree structure)
Structure:
<train_dir>/
├── <person1>/
│ ├── <somename1>.... | [
"Trains",
"a",
"k",
"-",
"nearest",
"neighbors",
"classifier",
"for",
"face",
"recognition",
"."
] | python | train | 41.396825 |
python-rope/rope | rope/refactor/change_signature.py | https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/refactor/change_signature.py#L126-L141 | def get_changes(self, changers, in_hierarchy=False, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Get changes caused by this refactoring
`changers` is a list of `_ArgumentChanger`\s. If `in_hierarchy`
is `True` the changers are applyed to all matching methods... | [
"def",
"get_changes",
"(",
"self",
",",
"changers",
",",
"in_hierarchy",
"=",
"False",
",",
"resources",
"=",
"None",
",",
"task_handle",
"=",
"taskhandle",
".",
"NullTaskHandle",
"(",
")",
")",
":",
"function_changer",
"=",
"_FunctionChangers",
"(",
"self",
... | Get changes caused by this refactoring
`changers` is a list of `_ArgumentChanger`\s. If `in_hierarchy`
is `True` the changers are applyed to all matching methods in
the class hierarchy.
`resources` can be a list of `rope.base.resource.File`\s that
should be searched for occurre... | [
"Get",
"changes",
"caused",
"by",
"this",
"refactoring"
] | python | train | 49.6875 |
PSPC-SPAC-buyandsell/von_anchor | von_anchor/nodepool/nodepool.py | https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/nodepool/nodepool.py#L140-L169 | async def open(self) -> 'NodePool':
"""
Explicit entry. Opens pool as configured, for later closure via close().
Creates pool if it does not yet exist, using configured genesis transaction file.
For use when keeping pool open across multiple calls.
Raise any AbsentPool if node p... | [
"async",
"def",
"open",
"(",
"self",
")",
"->",
"'NodePool'",
":",
"LOGGER",
".",
"debug",
"(",
"'NodePool.open >>>'",
")",
"await",
"pool",
".",
"set_protocol_version",
"(",
"self",
".",
"protocol",
".",
"indy",
"(",
")",
")",
"LOGGER",
".",
"info",
"("... | Explicit entry. Opens pool as configured, for later closure via close().
Creates pool if it does not yet exist, using configured genesis transaction file.
For use when keeping pool open across multiple calls.
Raise any AbsentPool if node pool ledger configuration is not available.
:ret... | [
"Explicit",
"entry",
".",
"Opens",
"pool",
"as",
"configured",
"for",
"later",
"closure",
"via",
"close",
"()",
".",
"Creates",
"pool",
"if",
"it",
"does",
"not",
"yet",
"exist",
"using",
"configured",
"genesis",
"transaction",
"file",
".",
"For",
"use",
"... | python | train | 40.866667 |
saltstack/salt | salt/modules/mac_group.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_group.py#L75-L88 | def _list_gids():
'''
Return a list of gids in use
'''
output = __salt__['cmd.run'](
['dscacheutil', '-q', 'group'],
output_loglevel='quiet',
python_shell=False
)
ret = set()
for line in salt.utils.itertools.split(output, '\n'):
if line.startswith('gid:'):
... | [
"def",
"_list_gids",
"(",
")",
":",
"output",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"[",
"'dscacheutil'",
",",
"'-q'",
",",
"'group'",
"]",
",",
"output_loglevel",
"=",
"'quiet'",
",",
"python_shell",
"=",
"False",
")",
"ret",
"=",
"set",
"(",
"... | Return a list of gids in use | [
"Return",
"a",
"list",
"of",
"gids",
"in",
"use"
] | python | train | 26.214286 |
pycontribs/pyrax | pyrax/cloudloadbalancers.py | https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/cloudloadbalancers.py#L1491-L1498 | def update_ssl_termination(self, loadbalancer, securePort=None, enabled=None,
secureTrafficOnly=None):
"""
Updates existing SSL termination information for the load balancer
without affecting the existing certificates/keys.
"""
return loadbalancer.update_ssl_terminati... | [
"def",
"update_ssl_termination",
"(",
"self",
",",
"loadbalancer",
",",
"securePort",
"=",
"None",
",",
"enabled",
"=",
"None",
",",
"secureTrafficOnly",
"=",
"None",
")",
":",
"return",
"loadbalancer",
".",
"update_ssl_termination",
"(",
"securePort",
"=",
"sec... | Updates existing SSL termination information for the load balancer
without affecting the existing certificates/keys. | [
"Updates",
"existing",
"SSL",
"termination",
"information",
"for",
"the",
"load",
"balancer",
"without",
"affecting",
"the",
"existing",
"certificates",
"/",
"keys",
"."
] | python | train | 51 |
MaxHalford/prince | prince/mca.py | https://github.com/MaxHalford/prince/blob/714c9cdfc4d9f8823eabf550a23ad01fe87c50d7/prince/mca.py#L42-L47 | def transform(self, X):
"""Computes the row principal coordinates of a dataset."""
utils.validation.check_is_fitted(self, 's_')
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
return self.row_coordinates(X) | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"utils",
".",
"validation",
".",
"check_is_fitted",
"(",
"self",
",",
"'s_'",
")",
"if",
"self",
".",
"check_input",
":",
"utils",
".",
"check_array",
"(",
"X",
",",
"dtype",
"=",
"[",
"str",
",",
... | Computes the row principal coordinates of a dataset. | [
"Computes",
"the",
"row",
"principal",
"coordinates",
"of",
"a",
"dataset",
"."
] | python | train | 43.833333 |
jaraco/jaraco.functools | jaraco/functools.py | https://github.com/jaraco/jaraco.functools/blob/cc972095e5aa2ae80d1d69d7ca84ee94178e869a/jaraco/functools.py#L354-L367 | def print_yielded(func):
"""
Convert a generator into a function that prints all yielded elements
>>> @print_yielded
... def x():
... yield 3; yield None
>>> x()
3
None
"""
print_all = functools.partial(map, print)
print_results = compose(more_itertools.recipes.consume, print_all, func)
return functool... | [
"def",
"print_yielded",
"(",
"func",
")",
":",
"print_all",
"=",
"functools",
".",
"partial",
"(",
"map",
",",
"print",
")",
"print_results",
"=",
"compose",
"(",
"more_itertools",
".",
"recipes",
".",
"consume",
",",
"print_all",
",",
"func",
")",
"return... | Convert a generator into a function that prints all yielded elements
>>> @print_yielded
... def x():
... yield 3; yield None
>>> x()
3
None | [
"Convert",
"a",
"generator",
"into",
"a",
"function",
"that",
"prints",
"all",
"yielded",
"elements"
] | python | train | 23.928571 |
moonso/vcftoolbox | vcftoolbox/parse_variant.py | https://github.com/moonso/vcftoolbox/blob/438fb1d85a83812c389774b94802eb5921c89e3a/vcftoolbox/parse_variant.py#L57-L88 | def get_variant_id(variant_dict=None, variant_line=None):
"""Build a variant id
The variant id is a string made of CHROM_POS_REF_ALT
Args:
variant_dict (dict): A variant dictionary
Returns:
variant_id (str)
"""
if variant_dict:
... | [
"def",
"get_variant_id",
"(",
"variant_dict",
"=",
"None",
",",
"variant_line",
"=",
"None",
")",
":",
"if",
"variant_dict",
":",
"chrom",
"=",
"variant_dict",
"[",
"'CHROM'",
"]",
"position",
"=",
"variant_dict",
"[",
"'POS'",
"]",
"ref",
"=",
"variant_dict... | Build a variant id
The variant id is a string made of CHROM_POS_REF_ALT
Args:
variant_dict (dict): A variant dictionary
Returns:
variant_id (str) | [
"Build",
"a",
"variant",
"id",
"The",
"variant",
"id",
"is",
"a",
"string",
"made",
"of",
"CHROM_POS_REF_ALT",
"Args",
":",
"variant_dict",
"(",
"dict",
")",
":",
"A",
"variant",
"dictionary",
"Returns",
":",
"variant_id",
"(",
"str",
")"
] | python | train | 25.5 |
gem/oq-engine | openquake/hazardlib/gsim/allen_2012.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/allen_2012.py#L122-L132 | def _get_stddevs(self, C, stddev_types, num_sites):
"""
Return total standard deviation.
"""
# standard deviation is converted from log10 to ln
std_total = np.log(10 ** C['sigma'])
stddevs = []
for _ in stddev_types:
stddevs.append(np.zeros(num_sites) ... | [
"def",
"_get_stddevs",
"(",
"self",
",",
"C",
",",
"stddev_types",
",",
"num_sites",
")",
":",
"# standard deviation is converted from log10 to ln",
"std_total",
"=",
"np",
".",
"log",
"(",
"10",
"**",
"C",
"[",
"'sigma'",
"]",
")",
"stddevs",
"=",
"[",
"]",... | Return total standard deviation. | [
"Return",
"total",
"standard",
"deviation",
"."
] | python | train | 31.454545 |
gorakhargosh/pathtools | pathtools/patterns.py | https://github.com/gorakhargosh/pathtools/blob/a3522fc61b00ee2d992ca375c600513bfb9020e9/pathtools/patterns.py#L98-L128 | def _match_path(pathname,
included_patterns,
excluded_patterns,
case_sensitive=True):
"""Internal function same as :func:`match_path` but does not check arguments.
Doctests::
>>> _match_path("/users/gorakhargosh/foobar.py", ["*.py"], ["*.PY"], True)
... | [
"def",
"_match_path",
"(",
"pathname",
",",
"included_patterns",
",",
"excluded_patterns",
",",
"case_sensitive",
"=",
"True",
")",
":",
"if",
"not",
"case_sensitive",
":",
"included_patterns",
"=",
"set",
"(",
"map",
"(",
"_string_lower",
",",
"included_patterns"... | Internal function same as :func:`match_path` but does not check arguments.
Doctests::
>>> _match_path("/users/gorakhargosh/foobar.py", ["*.py"], ["*.PY"], True)
True
>>> _match_path("/users/gorakhargosh/FOOBAR.PY", ["*.py"], ["*.PY"], True)
False
>>> _match_path("/users/gora... | [
"Internal",
"function",
"same",
"as",
":",
"func",
":",
"match_path",
"but",
"does",
"not",
"check",
"arguments",
"."
] | python | train | 45.387097 |
cvxopt/chompack | src/python/symbolic.py | https://github.com/cvxopt/chompack/blob/e07106b58b8055c34f6201e8c954482f86987833/src/python/symbolic.py#L1032-L1111 | def spmatrix(self, reordered = True, symmetric = False):
"""
Converts the :py:class:`cspmatrix` :math:`A` to a sparse matrix. A reordered
matrix is returned if the optional argument `reordered` is
`True` (default), and otherwise the inverse permutation is applied. Only the
defaul... | [
"def",
"spmatrix",
"(",
"self",
",",
"reordered",
"=",
"True",
",",
"symmetric",
"=",
"False",
")",
":",
"n",
"=",
"self",
".",
"symb",
".",
"n",
"snptr",
"=",
"self",
".",
"symb",
".",
"snptr",
"snode",
"=",
"self",
".",
"symb",
".",
"snode",
"r... | Converts the :py:class:`cspmatrix` :math:`A` to a sparse matrix. A reordered
matrix is returned if the optional argument `reordered` is
`True` (default), and otherwise the inverse permutation is applied. Only the
default options are allowed if the :py:class:`cspmatrix` :math:`A` represents
... | [
"Converts",
"the",
":",
"py",
":",
"class",
":",
"cspmatrix",
":",
"math",
":",
"A",
"to",
"a",
"sparse",
"matrix",
".",
"A",
"reordered",
"matrix",
"is",
"returned",
"if",
"the",
"optional",
"argument",
"reordered",
"is",
"True",
"(",
"default",
")",
... | python | train | 40.0125 |
pmacosta/peng | docs/support/incfile.py | https://github.com/pmacosta/peng/blob/976935377adaa3de26fc5677aceb2cdfbd6f93a7/docs/support/incfile.py#L9-L84 | def incfile(fname, fpointer, lrange="1,6-", sdir=None):
r"""
Include a Python source file in a docstring formatted in reStructuredText.
:param fname: File name, relative to environment variable
:bash:`${TRACER_DIR}`
:type fname: string
:param fpointer: Output function pointer. N... | [
"def",
"incfile",
"(",
"fname",
",",
"fpointer",
",",
"lrange",
"=",
"\"1,6-\"",
",",
"sdir",
"=",
"None",
")",
":",
"# Read file",
"file_dir",
"=",
"(",
"sdir",
"if",
"sdir",
"else",
"os",
".",
"environ",
".",
"get",
"(",
"\"TRACER_DIR\"",
",",
"os",
... | r"""
Include a Python source file in a docstring formatted in reStructuredText.
:param fname: File name, relative to environment variable
:bash:`${TRACER_DIR}`
:type fname: string
:param fpointer: Output function pointer. Normally is :code:`cog.out` but
:code:`p... | [
"r",
"Include",
"a",
"Python",
"source",
"file",
"in",
"a",
"docstring",
"formatted",
"in",
"reStructuredText",
"."
] | python | test | 32.315789 |
wglass/lighthouse | lighthouse/zookeeper.py | https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/zookeeper.py#L109-L126 | def handle_connection_change(self, state):
"""
Callback for handling changes in the kazoo client's connection state.
If the connection becomes lost or suspended, the `connected` Event
is cleared. Other given states imply that the connection is
established so `connected` is set.... | [
"def",
"handle_connection_change",
"(",
"self",
",",
"state",
")",
":",
"if",
"state",
"==",
"client",
".",
"KazooState",
".",
"LOST",
":",
"if",
"not",
"self",
".",
"shutdown",
".",
"is_set",
"(",
")",
":",
"logger",
".",
"info",
"(",
"\"Zookeeper sessi... | Callback for handling changes in the kazoo client's connection state.
If the connection becomes lost or suspended, the `connected` Event
is cleared. Other given states imply that the connection is
established so `connected` is set. | [
"Callback",
"for",
"handling",
"changes",
"in",
"the",
"kazoo",
"client",
"s",
"connection",
"state",
"."
] | python | train | 41.611111 |
annoviko/pyclustering | pyclustering/cluster/clarans.py | https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/clarans.py#L137-L160 | def __update_clusters(self, medoids):
"""!
@brief Forms cluster in line with specified medoids by calculation distance from each point to medoids.
"""
self.__belong = [0] * len(self.__pointer_data)
self.__clusters = [[] for i in range(len(medoids))]
... | [
"def",
"__update_clusters",
"(",
"self",
",",
"medoids",
")",
":",
"self",
".",
"__belong",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"self",
".",
"__pointer_data",
")",
"self",
".",
"__clusters",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len... | !
@brief Forms cluster in line with specified medoids by calculation distance from each point to medoids. | [
"!"
] | python | valid | 43.375 |
oasiswork/zimsoap | zimsoap/client.py | https://github.com/oasiswork/zimsoap/blob/d1ea2eb4d50f263c9a16e5549af03f1eff3e295e/zimsoap/client.py#L1043-L1051 | def get_account(self, account):
""" Fetches an account with all its attributes.
:param account: an account object, with either id or name attribute set
:returns: a zobjects.Account object, filled.
"""
selector = account.to_selector()
resp = self.request_single('GetAccoun... | [
"def",
"get_account",
"(",
"self",
",",
"account",
")",
":",
"selector",
"=",
"account",
".",
"to_selector",
"(",
")",
"resp",
"=",
"self",
".",
"request_single",
"(",
"'GetAccount'",
",",
"{",
"'account'",
":",
"selector",
"}",
")",
"return",
"zobjects",
... | Fetches an account with all its attributes.
:param account: an account object, with either id or name attribute set
:returns: a zobjects.Account object, filled. | [
"Fetches",
"an",
"account",
"with",
"all",
"its",
"attributes",
"."
] | python | train | 42.888889 |
graphql-python/graphql-core | graphql/execution/values.py | https://github.com/graphql-python/graphql-core/blob/d8e9d3abe7c209eb2f51cf001402783bfd480596/graphql/execution/values.py#L151-L186 | def coerce_value(type, value):
# type: (Any, Any) -> Union[List, Dict, int, float, bool, str, None]
"""Given a type and any value, return a runtime value coerced to match the type."""
if isinstance(type, GraphQLNonNull):
# Note: we're not checking that the result of coerceValue is
# non-null... | [
"def",
"coerce_value",
"(",
"type",
",",
"value",
")",
":",
"# type: (Any, Any) -> Union[List, Dict, int, float, bool, str, None]",
"if",
"isinstance",
"(",
"type",
",",
"GraphQLNonNull",
")",
":",
"# Note: we're not checking that the result of coerceValue is",
"# non-null.",
"... | Given a type and any value, return a runtime value coerced to match the type. | [
"Given",
"a",
"type",
"and",
"any",
"value",
"return",
"a",
"runtime",
"value",
"coerced",
"to",
"match",
"the",
"type",
"."
] | python | train | 39.361111 |
pydata/xarray | xarray/backends/api.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/backends/api.py#L541-L727 | def open_mfdataset(paths, chunks=None, concat_dim=_CONCAT_DIM_DEFAULT,
compat='no_conflicts', preprocess=None, engine=None,
lock=None, data_vars='all', coords='different',
autoclose=None, parallel=False, **kwargs):
"""Open multiple files as a single dataset.
... | [
"def",
"open_mfdataset",
"(",
"paths",
",",
"chunks",
"=",
"None",
",",
"concat_dim",
"=",
"_CONCAT_DIM_DEFAULT",
",",
"compat",
"=",
"'no_conflicts'",
",",
"preprocess",
"=",
"None",
",",
"engine",
"=",
"None",
",",
"lock",
"=",
"None",
",",
"data_vars",
... | Open multiple files as a single dataset.
Requires dask to be installed. See documentation for details on dask [1].
Attributes from the first dataset file are used for the combined dataset.
Parameters
----------
paths : str or sequence
Either a string glob in the form "path/to/my/files/*.nc... | [
"Open",
"multiple",
"files",
"as",
"a",
"single",
"dataset",
"."
] | python | train | 44.55615 |
ronhanson/python-tbx | tbx/process.py | https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/process.py#L38-L51 | def synchronized(lock):
"""
Synchronization decorator; provide thread-safe locking on a function
http://code.activestate.com/recipes/465057/
"""
def wrap(f):
def synchronize(*args, **kw):
lock.acquire()
try:
return f(*args, **kw)
finally:
... | [
"def",
"synchronized",
"(",
"lock",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"def",
"synchronize",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"return",
"f",
"(",
"*",
"args",
",",
"*",
"... | Synchronization decorator; provide thread-safe locking on a function
http://code.activestate.com/recipes/465057/ | [
"Synchronization",
"decorator",
";",
"provide",
"thread",
"-",
"safe",
"locking",
"on",
"a",
"function",
"http",
":",
"//",
"code",
".",
"activestate",
".",
"com",
"/",
"recipes",
"/",
"465057",
"/"
] | python | train | 27.071429 |
inspirehep/harvesting-kit | harvestingkit/ftp_utils.py | https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L207-L227 | def rm(self, filename):
""" Delete a file from the server.
:param filename: the file to be deleted.
:type filename: string
"""
try:
self._ftp.delete(filename)
except error_perm: # target is either a directory
# either it does not ... | [
"def",
"rm",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"self",
".",
"_ftp",
".",
"delete",
"(",
"filename",
")",
"except",
"error_perm",
":",
"# target is either a directory",
"# either it does not exist",
"try",
":",
"current_folder",
"=",
"self",
"... | Delete a file from the server.
:param filename: the file to be deleted.
:type filename: string | [
"Delete",
"a",
"file",
"from",
"the",
"server",
"."
] | python | valid | 36.714286 |
mdgoldberg/sportsref | sportsref/nba/teams.py | https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nba/teams.py#L67-L76 | def schedule(self, year):
"""Gets schedule information for a team-season.
:year: The year for which we want the schedule.
:returns: DataFrame of schedule information.
"""
doc = self.get_year_doc('{}_games'.format(year))
table = doc('table#games')
df = sportsref.u... | [
"def",
"schedule",
"(",
"self",
",",
"year",
")",
":",
"doc",
"=",
"self",
".",
"get_year_doc",
"(",
"'{}_games'",
".",
"format",
"(",
"year",
")",
")",
"table",
"=",
"doc",
"(",
"'table#games'",
")",
"df",
"=",
"sportsref",
".",
"utils",
".",
"parse... | Gets schedule information for a team-season.
:year: The year for which we want the schedule.
:returns: DataFrame of schedule information. | [
"Gets",
"schedule",
"information",
"for",
"a",
"team",
"-",
"season",
"."
] | python | test | 35.2 |
thomasdelaet/python-velbus | velbus/messages/set_date.py | https://github.com/thomasdelaet/python-velbus/blob/af2f8af43f1a24bf854eff9f3126fd7b5c41b3dd/velbus/messages/set_date.py#L35-L46 | def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 4)
self.set_attributes(priority, address, rtr)
self._day = data[0]... | [
"def",
"populate",
"(",
"self",
",",
"priority",
",",
"address",
",",
"rtr",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"needs_low_priority",
"(",
"priority",
")",
"self",
".",
"needs_no_rtr",
"(",
"rtr",
... | :return: None | [
":",
"return",
":",
"None"
] | python | train | 32.083333 |
apache/incubator-heron | third_party/python/cpplint/cpplint.py | https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L3853-L3873 | def GetPreviousNonBlankLine(clean_lines, linenum):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents ... | [
"def",
"GetPreviousNonBlankLine",
"(",
"clean_lines",
",",
"linenum",
")",
":",
"prevlinenum",
"=",
"linenum",
"-",
"1",
"while",
"prevlinenum",
">=",
"0",
":",
"prevline",
"=",
"clean_lines",
".",
"elided",
"[",
"prevlinenum",
"]",
"if",
"not",
"IsBlankLine",... | Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, ... | [
"Return",
"the",
"most",
"recent",
"non",
"-",
"blank",
"line",
"and",
"its",
"line",
"number",
"."
] | python | valid | 35.952381 |
tlevine/vlermv | vlermv/_abstract.py | https://github.com/tlevine/vlermv/blob/0b332ea1c20e4065b30f5e3ec0c1d0fffbce6b20/vlermv/_abstract.py#L18-L51 | def memoize(Class, *args, **kwargs):
'''
Memoize/record a function inside this vlermv. ::
@Vlermv.cache('~/.http')
def get(url):
return requests.get(url, auth = ('username', 'password'))
The args and kwargs get passed to the Vlermv with some slight chang... | [
"def",
"memoize",
"(",
"Class",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"if",
"hasattr",
"(",
"func",
",",
"'__name__'",
")",
":",
"_args",
"... | Memoize/record a function inside this vlermv. ::
@Vlermv.cache('~/.http')
def get(url):
return requests.get(url, auth = ('username', 'password'))
The args and kwargs get passed to the Vlermv with some slight changes.
Here are the changes.
First, the def... | [
"Memoize",
"/",
"record",
"a",
"function",
"inside",
"this",
"vlermv",
".",
"::"
] | python | train | 39 |
CivicSpleen/ambry | ambry/run.py | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/run.py#L332-L414 | def normalize_dsn_or_dict(d):
"""Clean up a database DSN, or dict version of a DSN, returning both the cleaned DSN and dict version"""
if isinstance(d, dict):
try:
# Convert from an AttrDict to a real dict
d = d.to_dict()
except AttributeError:
pass # Alread... | [
"def",
"normalize_dsn_or_dict",
"(",
"d",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"dict",
")",
":",
"try",
":",
"# Convert from an AttrDict to a real dict",
"d",
"=",
"d",
".",
"to_dict",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"# Already a rea... | Clean up a database DSN, or dict version of a DSN, returning both the cleaned DSN and dict version | [
"Clean",
"up",
"a",
"database",
"DSN",
"or",
"dict",
"version",
"of",
"a",
"DSN",
"returning",
"both",
"the",
"cleaned",
"DSN",
"and",
"dict",
"version"
] | python | train | 29.120482 |
synw/gencharts | gencharts/__init__.py | https://github.com/synw/gencharts/blob/fa35604a9445b399bb4f91bc91af488e8e8208fd/gencharts/__init__.py#L155-L177 | def _chart_class(self, df, chart_type, **kwargs):
"""
Get the right chart class from a string
"""
if chart_type == "bar":
return Chart(df).mark_bar(**kwargs)
elif chart_type == "circle":
return Chart(df).mark_circle(**kwargs)
elif chart_type == "li... | [
"def",
"_chart_class",
"(",
"self",
",",
"df",
",",
"chart_type",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"chart_type",
"==",
"\"bar\"",
":",
"return",
"Chart",
"(",
"df",
")",
".",
"mark_bar",
"(",
"*",
"*",
"kwargs",
")",
"elif",
"chart_type",
"==... | Get the right chart class from a string | [
"Get",
"the",
"right",
"chart",
"class",
"from",
"a",
"string"
] | python | test | 38.304348 |
pandas-dev/pandas | pandas/core/indexing.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/indexing.py#L270-L295 | def _has_valid_positional_setitem_indexer(self, indexer):
""" validate that an positional indexer cannot enlarge its target
will raise if needed, does not modify the indexer externally
"""
if isinstance(indexer, dict):
raise IndexError("{0} cannot enlarge its target object"
... | [
"def",
"_has_valid_positional_setitem_indexer",
"(",
"self",
",",
"indexer",
")",
":",
"if",
"isinstance",
"(",
"indexer",
",",
"dict",
")",
":",
"raise",
"IndexError",
"(",
"\"{0} cannot enlarge its target object\"",
".",
"format",
"(",
"self",
".",
"name",
")",
... | validate that an positional indexer cannot enlarge its target
will raise if needed, does not modify the indexer externally | [
"validate",
"that",
"an",
"positional",
"indexer",
"cannot",
"enlarge",
"its",
"target",
"will",
"raise",
"if",
"needed",
"does",
"not",
"modify",
"the",
"indexer",
"externally"
] | python | train | 45.038462 |
wimglenn/wimpy | wimpy/util.py | https://github.com/wimglenn/wimpy/blob/4e8ebe4e7052d88c9f88ac7dcaa1b587cc2cf86e/wimpy/util.py#L61-L68 | def strip_suffix(s, suffix, strict=False):
"""Removes the suffix, if it's there, otherwise returns input string unchanged.
If strict is True, also ensures the suffix was present"""
if s.endswith(suffix):
return s[: len(s) - len(suffix)]
elif strict:
raise WimpyError("string doesn't end w... | [
"def",
"strip_suffix",
"(",
"s",
",",
"suffix",
",",
"strict",
"=",
"False",
")",
":",
"if",
"s",
".",
"endswith",
"(",
"suffix",
")",
":",
"return",
"s",
"[",
":",
"len",
"(",
"s",
")",
"-",
"len",
"(",
"suffix",
")",
"]",
"elif",
"strict",
":... | Removes the suffix, if it's there, otherwise returns input string unchanged.
If strict is True, also ensures the suffix was present | [
"Removes",
"the",
"suffix",
"if",
"it",
"s",
"there",
"otherwise",
"returns",
"input",
"string",
"unchanged",
".",
"If",
"strict",
"is",
"True",
"also",
"ensures",
"the",
"suffix",
"was",
"present"
] | python | test | 42.25 |
wummel/linkchecker | linkcheck/logger/dot.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/dot.py#L70-L78 | def write_edge (self, node):
"""Write edge from parent to node."""
source = dotquote(self.nodes[node["parent_url"]]["label"])
target = dotquote(node["label"])
self.writeln(u' "%s" -> "%s" [' % (source, target))
self.writeln(u' label="%s",' % dotquote(node["edge"]))
if... | [
"def",
"write_edge",
"(",
"self",
",",
"node",
")",
":",
"source",
"=",
"dotquote",
"(",
"self",
".",
"nodes",
"[",
"node",
"[",
"\"parent_url\"",
"]",
"]",
"[",
"\"label\"",
"]",
")",
"target",
"=",
"dotquote",
"(",
"node",
"[",
"\"label\"",
"]",
")... | Write edge from parent to node. | [
"Write",
"edge",
"from",
"parent",
"to",
"node",
"."
] | python | train | 47.333333 |
slok/prometheus-python | prometheus/formats.py | https://github.com/slok/prometheus-python/blob/51c6de3cdcd4e36eae6e1643b136f486b57a18cd/prometheus/formats.py#L291-L304 | def marshall(self, registry):
"""Returns bytes"""
result = b""
for i in registry.get_all():
# Each message needs to be prefixed with a varint with the size of
# the message (MetrycType)
# https://github.com/matttproud/golang_protobuf_extensions/blob/master/ex... | [
"def",
"marshall",
"(",
"self",
",",
"registry",
")",
":",
"result",
"=",
"b\"\"",
"for",
"i",
"in",
"registry",
".",
"get_all",
"(",
")",
":",
"# Each message needs to be prefixed with a varint with the size of",
"# the message (MetrycType)",
"# https://github.com/matttp... | Returns bytes | [
"Returns",
"bytes"
] | python | train | 42 |
CyberReboot/vent | vent/menus/backup.py | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/backup.py#L30-L43 | def on_ok(self):
""" Perform restoration on the backup file selected """
if self.dir_select.value:
npyscreen.notify_wait('In the process of restoring',
title='Restoring...')
status = self.restore(self.dirs[self.dir_select.value[0]])
i... | [
"def",
"on_ok",
"(",
"self",
")",
":",
"if",
"self",
".",
"dir_select",
".",
"value",
":",
"npyscreen",
".",
"notify_wait",
"(",
"'In the process of restoring'",
",",
"title",
"=",
"'Restoring...'",
")",
"status",
"=",
"self",
".",
"restore",
"(",
"self",
... | Perform restoration on the backup file selected | [
"Perform",
"restoration",
"on",
"the",
"backup",
"file",
"selected"
] | python | train | 44.142857 |
solvebio/solvebio-python | solvebio/contrib/vcf_parser/vcf_parser.py | https://github.com/solvebio/solvebio-python/blob/b29614643043afd19c1d8074e8f25c6700d51a73/solvebio/contrib/vcf_parser/vcf_parser.py#L140-L167 | def _parse_info_snpeff(self, info):
"""
Specialized INFO field parser for SnpEff ANN fields.
Requires self._snpeff_ann_fields to be set.
"""
ann = info.pop('ANN', []) or []
# Overwrite the existing ANN with something parsed
# Split on '|', merge with the ANN keys ... | [
"def",
"_parse_info_snpeff",
"(",
"self",
",",
"info",
")",
":",
"ann",
"=",
"info",
".",
"pop",
"(",
"'ANN'",
",",
"[",
"]",
")",
"or",
"[",
"]",
"# Overwrite the existing ANN with something parsed",
"# Split on '|', merge with the ANN keys parsed above.",
"# Ensure ... | Specialized INFO field parser for SnpEff ANN fields.
Requires self._snpeff_ann_fields to be set. | [
"Specialized",
"INFO",
"field",
"parser",
"for",
"SnpEff",
"ANN",
"fields",
".",
"Requires",
"self",
".",
"_snpeff_ann_fields",
"to",
"be",
"set",
"."
] | python | test | 34.964286 |
tanghaibao/goatools | goatools/cli/gosubdag_plot.py | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/cli/gosubdag_plot.py#L270-L275 | def get_docargs(self, args=None, prt=None):
"""Pare down docopt. Return a minimal dictionary and a set containing runtime arg values."""
# docargs = self.objdoc.get_docargs(args, exp_letters=set(['o', 't', 'p', 'c']))
docargs = self.objdoc.get_docargs(args, prt)
self._chk_docopts(docargs... | [
"def",
"get_docargs",
"(",
"self",
",",
"args",
"=",
"None",
",",
"prt",
"=",
"None",
")",
":",
"# docargs = self.objdoc.get_docargs(args, exp_letters=set(['o', 't', 'p', 'c']))",
"docargs",
"=",
"self",
".",
"objdoc",
".",
"get_docargs",
"(",
"args",
",",
"prt",
... | Pare down docopt. Return a minimal dictionary and a set containing runtime arg values. | [
"Pare",
"down",
"docopt",
".",
"Return",
"a",
"minimal",
"dictionary",
"and",
"a",
"set",
"containing",
"runtime",
"arg",
"values",
"."
] | python | train | 56.5 |
KelSolaar/Umbra | umbra/components/factory/script_editor/script_editor.py | https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/script_editor.py#L3668-L3684 | def evaluate_script(self):
"""
Evaluates current **Script_Editor_tabWidget** Widget tab Model editor content
into the interactive console.
:return: Method success.
:rtype: bool
"""
editor = self.get_current_editor()
if not editor:
return Fals... | [
"def",
"evaluate_script",
"(",
"self",
")",
":",
"editor",
"=",
"self",
".",
"get_current_editor",
"(",
")",
"if",
"not",
"editor",
":",
"return",
"False",
"LOGGER",
".",
"debug",
"(",
"\"> Evaluating 'Script Editor' content.\"",
")",
"if",
"self",
".",
"evalu... | Evaluates current **Script_Editor_tabWidget** Widget tab Model editor content
into the interactive console.
:return: Method success.
:rtype: bool | [
"Evaluates",
"current",
"**",
"Script_Editor_tabWidget",
"**",
"Widget",
"tab",
"Model",
"editor",
"content",
"into",
"the",
"interactive",
"console",
"."
] | python | train | 30.588235 |
sananth12/ImageScraper | image_scraper/utils.py | https://github.com/sananth12/ImageScraper/blob/04cdefaa184420637d02b5a285cf407bbd428929/image_scraper/utils.py#L36-L99 | def get_arguments(self):
""" Gets the arguments from the command line. """
parser = argparse.ArgumentParser(
description='Downloads images from given URL')
parser.add_argument('url2scrape', nargs=1, help="URL to scrape")
parser.add_argument('-m', '--max-images', type=int, de... | [
"def",
"get_arguments",
"(",
"self",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Downloads images from given URL'",
")",
"parser",
".",
"add_argument",
"(",
"'url2scrape'",
",",
"nargs",
"=",
"1",
",",
"help",
"=",
"\... | Gets the arguments from the command line. | [
"Gets",
"the",
"arguments",
"from",
"the",
"command",
"line",
"."
] | python | train | 54.234375 |
spyder-ide/spyder | spyder/widgets/mixins.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/mixins.py#L343-L353 | def set_eol_chars(self, text):
"""Set widget end-of-line (EOL) characters from text (analyzes text)"""
if not is_text_string(text): # testing for QString (PyQt API#1)
text = to_text_string(text)
eol_chars = sourcecode.get_eol_chars(text)
is_document_modified = eol_chars ... | [
"def",
"set_eol_chars",
"(",
"self",
",",
"text",
")",
":",
"if",
"not",
"is_text_string",
"(",
"text",
")",
":",
"# testing for QString (PyQt API#1)\r",
"text",
"=",
"to_text_string",
"(",
"text",
")",
"eol_chars",
"=",
"sourcecode",
".",
"get_eol_chars",
"(",
... | Set widget end-of-line (EOL) characters from text (analyzes text) | [
"Set",
"widget",
"end",
"-",
"of",
"-",
"line",
"(",
"EOL",
")",
"characters",
"from",
"text",
"(",
"analyzes",
"text",
")"
] | python | train | 53.181818 |
gmr/rejected | rejected/log.py | https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/log.py#L36-L47 | def filter(self, record):
"""Is the specified record to be logged? Returns zero for no,
nonzero for yes. If deemed appropriate, the record may be modified
in-place by this method.
:param logging.LogRecord record: The log record to process
:rtype: int
"""
if self... | [
"def",
"filter",
"(",
"self",
",",
"record",
")",
":",
"if",
"self",
".",
"_exists",
":",
"return",
"int",
"(",
"getattr",
"(",
"record",
",",
"'correlation_id'",
",",
"None",
")",
"is",
"not",
"None",
")",
"return",
"int",
"(",
"getattr",
"(",
"reco... | Is the specified record to be logged? Returns zero for no,
nonzero for yes. If deemed appropriate, the record may be modified
in-place by this method.
:param logging.LogRecord record: The log record to process
:rtype: int | [
"Is",
"the",
"specified",
"record",
"to",
"be",
"logged?",
"Returns",
"zero",
"for",
"no",
"nonzero",
"for",
"yes",
".",
"If",
"deemed",
"appropriate",
"the",
"record",
"may",
"be",
"modified",
"in",
"-",
"place",
"by",
"this",
"method",
"."
] | python | train | 38.5 |
pgjones/quart | quart/datastructures.py | https://github.com/pgjones/quart/blob/7cb2d3bd98e8746025764f2b933abc12041fa175/quart/datastructures.py#L136-L152 | def save(self, destination: BinaryIO, buffer_size: int=16384) -> None:
"""Save the file to the destination.
Arguments:
destination: A filename (str) or file object to write to.
buffer_size: Buffer size as used as length in
:func:`shutil.copyfileobj`.
"""
... | [
"def",
"save",
"(",
"self",
",",
"destination",
":",
"BinaryIO",
",",
"buffer_size",
":",
"int",
"=",
"16384",
")",
"->",
"None",
":",
"close_destination",
"=",
"False",
"if",
"isinstance",
"(",
"destination",
",",
"str",
")",
":",
"destination",
"=",
"o... | Save the file to the destination.
Arguments:
destination: A filename (str) or file object to write to.
buffer_size: Buffer size as used as length in
:func:`shutil.copyfileobj`. | [
"Save",
"the",
"file",
"to",
"the",
"destination",
"."
] | python | train | 36.941176 |
jenisys/parse_type | tasks/_tasklet_cleanup.py | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/tasks/_tasklet_cleanup.py#L70-L83 | def execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=False):
"""Execute several cleanup tasks as part of the cleanup.
REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks.
:param ctx: Context object for the tasks.
:param cleanup_tasks: Collection of cleanup tasks (as Colle... | [
"def",
"execute_cleanup_tasks",
"(",
"ctx",
",",
"cleanup_tasks",
",",
"dry_run",
"=",
"False",
")",
":",
"# pylint: disable=redefined-outer-name",
"executor",
"=",
"Executor",
"(",
"cleanup_tasks",
",",
"ctx",
".",
"config",
")",
"for",
"cleanup_task",
"in",
"cle... | Execute several cleanup tasks as part of the cleanup.
REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks.
:param ctx: Context object for the tasks.
:param cleanup_tasks: Collection of cleanup tasks (as Collection).
:param dry_run: Indicates dry-run mode (bool) | [
"Execute",
"several",
"cleanup",
"tasks",
"as",
"part",
"of",
"the",
"cleanup",
"."
] | python | train | 45.142857 |
draperjames/qtpandas | qtpandas/utils.py | https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/utils.py#L33-L56 | def convertTimestamps(column):
"""Convert a dtype of a given column to a datetime.
This method tries to do this by brute force.
Args:
column (pandas.Series): A Series object with all rows.
Returns:
column: Converted to datetime if no errors occured, else the
original colum... | [
"def",
"convertTimestamps",
"(",
"column",
")",
":",
"tempColumn",
"=",
"column",
"try",
":",
"# Try to convert the first row and a random row instead of the complete",
"# column, might be faster",
"# tempValue = np.datetime64(column[0])",
"tempValue",
"=",
"np",
".",
"datetime64... | Convert a dtype of a given column to a datetime.
This method tries to do this by brute force.
Args:
column (pandas.Series): A Series object with all rows.
Returns:
column: Converted to datetime if no errors occured, else the
original column will be returned. | [
"Convert",
"a",
"dtype",
"of",
"a",
"given",
"column",
"to",
"a",
"datetime",
"."
] | python | train | 29.208333 |
gaqzi/py-gocd | gocd/api/pipeline.py | https://github.com/gaqzi/py-gocd/blob/6fe5b62dea51e665c11a343aba5fc98e130c5c63/gocd/api/pipeline.py#L208-L252 | def console_output(self, instance=None):
"""Yields the output and metadata from all jobs in the pipeline
Args:
instance: The result of a :meth:`instance` call, if not supplied
the latest of the pipeline will be used.
Yields:
tuple: (metadata (dict), output (str)... | [
"def",
"console_output",
"(",
"self",
",",
"instance",
"=",
"None",
")",
":",
"if",
"instance",
"is",
"None",
":",
"instance",
"=",
"self",
".",
"instance",
"(",
")",
"for",
"stage",
"in",
"instance",
"[",
"'stages'",
"]",
":",
"for",
"job",
"in",
"s... | Yields the output and metadata from all jobs in the pipeline
Args:
instance: The result of a :meth:`instance` call, if not supplied
the latest of the pipeline will be used.
Yields:
tuple: (metadata (dict), output (str)).
metadata contains:
- pipel... | [
"Yields",
"the",
"output",
"and",
"metadata",
"from",
"all",
"jobs",
"in",
"the",
"pipeline"
] | python | valid | 31.377778 |
ethereum/py-evm | eth/rlp/transactions.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/rlp/transactions.py#L155-L166 | def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
... | [
"def",
"create_unsigned_transaction",
"(",
"cls",
",",
"*",
",",
"nonce",
":",
"int",
",",
"gas_price",
":",
"int",
",",
"gas",
":",
"int",
",",
"to",
":",
"Address",
",",
"value",
":",
"int",
",",
"data",
":",
"bytes",
")",
"->",
"'BaseUnsignedTransac... | Create an unsigned transaction. | [
"Create",
"an",
"unsigned",
"transaction",
"."
] | python | train | 43.416667 |
google/transitfeed | transitfeed/util.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/util.py#L255-L266 | def ValidateURL(url, column_name=None, problems=None):
"""
Validates a non-required URL value using IsValidURL():
- if invalid adds InvalidValue error (if problems accumulator is provided)
- an empty URL is considered valid and no error or warning is issued.
"""
if IsEmpty(url) or IsValidURL(url):
r... | [
"def",
"ValidateURL",
"(",
"url",
",",
"column_name",
"=",
"None",
",",
"problems",
"=",
"None",
")",
":",
"if",
"IsEmpty",
"(",
"url",
")",
"or",
"IsValidURL",
"(",
"url",
")",
":",
"return",
"True",
"else",
":",
"if",
"problems",
":",
"problems",
"... | Validates a non-required URL value using IsValidURL():
- if invalid adds InvalidValue error (if problems accumulator is provided)
- an empty URL is considered valid and no error or warning is issued. | [
"Validates",
"a",
"non",
"-",
"required",
"URL",
"value",
"using",
"IsValidURL",
"()",
":",
"-",
"if",
"invalid",
"adds",
"InvalidValue",
"error",
"(",
"if",
"problems",
"accumulator",
"is",
"provided",
")",
"-",
"an",
"empty",
"URL",
"is",
"considered",
"... | python | train | 33.916667 |
numenta/htmresearch | htmresearch/algorithms/lateral_pooler.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/algorithms/lateral_pooler.py#L67-L98 | def _inhibitColumnsWithLateral(self, overlaps, lateralConnections):
"""
Performs an experimentatl local inhibition. Local inhibition is
iteratively performed on a column by column basis.
"""
n,m = self.shape
y = np.zeros(n)
s = self.sparsity
L = lateralConnections
desiredWeigh... | [
"def",
"_inhibitColumnsWithLateral",
"(",
"self",
",",
"overlaps",
",",
"lateralConnections",
")",
":",
"n",
",",
"m",
"=",
"self",
".",
"shape",
"y",
"=",
"np",
".",
"zeros",
"(",
"n",
")",
"s",
"=",
"self",
".",
"sparsity",
"L",
"=",
"lateralConnecti... | Performs an experimentatl local inhibition. Local inhibition is
iteratively performed on a column by column basis. | [
"Performs",
"an",
"experimentatl",
"local",
"inhibition",
".",
"Local",
"inhibition",
"is",
"iteratively",
"performed",
"on",
"a",
"column",
"by",
"column",
"basis",
"."
] | python | train | 26.25 |
fermiPy/fermipy | fermipy/roi_model.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/roi_model.py#L1940-L1951 | def load_fits_catalog(self, name, **kwargs):
"""Load sources from a FITS catalog file.
Parameters
----------
name : str
Catalog name or path to a catalog FITS file.
"""
# EAC split this function to make it easier to load an existing catalog
cat = cat... | [
"def",
"load_fits_catalog",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"# EAC split this function to make it easier to load an existing catalog",
"cat",
"=",
"catalog",
".",
"Catalog",
".",
"create",
"(",
"name",
")",
"self",
".",
"load_existing_ca... | Load sources from a FITS catalog file.
Parameters
----------
name : str
Catalog name or path to a catalog FITS file. | [
"Load",
"sources",
"from",
"a",
"FITS",
"catalog",
"file",
"."
] | python | train | 32 |
saltstack/salt | salt/cloud/clouds/xen.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/xen.py#L1259-L1289 | def destroy_template(name=None, call=None, kwargs=None):
'''
Destroy Xen VM or template instance
.. code-block:: bash
salt-cloud -f destroy_template myxen name=testvm2
'''
if call == 'action':
raise SaltCloudSystemExit(
'The destroy_template function must be ca... | [
"def",
"destroy_template",
"(",
"name",
"=",
"None",
",",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy_template function must be called with -f.'",
")",
"if",
... | Destroy Xen VM or template instance
.. code-block:: bash
salt-cloud -f destroy_template myxen name=testvm2 | [
"Destroy",
"Xen",
"VM",
"or",
"template",
"instance"
] | python | train | 29.16129 |
llllllllll/codetransformer | codetransformer/code.py | https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/code.py#L220-L257 | def pycode(argcount,
kwonlyargcount,
nlocals,
stacksize,
flags,
codestring,
constants,
names,
varnames,
filename,
name,
firstlineno,
lnotab,
freevars=(),
cellvars=())... | [
"def",
"pycode",
"(",
"argcount",
",",
"kwonlyargcount",
",",
"nlocals",
",",
"stacksize",
",",
"flags",
",",
"codestring",
",",
"constants",
",",
"names",
",",
"varnames",
",",
"filename",
",",
"name",
",",
"firstlineno",
",",
"lnotab",
",",
"freevars",
"... | types.CodeType constructor that accepts keyword arguments.
See Also
--------
types.CodeType | [
"types",
".",
"CodeType",
"constructor",
"that",
"accepts",
"keyword",
"arguments",
"."
] | python | train | 18.447368 |
kgiusti/pyngus | pyngus/link.py | https://github.com/kgiusti/pyngus/blob/5392392046989f1bb84ba938c30e4d48311075f1/pyngus/link.py#L171-L178 | def target_address(self):
"""Return the authorative target of the link."""
# If link is a receiver, target is determined by the local
# value, else use the remote.
if self._pn_link.is_receiver:
return self._pn_link.target.address
else:
return self._pn_link... | [
"def",
"target_address",
"(",
"self",
")",
":",
"# If link is a receiver, target is determined by the local",
"# value, else use the remote.",
"if",
"self",
".",
"_pn_link",
".",
"is_receiver",
":",
"return",
"self",
".",
"_pn_link",
".",
"target",
".",
"address",
"else... | Return the authorative target of the link. | [
"Return",
"the",
"authorative",
"target",
"of",
"the",
"link",
"."
] | python | test | 41.875 |
IrvKalb/pygwidgets | pygwidgets/pygwidgets.py | https://github.com/IrvKalb/pygwidgets/blob/a830d8885d4d209e471cb53816277d30db56273c/pygwidgets/pygwidgets.py#L2212-L2217 | def flipVertical(self):
""" flips an image object vertically
"""
self.flipV = not self.flipV
self._transmogrophy(self.angle, self.percent, self.scaleFromCenter, self.flipH, self.flipV) | [
"def",
"flipVertical",
"(",
"self",
")",
":",
"self",
".",
"flipV",
"=",
"not",
"self",
".",
"flipV",
"self",
".",
"_transmogrophy",
"(",
"self",
".",
"angle",
",",
"self",
".",
"percent",
",",
"self",
".",
"scaleFromCenter",
",",
"self",
".",
"flipH",... | flips an image object vertically | [
"flips",
"an",
"image",
"object",
"vertically"
] | python | train | 37.5 |
alerta/python-alerta-client | alertaclient/commands/cmd_raw.py | https://github.com/alerta/python-alerta-client/blob/7eb367b5fe87d5fc20b54dea8cddd7f09e251afa/alertaclient/commands/cmd_raw.py#L13-L26 | def cli(obj, ids, query, filters):
"""Show raw data for alerts."""
client = obj['client']
if ids:
query = [('id', x) for x in ids]
elif query:
query = [('q', query)]
else:
query = build_query(filters)
alerts = client.search(query)
headers = {'id': 'ID', 'rawData': 'R... | [
"def",
"cli",
"(",
"obj",
",",
"ids",
",",
"query",
",",
"filters",
")",
":",
"client",
"=",
"obj",
"[",
"'client'",
"]",
"if",
"ids",
":",
"query",
"=",
"[",
"(",
"'id'",
",",
"x",
")",
"for",
"x",
"in",
"ids",
"]",
"elif",
"query",
":",
"qu... | Show raw data for alerts. | [
"Show",
"raw",
"data",
"for",
"alerts",
"."
] | python | train | 31.857143 |
eirannejad/Revit-Journal-Maker | rjm/__init__.py | https://github.com/eirannejad/Revit-Journal-Maker/blob/09a4f27da6d183f63a2c93ed99dca8a8590d5241/rjm/__init__.py#L394-L420 | def sync_model(self, comment='', compact_central=False,
release_borrowed=True, release_workset=True,
save_local=False):
"""Append a sync model entry to the journal.
This instructs Revit to sync the currently open workshared model.
Args:
comment... | [
"def",
"sync_model",
"(",
"self",
",",
"comment",
"=",
"''",
",",
"compact_central",
"=",
"False",
",",
"release_borrowed",
"=",
"True",
",",
"release_workset",
"=",
"True",
",",
"save_local",
"=",
"False",
")",
":",
"self",
".",
"_add_entry",
"(",
"templa... | Append a sync model entry to the journal.
This instructs Revit to sync the currently open workshared model.
Args:
comment (str): comment to be provided for the sync step
compact_central (bool): if True compacts the central file
release_borrowed (bool): if True relea... | [
"Append",
"a",
"sync",
"model",
"entry",
"to",
"the",
"journal",
"."
] | python | train | 43.814815 |
fstab50/metal | metal/script_utils.py | https://github.com/fstab50/metal/blob/0488bbdd516a508909267cc44191f632e21156ba/metal/script_utils.py#L78-L91 | def convert_timedelta(duration):
"""
Summary:
Convert duration into component time units
Args:
:duration (datetime.timedelta): time duration to convert
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers)
"""
days, seconds = duration.days, duration.seconds
... | [
"def",
"convert_timedelta",
"(",
"duration",
")",
":",
"days",
",",
"seconds",
"=",
"duration",
".",
"days",
",",
"duration",
".",
"seconds",
"hours",
"=",
"seconds",
"//",
"3600",
"minutes",
"=",
"(",
"seconds",
"%",
"3600",
")",
"//",
"60",
"seconds",
... | Summary:
Convert duration into component time units
Args:
:duration (datetime.timedelta): time duration to convert
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers) | [
"Summary",
":",
"Convert",
"duration",
"into",
"component",
"time",
"units",
"Args",
":",
":",
"duration",
"(",
"datetime",
".",
"timedelta",
")",
":",
"time",
"duration",
"to",
"convert",
"Returns",
":",
"days",
"hours",
"minutes",
"seconds",
"|",
"TYPE",
... | python | train | 31.214286 |
elyase/masstable | masstable/masstable.py | https://github.com/elyase/masstable/blob/3eb72b22cd3337bc5c6bb95bb7bb73fdbe6ae9e2/masstable/masstable.py#L329-L341 | def odd_odd(self):
"""Selects odd-odd nuclei from the table:
>>> Table('FRDM95').odd_odd
Out[13]:
Z N
9 9 1.21
11 0.10
13 3.08
15 9.32
...
"""
return self.select(lambda Z, N: (Z % 2) and (N % 2)... | [
"def",
"odd_odd",
"(",
"self",
")",
":",
"return",
"self",
".",
"select",
"(",
"lambda",
"Z",
",",
"N",
":",
"(",
"Z",
"%",
"2",
")",
"and",
"(",
"N",
"%",
"2",
")",
",",
"name",
"=",
"self",
".",
"name",
")"
] | Selects odd-odd nuclei from the table:
>>> Table('FRDM95').odd_odd
Out[13]:
Z N
9 9 1.21
11 0.10
13 3.08
15 9.32
... | [
"Selects",
"odd",
"-",
"odd",
"nuclei",
"from",
"the",
"table",
":"
] | python | test | 25 |
SBRG/ssbio | ssbio/biopython/Bio/Struct/WWW/WHATIFXML.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/biopython/Bio/Struct/WWW/WHATIFXML.py#L72-L79 | def _handle_builder_exception(self, message, residue):
"""
Makes a PDB Construction Error a bit more verbose and informative
"""
message = "%s. Error when parsing residue %s:%s" %(message, residue['number'], residue['name'])
raise PDBConstructionException(messag... | [
"def",
"_handle_builder_exception",
"(",
"self",
",",
"message",
",",
"residue",
")",
":",
"message",
"=",
"\"%s. Error when parsing residue %s:%s\"",
"%",
"(",
"message",
",",
"residue",
"[",
"'number'",
"]",
",",
"residue",
"[",
"'name'",
"]",
")",
"raise",
... | Makes a PDB Construction Error a bit more verbose and informative | [
"Makes",
"a",
"PDB",
"Construction",
"Error",
"a",
"bit",
"more",
"verbose",
"and",
"informative"
] | python | train | 39.375 |
mitsei/dlkit | dlkit/records/osid/base_records.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/osid/base_records.py#L2151-L2155 | def has_file_url(self):
"""stub"""
return bool(self._get_asset_content(
Id(self.my_osid_object._my_map['fileId']['assetId']),
self.my_osid_object._my_map['fileId']['assetContentTypeId']).has_url()) | [
"def",
"has_file_url",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"_get_asset_content",
"(",
"Id",
"(",
"self",
".",
"my_osid_object",
".",
"_my_map",
"[",
"'fileId'",
"]",
"[",
"'assetId'",
"]",
")",
",",
"self",
".",
"my_osid_object",
"... | stub | [
"stub"
] | python | train | 46.6 |
astrorafael/twisted-mqtt | mqtt/pdu.py | https://github.com/astrorafael/twisted-mqtt/blob/5b322f7c2b82a502b1e1b70703ae45f1f668d07d/mqtt/pdu.py#L92-L106 | def encodeLength(value):
'''
Encodes value into a multibyte sequence defined by MQTT protocol.
Used to encode packet length fields.
'''
encoded = bytearray()
while True:
digit = value % 128
value //= 128
if value > 0:
digit |= 128
encoded.append(digit)... | [
"def",
"encodeLength",
"(",
"value",
")",
":",
"encoded",
"=",
"bytearray",
"(",
")",
"while",
"True",
":",
"digit",
"=",
"value",
"%",
"128",
"value",
"//=",
"128",
"if",
"value",
">",
"0",
":",
"digit",
"|=",
"128",
"encoded",
".",
"append",
"(",
... | Encodes value into a multibyte sequence defined by MQTT protocol.
Used to encode packet length fields. | [
"Encodes",
"value",
"into",
"a",
"multibyte",
"sequence",
"defined",
"by",
"MQTT",
"protocol",
".",
"Used",
"to",
"encode",
"packet",
"length",
"fields",
"."
] | python | test | 24.4 |
apache/incubator-mxnet | python/mxnet/ndarray/ndarray.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L4070-L4117 | def from_dlpack(dlpack):
"""Returns a NDArray backed by a dlpack tensor.
Parameters
----------
dlpack: PyCapsule (the pointer of DLManagedTensor)
input data
Returns
-------
NDArray
a NDArray backed by a dlpack tensor
Examples
--------
>>> x = mx.nd.ones((2,3))
... | [
"def",
"from_dlpack",
"(",
"dlpack",
")",
":",
"handle",
"=",
"NDArrayHandle",
"(",
")",
"dlpack",
"=",
"ctypes",
".",
"py_object",
"(",
"dlpack",
")",
"assert",
"ctypes",
".",
"pythonapi",
".",
"PyCapsule_IsValid",
"(",
"dlpack",
",",
"_c_str_dltensor",
")"... | Returns a NDArray backed by a dlpack tensor.
Parameters
----------
dlpack: PyCapsule (the pointer of DLManagedTensor)
input data
Returns
-------
NDArray
a NDArray backed by a dlpack tensor
Examples
--------
>>> x = mx.nd.ones((2,3))
>>> y = mx.nd.to_dlpack_for_... | [
"Returns",
"a",
"NDArray",
"backed",
"by",
"a",
"dlpack",
"tensor",
"."
] | python | train | 28.583333 |
coursera-dl/coursera-dl | coursera/utils.py | https://github.com/coursera-dl/coursera-dl/blob/9b434bcf3c4011bf3181429fe674633ae5fb7d4d/coursera/utils.py#L173-L181 | def get_anchor_format(a):
"""
Extract the resource file-type format from the anchor.
"""
# (. or format=) then (file_extension) then (? or $)
# e.g. "...format=txt" or "...download.mp4?..."
fmt = re.search(r"(?:\.|format=)(\w+)(?:\?.*)?$", a)
return fmt.group(1) if fmt else None | [
"def",
"get_anchor_format",
"(",
"a",
")",
":",
"# (. or format=) then (file_extension) then (? or $)",
"# e.g. \"...format=txt\" or \"...download.mp4?...\"",
"fmt",
"=",
"re",
".",
"search",
"(",
"r\"(?:\\.|format=)(\\w+)(?:\\?.*)?$\"",
",",
"a",
")",
"return",
"fmt",
".",
... | Extract the resource file-type format from the anchor. | [
"Extract",
"the",
"resource",
"file",
"-",
"type",
"format",
"from",
"the",
"anchor",
"."
] | python | train | 33.333333 |
neptune-ml/steppy-toolkit | toolkit/preprocessing/misc.py | https://github.com/neptune-ml/steppy-toolkit/blob/bf3f48cfcc65dffc46e65ddd5d6cfec6bb9f9132/toolkit/preprocessing/misc.py#L163-L173 | def transform(self, X):
"""
Args:
X: DataFrame with NaN's
Returns:
Dictionary with one key - 'X' corresponding to given DataFrame but without nan's
"""
if self.fill_missing:
X = self.filler.complete(X)
return {'X': X} | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"if",
"self",
".",
"fill_missing",
":",
"X",
"=",
"self",
".",
"filler",
".",
"complete",
"(",
"X",
")",
"return",
"{",
"'X'",
":",
"X",
"}"
] | Args:
X: DataFrame with NaN's
Returns:
Dictionary with one key - 'X' corresponding to given DataFrame but without nan's | [
"Args",
":",
"X",
":",
"DataFrame",
"with",
"NaN",
"s",
"Returns",
":",
"Dictionary",
"with",
"one",
"key",
"-",
"X",
"corresponding",
"to",
"given",
"DataFrame",
"but",
"without",
"nan",
"s"
] | python | train | 26.545455 |
NuGrid/NuGridPy | nugridpy/utils.py | https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/utils.py#L955-L979 | def colourblind(i):
'''
colour pallete from http://tableaufriction.blogspot.ro/
allegedly suitable for colour-blind folk
SJ
'''
rawRGBs = [(162,200,236),
(255,128,14),
(171,171,171),
(95,158,209),
(89,89,89),
... | [
"def",
"colourblind",
"(",
"i",
")",
":",
"rawRGBs",
"=",
"[",
"(",
"162",
",",
"200",
",",
"236",
")",
",",
"(",
"255",
",",
"128",
",",
"14",
")",
",",
"(",
"171",
",",
"171",
",",
"171",
")",
",",
"(",
"95",
",",
"158",
",",
"209",
")"... | colour pallete from http://tableaufriction.blogspot.ro/
allegedly suitable for colour-blind folk
SJ | [
"colour",
"pallete",
"from",
"http",
":",
"//",
"tableaufriction",
".",
"blogspot",
".",
"ro",
"/",
"allegedly",
"suitable",
"for",
"colour",
"-",
"blind",
"folk"
] | python | train | 24.8 |
angr/angr | angr/exploration_techniques/director.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/exploration_techniques/director.py#L79-L112 | def _dfs_edges(graph, source, max_steps=None):
"""
Perform a depth-first search on the given DiGraph, with a limit on maximum steps.
:param networkx.DiGraph graph: The graph to traverse.
:param Any source: The source to begin traversal.
:param int max_steps: ... | [
"def",
"_dfs_edges",
"(",
"graph",
",",
"source",
",",
"max_steps",
"=",
"None",
")",
":",
"if",
"max_steps",
"is",
"None",
":",
"yield",
"networkx",
".",
"dfs_edges",
"(",
"graph",
",",
"source",
")",
"else",
":",
"steps_map",
"=",
"defaultdict",
"(",
... | Perform a depth-first search on the given DiGraph, with a limit on maximum steps.
:param networkx.DiGraph graph: The graph to traverse.
:param Any source: The source to begin traversal.
:param int max_steps: Maximum steps of the traversal, or None if not limiting steps.
... | [
"Perform",
"a",
"depth",
"-",
"first",
"search",
"on",
"the",
"given",
"DiGraph",
"with",
"a",
"limit",
"on",
"maximum",
"steps",
"."
] | python | train | 32.558824 |
KrzyHonk/bpmn-python | bpmn_python/graph/classes/condition_expression_type.py | https://github.com/KrzyHonk/bpmn-python/blob/6e5e28e3d656dbf5bd3d85d78fe8e3f2fb462629/bpmn_python/graph/classes/condition_expression_type.py#L28-L36 | def set_condition(self, value):
"""
Setter for 'condition' field.
:param value - a new value of 'condition' field. Required field. Must be a String.
"""
if value is None or not isinstance(value, str):
raise TypeError("Condition is required and must be set to a String"... | [
"def",
"set_condition",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Condition is required and must be set to a String\"",
")",
"else",
":",
"self... | Setter for 'condition' field.
:param value - a new value of 'condition' field. Required field. Must be a String. | [
"Setter",
"for",
"condition",
"field",
".",
":",
"param",
"value",
"-",
"a",
"new",
"value",
"of",
"condition",
"field",
".",
"Required",
"field",
".",
"Must",
"be",
"a",
"String",
"."
] | python | train | 40.444444 |
DLR-RM/RAFCON | source/rafcon/core/states/container_state.py | https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/container_state.py#L1978-L2000 | def _check_transition_target(self, transition):
"""Checks the validity of a transition target
Checks whether the transition target is valid.
:param rafcon.core.transition.Transition transition: The transition to be checked
:return bool validity, str message: validity is True, when the ... | [
"def",
"_check_transition_target",
"(",
"self",
",",
"transition",
")",
":",
"to_state_id",
"=",
"transition",
".",
"to_state",
"to_outcome_id",
"=",
"transition",
".",
"to_outcome",
"if",
"to_state_id",
"==",
"self",
".",
"state_id",
":",
"if",
"to_outcome_id",
... | Checks the validity of a transition target
Checks whether the transition target is valid.
:param rafcon.core.transition.Transition transition: The transition to be checked
:return bool validity, str message: validity is True, when the transition is valid, False else. message gives
... | [
"Checks",
"the",
"validity",
"of",
"a",
"transition",
"target"
] | python | train | 41.217391 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.