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 |
|---|---|---|---|---|---|---|---|---|---|
openfisca/openfisca-core | openfisca_core/populations.py | https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/populations.py#L310-L325 | def any(self, array, role = None):
"""
Return ``True`` if ``array`` is ``True`` for any members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into acc... | [
"def",
"any",
"(",
"self",
",",
"array",
",",
"role",
"=",
"None",
")",
":",
"sum_in_entity",
"=",
"self",
".",
"sum",
"(",
"array",
",",
"role",
"=",
"role",
")",
"return",
"(",
"sum_in_entity",
">",
"0",
")"
] | Return ``True`` if ``array`` is ``True`` for any members of the entity.
``array`` must have the dimension of the number of persons in the simulation
If ``role`` is provided, only the entity member with the given role are taken into account.
Example:
>>> salaries = hou... | [
"Return",
"True",
"if",
"array",
"is",
"True",
"for",
"any",
"members",
"of",
"the",
"entity",
"."
] | python | train | 37.9375 |
dmlc/gluon-nlp | scripts/word_embeddings/data.py | https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/word_embeddings/data.py#L376-L427 | def skipgram_lookup(indices, subwordidxs, subwordidxsptr, offset=0):
"""Get a sparse COO array of words and subwords for SkipGram.
Parameters
----------
indices : numpy.ndarray
Array containing numbers in [0, vocabulary_size). The element at
position idx is taken to be the word that occ... | [
"def",
"skipgram_lookup",
"(",
"indices",
",",
"subwordidxs",
",",
"subwordidxsptr",
",",
"offset",
"=",
"0",
")",
":",
"row",
"=",
"[",
"]",
"col",
"=",
"[",
"]",
"data",
"=",
"[",
"]",
"for",
"i",
",",
"idx",
"in",
"enumerate",
"(",
"indices",
")... | Get a sparse COO array of words and subwords for SkipGram.
Parameters
----------
indices : numpy.ndarray
Array containing numbers in [0, vocabulary_size). The element at
position idx is taken to be the word that occurs at row idx in the
SkipGram batch.
offset : int
Offse... | [
"Get",
"a",
"sparse",
"COO",
"array",
"of",
"words",
"and",
"subwords",
"for",
"SkipGram",
"."
] | python | train | 37.384615 |
scivision/pymap3d | pymap3d/timeconv.py | https://github.com/scivision/pymap3d/blob/c9cf676594611cdb52ff7e0eca6388c80ed4f63f/pymap3d/timeconv.py#L10-L44 | def str2dt(time: datetime) -> np.ndarray:
"""
Converts times in string or list of strings to datetime(s)
Parameters
----------
time : str or datetime.datetime or numpy.datetime64
Results
-------
t : datetime.datetime
"""
if isinstance(time, datetime):
return time
... | [
"def",
"str2dt",
"(",
"time",
":",
"datetime",
")",
"->",
"np",
".",
"ndarray",
":",
"if",
"isinstance",
"(",
"time",
",",
"datetime",
")",
":",
"return",
"time",
"elif",
"isinstance",
"(",
"time",
",",
"str",
")",
":",
"return",
"parse",
"(",
"time"... | Converts times in string or list of strings to datetime(s)
Parameters
----------
time : str or datetime.datetime or numpy.datetime64
Results
-------
t : datetime.datetime | [
"Converts",
"times",
"in",
"string",
"or",
"list",
"of",
"strings",
"to",
"datetime",
"(",
"s",
")"
] | python | train | 25.8 |
Jammy2211/PyAutoLens | autolens/data/ccd.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/data/ccd.py#L1132-L1149 | def load_psf(psf_path, psf_hdu, pixel_scale, renormalize=False):
"""Factory for loading the psf from a .fits file.
Parameters
----------
psf_path : str
The path to the psf .fits file containing the psf (e.g. '/path/to/psf.fits')
psf_hdu : int
The hdu the psf is contained in the .fit... | [
"def",
"load_psf",
"(",
"psf_path",
",",
"psf_hdu",
",",
"pixel_scale",
",",
"renormalize",
"=",
"False",
")",
":",
"if",
"renormalize",
":",
"return",
"PSF",
".",
"from_fits_renormalized",
"(",
"file_path",
"=",
"psf_path",
",",
"hdu",
"=",
"psf_hdu",
",",
... | Factory for loading the psf from a .fits file.
Parameters
----------
psf_path : str
The path to the psf .fits file containing the psf (e.g. '/path/to/psf.fits')
psf_hdu : int
The hdu the psf is contained in the .fits file specified by *psf_path*.
pixel_scale : float
The size... | [
"Factory",
"for",
"loading",
"the",
"psf",
"from",
"a",
".",
"fits",
"file",
"."
] | python | valid | 41.833333 |
Capitains/MyCapytain | MyCapytain/resolvers/cts/local.py | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resolvers/cts/local.py#L125-L137 | def _parse_textgroup_wrapper(self, cts_file):
""" Wraps with a Try/Except the textgroup parsing from a cts file
:param cts_file: Path to the CTS File
:type cts_file: str
:return: CtsTextgroupMetadata
"""
try:
return self._parse_textgroup(cts_file)
exc... | [
"def",
"_parse_textgroup_wrapper",
"(",
"self",
",",
"cts_file",
")",
":",
"try",
":",
"return",
"self",
".",
"_parse_textgroup",
"(",
"cts_file",
")",
"except",
"Exception",
"as",
"E",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Error parsing %s \"",
... | Wraps with a Try/Except the textgroup parsing from a cts file
:param cts_file: Path to the CTS File
:type cts_file: str
:return: CtsTextgroupMetadata | [
"Wraps",
"with",
"a",
"Try",
"/",
"Except",
"the",
"textgroup",
"parsing",
"from",
"a",
"cts",
"file"
] | python | train | 35.692308 |
SBRG/ssbio | ssbio/utils.py | https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/utils.py#L327-L362 | def force_rerun(flag, outfile):
"""Check if we should force rerunning of a command if an output file exists.
Args:
flag (bool): Flag to force rerun.
outfile (str): Path to output file which may already exist.
Returns:
bool: If we should force rerunning of a command
Examples:
... | [
"def",
"force_rerun",
"(",
"flag",
",",
"outfile",
")",
":",
"# If flag is True, always run",
"if",
"flag",
":",
"return",
"True",
"# If flag is False but file doesn't exist, also run",
"elif",
"not",
"flag",
"and",
"not",
"op",
".",
"exists",
"(",
"outfile",
")",
... | Check if we should force rerunning of a command if an output file exists.
Args:
flag (bool): Flag to force rerun.
outfile (str): Path to output file which may already exist.
Returns:
bool: If we should force rerunning of a command
Examples:
>>> force_rerun(flag=True, outfi... | [
"Check",
"if",
"we",
"should",
"force",
"rerunning",
"of",
"a",
"command",
"if",
"an",
"output",
"file",
"exists",
"."
] | python | train | 27.333333 |
cltk/cltk | cltk/corpus/greek/alphabet.py | https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/corpus/greek/alphabet.py#L522-L533 | def expand_iota_subscript(input_str, lowercase=False):
"""Find characters with iota subscript and replace w/ char + iota added."""
new_list = []
for char in input_str:
new_char = MAP_SUBSCRIPT_NO_SUB.get(char)
if not new_char:
new_char = char
new_list.append(new_char)
... | [
"def",
"expand_iota_subscript",
"(",
"input_str",
",",
"lowercase",
"=",
"False",
")",
":",
"new_list",
"=",
"[",
"]",
"for",
"char",
"in",
"input_str",
":",
"new_char",
"=",
"MAP_SUBSCRIPT_NO_SUB",
".",
"get",
"(",
"char",
")",
"if",
"not",
"new_char",
":... | Find characters with iota subscript and replace w/ char + iota added. | [
"Find",
"characters",
"with",
"iota",
"subscript",
"and",
"replace",
"w",
"/",
"char",
"+",
"iota",
"added",
"."
] | python | train | 34 |
danilobellini/audiolazy | audiolazy/lazy_lpc.py | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_lpc.py#L276-L294 | def lpc(blk, order=None):
"""
Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object,
the analysis whitening filter. This implementation uses the covariance
method, assuming a zero-mean stochastic process, using numpy.linalg.pinv
as a linear system solver.
"""
from numpy import matrix
... | [
"def",
"lpc",
"(",
"blk",
",",
"order",
"=",
"None",
")",
":",
"from",
"numpy",
"import",
"matrix",
"from",
"numpy",
".",
"linalg",
"import",
"pinv",
"lagm",
"=",
"lag_matrix",
"(",
"blk",
",",
"order",
")",
"phi",
"=",
"matrix",
"(",
"lagm",
")",
... | Find the Linear Predictive Coding (LPC) coefficients as a ZFilter object,
the analysis whitening filter. This implementation uses the covariance
method, assuming a zero-mean stochastic process, using numpy.linalg.pinv
as a linear system solver. | [
"Find",
"the",
"Linear",
"Predictive",
"Coding",
"(",
"LPC",
")",
"coefficients",
"as",
"a",
"ZFilter",
"object",
"the",
"analysis",
"whitening",
"filter",
".",
"This",
"implementation",
"uses",
"the",
"covariance",
"method",
"assuming",
"a",
"zero",
"-",
"mea... | python | train | 33.105263 |
helixyte/everest | everest/repositories/uow.py | https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/repositories/uow.py#L42-L50 | def register_clean(self, entity_class, entity):
"""
Registers the given entity for the given class as CLEAN.
:returns: Cloned entity.
"""
EntityState.manage(entity, self)
EntityState.get_state(entity).status = ENTITY_STATUS.CLEAN
self.__entity_set_map[entity_clas... | [
"def",
"register_clean",
"(",
"self",
",",
"entity_class",
",",
"entity",
")",
":",
"EntityState",
".",
"manage",
"(",
"entity",
",",
"self",
")",
"EntityState",
".",
"get_state",
"(",
"entity",
")",
".",
"status",
"=",
"ENTITY_STATUS",
".",
"CLEAN",
"self... | Registers the given entity for the given class as CLEAN.
:returns: Cloned entity. | [
"Registers",
"the",
"given",
"entity",
"for",
"the",
"given",
"class",
"as",
"CLEAN",
"."
] | python | train | 36.222222 |
python-cmd2/cmd2 | cmd2/history.py | https://github.com/python-cmd2/cmd2/blob/b22c0bd891ed08c8b09df56df9d91f48166a5e2a/cmd2/history.py#L92-L104 | def get(self, index: Union[int, str]) -> HistoryItem:
"""Get item from the History list using 1-based indexing.
:param index: optional item to get (index as either integer or string)
:return: a single HistoryItem
"""
index = int(index)
if index == 0:
raise In... | [
"def",
"get",
"(",
"self",
",",
"index",
":",
"Union",
"[",
"int",
",",
"str",
"]",
")",
"->",
"HistoryItem",
":",
"index",
"=",
"int",
"(",
"index",
")",
"if",
"index",
"==",
"0",
":",
"raise",
"IndexError",
"(",
"'The first command in history is comman... | Get item from the History list using 1-based indexing.
:param index: optional item to get (index as either integer or string)
:return: a single HistoryItem | [
"Get",
"item",
"from",
"the",
"History",
"list",
"using",
"1",
"-",
"based",
"indexing",
"."
] | python | train | 35.846154 |
sibirrer/lenstronomy | lenstronomy/LensModel/numerical_profile_integrals.py | https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/LensModel/numerical_profile_integrals.py#L39-L54 | def density_2d(self, r, kwargs_profile):
"""
computes the projected density along the line-of-sight
:param r: radius (arcsec)
:param kwargs_profile: keyword argument list with lens model parameters
:return: 2d projected density at projected radius r
"""
kwargs = c... | [
"def",
"density_2d",
"(",
"self",
",",
"r",
",",
"kwargs_profile",
")",
":",
"kwargs",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs_profile",
")",
"try",
":",
"del",
"kwargs",
"[",
"'center_x'",
"]",
"del",
"kwargs",
"[",
"'center_y'",
"]",
"except",
":",
... | computes the projected density along the line-of-sight
:param r: radius (arcsec)
:param kwargs_profile: keyword argument list with lens model parameters
:return: 2d projected density at projected radius r | [
"computes",
"the",
"projected",
"density",
"along",
"the",
"line",
"-",
"of",
"-",
"sight",
":",
"param",
"r",
":",
"radius",
"(",
"arcsec",
")",
":",
"param",
"kwargs_profile",
":",
"keyword",
"argument",
"list",
"with",
"lens",
"model",
"parameters",
":"... | python | train | 40.5625 |
SpriteLink/NIPAP | nipap/nipap/backend.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap/nipap/backend.py#L1146-L1183 | def _expand_vrf_spec(self, spec):
""" Expand VRF specification to SQL.
id [integer]
internal database id of VRF
name [string]
name of VRF
A VRF is referenced either by its internal database id or by its
name. Both are used for ex... | [
"def",
"_expand_vrf_spec",
"(",
"self",
",",
"spec",
")",
":",
"if",
"type",
"(",
"spec",
")",
"is",
"not",
"dict",
":",
"raise",
"NipapInputError",
"(",
"\"vrf specification must be a dict\"",
")",
"allowed_values",
"=",
"[",
"'id'",
",",
"'name'",
",",
"'r... | Expand VRF specification to SQL.
id [integer]
internal database id of VRF
name [string]
name of VRF
A VRF is referenced either by its internal database id or by its
name. Both are used for exact matching and so no wildcard or
... | [
"Expand",
"VRF",
"specification",
"to",
"SQL",
"."
] | python | train | 39.5 |
ladybug-tools/uwg | uwg/element.py | https://github.com/ladybug-tools/uwg/blob/fb71f656b3cb69e7ccf1d851dff862e14fa210fc/uwg/element.py#L233-L254 | def qsat(self,temp,pres,parameter):
"""
Calculate (qsat_lst) vector of saturation humidity from:
temp = vector of element layer temperatures
pres = pressure (at current timestep).
"""
gamw = (parameter.cl - parameter.cpv) / parameter.rv
betaw = (parameter.... | [
"def",
"qsat",
"(",
"self",
",",
"temp",
",",
"pres",
",",
"parameter",
")",
":",
"gamw",
"=",
"(",
"parameter",
".",
"cl",
"-",
"parameter",
".",
"cpv",
")",
"/",
"parameter",
".",
"rv",
"betaw",
"=",
"(",
"parameter",
".",
"lvtt",
"/",
"parameter... | Calculate (qsat_lst) vector of saturation humidity from:
temp = vector of element layer temperatures
pres = pressure (at current timestep). | [
"Calculate",
"(",
"qsat_lst",
")",
"vector",
"of",
"saturation",
"humidity",
"from",
":",
"temp",
"=",
"vector",
"of",
"element",
"layer",
"temperatures",
"pres",
"=",
"pressure",
"(",
"at",
"current",
"timestep",
")",
"."
] | python | train | 43.863636 |
sorgerlab/indra | indra/assemblers/english/assembler.py | https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/assemblers/english/assembler.py#L317-L322 | def _assemble_gap(stmt):
"""Assemble Gap statements into text."""
subj_str = _assemble_agent_str(stmt.gap)
obj_str = _assemble_agent_str(stmt.ras)
stmt_str = subj_str + ' is a GAP for ' + obj_str
return _make_sentence(stmt_str) | [
"def",
"_assemble_gap",
"(",
"stmt",
")",
":",
"subj_str",
"=",
"_assemble_agent_str",
"(",
"stmt",
".",
"gap",
")",
"obj_str",
"=",
"_assemble_agent_str",
"(",
"stmt",
".",
"ras",
")",
"stmt_str",
"=",
"subj_str",
"+",
"' is a GAP for '",
"+",
"obj_str",
"r... | Assemble Gap statements into text. | [
"Assemble",
"Gap",
"statements",
"into",
"text",
"."
] | python | train | 40.333333 |
raiden-network/raiden | raiden/network/rpc/client.py | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/client.py#L188-L207 | def check_address_has_code(
client: 'JSONRPCClient',
address: Address,
contract_name: str = '',
):
""" Checks that the given address contains code. """
result = client.web3.eth.getCode(to_checksum_address(address), 'latest')
if not result:
if contract_name:
forma... | [
"def",
"check_address_has_code",
"(",
"client",
":",
"'JSONRPCClient'",
",",
"address",
":",
"Address",
",",
"contract_name",
":",
"str",
"=",
"''",
",",
")",
":",
"result",
"=",
"client",
".",
"web3",
".",
"eth",
".",
"getCode",
"(",
"to_checksum_address",
... | Checks that the given address contains code. | [
"Checks",
"that",
"the",
"given",
"address",
"contains",
"code",
"."
] | python | train | 30.4 |
pyviz/holoviews | holoviews/plotting/mpl/util.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/plotting/mpl/util.py#L189-L195 | def axis_overlap(ax1, ax2):
"""
Tests whether two axes overlap vertically
"""
b1, t1 = ax1.get_position().intervaly
b2, t2 = ax2.get_position().intervaly
return t1 > b2 and b1 < t2 | [
"def",
"axis_overlap",
"(",
"ax1",
",",
"ax2",
")",
":",
"b1",
",",
"t1",
"=",
"ax1",
".",
"get_position",
"(",
")",
".",
"intervaly",
"b2",
",",
"t2",
"=",
"ax2",
".",
"get_position",
"(",
")",
".",
"intervaly",
"return",
"t1",
">",
"b2",
"and",
... | Tests whether two axes overlap vertically | [
"Tests",
"whether",
"two",
"axes",
"overlap",
"vertically"
] | python | train | 28.285714 |
ga4gh/ga4gh-server | ga4gh/server/backend.py | https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/backend.py#L973-L980 | def runSearchCallSets(self, request):
"""
Runs the specified SearchCallSetsRequest.
"""
return self.runSearchRequest(
request, protocol.SearchCallSetsRequest,
protocol.SearchCallSetsResponse,
self.callSetsGenerator) | [
"def",
"runSearchCallSets",
"(",
"self",
",",
"request",
")",
":",
"return",
"self",
".",
"runSearchRequest",
"(",
"request",
",",
"protocol",
".",
"SearchCallSetsRequest",
",",
"protocol",
".",
"SearchCallSetsResponse",
",",
"self",
".",
"callSetsGenerator",
")"
... | Runs the specified SearchCallSetsRequest. | [
"Runs",
"the",
"specified",
"SearchCallSetsRequest",
"."
] | python | train | 34.5 |
Clinical-Genomics/trailblazer | trailblazer/cli/delete.py | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/cli/delete.py#L12-L46 | def delete(context, force, yes, analysis_id):
"""Delete an analysis log from the database."""
analysis_obj = context.obj['store'].analysis(analysis_id)
if analysis_obj is None:
print(click.style('analysis log not found', fg='red'))
context.abort()
print(click.style(f"{analysis_obj.famil... | [
"def",
"delete",
"(",
"context",
",",
"force",
",",
"yes",
",",
"analysis_id",
")",
":",
"analysis_obj",
"=",
"context",
".",
"obj",
"[",
"'store'",
"]",
".",
"analysis",
"(",
"analysis_id",
")",
"if",
"analysis_obj",
"is",
"None",
":",
"print",
"(",
"... | Delete an analysis log from the database. | [
"Delete",
"an",
"analysis",
"log",
"from",
"the",
"database",
"."
] | python | train | 47.2 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L868-L951 | def convert_docx_to_text(
filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename: filename to process
blob: binary ``bytes`` object to p... | [
"def",
"convert_docx_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"if",
"True",
":",
"text",
"=",
"''",
"with",
"get... | Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename: filename to process
blob: binary ``bytes`` object to process
config: :class:`TextProcessingConfig` control object
Returns:
text contents
Notes:
- Old ``docx`` (https://pypi.py... | [
"Converts",
"a",
"DOCX",
"file",
"to",
"text",
".",
"Pass",
"either",
"a",
"filename",
"or",
"a",
"binary",
"object",
"."
] | python | train | 33.142857 |
spyder-ide/spyder | spyder/plugins/editor/utils/autosave.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/utils/autosave.py#L135-L152 | def create_unique_autosave_filename(self, filename, autosave_dir):
"""
Create unique autosave file name for specified file name.
Args:
filename (str): original file name
autosave_dir (str): directory in which autosave files are stored
"""
basename = osp.b... | [
"def",
"create_unique_autosave_filename",
"(",
"self",
",",
"filename",
",",
"autosave_dir",
")",
":",
"basename",
"=",
"osp",
".",
"basename",
"(",
"filename",
")",
"autosave_filename",
"=",
"osp",
".",
"join",
"(",
"autosave_dir",
",",
"basename",
")",
"if",... | Create unique autosave file name for specified file name.
Args:
filename (str): original file name
autosave_dir (str): directory in which autosave files are stored | [
"Create",
"unique",
"autosave",
"file",
"name",
"for",
"specified",
"file",
"name",
"."
] | python | train | 44 |
upsight/doctor | doctor/types.py | https://github.com/upsight/doctor/blob/2cf1d433f6f1aa1355644b449a757c0660793cdd/doctor/types.py#L914-L922 | def array(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Array` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Array`
"""
kwargs['description'] = description
return type('Array', (A... | [
"def",
"array",
"(",
"description",
",",
"*",
"*",
"kwargs",
")",
"->",
"typing",
".",
"Type",
":",
"kwargs",
"[",
"'description'",
"]",
"=",
"description",
"return",
"type",
"(",
"'Array'",
",",
"(",
"Array",
",",
")",
",",
"kwargs",
")"
] | Create a :class:`~doctor.types.Array` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Array` | [
"Create",
"a",
":",
"class",
":",
"~doctor",
".",
"types",
".",
"Array",
"type",
"."
] | python | train | 36.333333 |
Chilipp/funcargparse | funcargparse/__init__.py | https://github.com/Chilipp/funcargparse/blob/398ce8e7fa5aa35c465215446bda151cf1ecf7ad/funcargparse/__init__.py#L721-L755 | def update_short(self, **kwargs):
"""
Update the short optional arguments (those with one leading '-')
This method updates the short argument name for the specified function
arguments as stored in :attr:`unfinished_arguments`
Parameters
----------
``**kwargs``
... | [
"def",
"update_short",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"kwargs",
")",
":",
"self",
".",
"update_arg",
"(",
"key",
",",
"short",
"=",
"val",
")"
] | Update the short optional arguments (those with one leading '-')
This method updates the short argument name for the specified function
arguments as stored in :attr:`unfinished_arguments`
Parameters
----------
``**kwargs``
Keywords must be keys in the :attr:`unfinis... | [
"Update",
"the",
"short",
"optional",
"arguments",
"(",
"those",
"with",
"one",
"leading",
"-",
")"
] | python | train | 31.2 |
pip-services3-python/pip-services3-commons-python | pip_services3_commons/refer/DependencyResolver.py | https://github.com/pip-services3-python/pip-services3-commons-python/blob/22cbbb3e91e49717f65c083d36147fdb07ba9e3b/pip_services3_commons/refer/DependencyResolver.py#L167-L176 | def get_one_optional(self, name):
"""
Gets one optional dependency by its name.
:param name: the dependency name to locate.
:return: a dependency reference or null of the dependency was not found
"""
locator = self._locate(name)
return self._references.get_one_o... | [
"def",
"get_one_optional",
"(",
"self",
",",
"name",
")",
":",
"locator",
"=",
"self",
".",
"_locate",
"(",
"name",
")",
"return",
"self",
".",
"_references",
".",
"get_one_optional",
"(",
"locator",
")",
"if",
"locator",
"!=",
"None",
"else",
"None"
] | Gets one optional dependency by its name.
:param name: the dependency name to locate.
:return: a dependency reference or null of the dependency was not found | [
"Gets",
"one",
"optional",
"dependency",
"by",
"its",
"name",
"."
] | python | train | 35.6 |
coopernurse/barrister | barrister/docco.py | https://github.com/coopernurse/barrister/blob/0471b1d98d3327ba381684db496ec94c79c20848/barrister/docco.py#L312-L352 | def parse_struct(s):
"""
Returns a docco section for the given struct.
:Parameters:
s
Parsed IDL struct dict. Keys: 'comment', 'name', 'extends', 'fields'
"""
docs = s['comment']
code = '<span class="k">struct</span> <span class="gs">%s</span>' % s['name']
if s['extends']:
... | [
"def",
"parse_struct",
"(",
"s",
")",
":",
"docs",
"=",
"s",
"[",
"'comment'",
"]",
"code",
"=",
"'<span class=\"k\">struct</span> <span class=\"gs\">%s</span>'",
"%",
"s",
"[",
"'name'",
"]",
"if",
"s",
"[",
"'extends'",
"]",
":",
"code",
"+=",
"' extends <sp... | Returns a docco section for the given struct.
:Parameters:
s
Parsed IDL struct dict. Keys: 'comment', 'name', 'extends', 'fields' | [
"Returns",
"a",
"docco",
"section",
"for",
"the",
"given",
"struct",
"."
] | python | train | 30.878049 |
inasafe/inasafe | safe/gui/tools/options_dialog.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/options_dialog.py#L498-L507 | def open_user_directory_path(self):
"""Open File dialog to choose the user directory path."""
# noinspection PyCallByClass,PyTypeChecker
directory_name = QFileDialog.getExistingDirectory(
self,
self.tr('Results directory'),
self.leUserDirectoryPath.text(),
... | [
"def",
"open_user_directory_path",
"(",
"self",
")",
":",
"# noinspection PyCallByClass,PyTypeChecker",
"directory_name",
"=",
"QFileDialog",
".",
"getExistingDirectory",
"(",
"self",
",",
"self",
".",
"tr",
"(",
"'Results directory'",
")",
",",
"self",
".",
"leUserDi... | Open File dialog to choose the user directory path. | [
"Open",
"File",
"dialog",
"to",
"choose",
"the",
"user",
"directory",
"path",
"."
] | python | train | 43.3 |
Genida/archan | src/archan/plugins/checkers.py | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/plugins/checkers.py#L414-L444 | def check(self, dsm, **kwargs):
"""
Check layered architecture.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
Returns:
bool, str: True if layered architecture else False, messages
"""
layered_architecture = True
messages =... | [
"def",
"check",
"(",
"self",
",",
"dsm",
",",
"*",
"*",
"kwargs",
")",
":",
"layered_architecture",
"=",
"True",
"messages",
"=",
"[",
"]",
"categories",
"=",
"dsm",
".",
"categories",
"dsm_size",
"=",
"dsm",
".",
"size",
"[",
"0",
"]",
"if",
"not",
... | Check layered architecture.
Args:
dsm (:class:`DesignStructureMatrix`): the DSM to check.
Returns:
bool, str: True if layered architecture else False, messages | [
"Check",
"layered",
"architecture",
"."
] | python | train | 35.83871 |
apache/incubator-mxnet | python/mxnet/ndarray/ndarray.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/ndarray.py#L3884-L3908 | def empty(shape, ctx=None, dtype=None):
"""Returns a new array of given shape and type, without initializing entries.
Parameters
----------
shape : int or tuple of int
The shape of the empty array.
ctx : Context, optional
An optional device context (default is the current default co... | [
"def",
"empty",
"(",
"shape",
",",
"ctx",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"shape",
",",
"int",
")",
":",
"shape",
"=",
"(",
"shape",
",",
")",
"if",
"ctx",
"is",
"None",
":",
"ctx",
"=",
"current_context... | Returns a new array of given shape and type, without initializing entries.
Parameters
----------
shape : int or tuple of int
The shape of the empty array.
ctx : Context, optional
An optional device context (default is the current default context).
dtype : str or numpy.dtype, optiona... | [
"Returns",
"a",
"new",
"array",
"of",
"given",
"shape",
"and",
"type",
"without",
"initializing",
"entries",
"."
] | python | train | 27.92 |
refenv/cijoe | deprecated/modules/cij/spdk.py | https://github.com/refenv/cijoe/blob/21d7b2ed4ff68e0a1457e7df2db27f6334f1a379/deprecated/modules/cij/spdk.py#L117-L121 | def vblk_erase(self, address):
"""nvm_vblk erase"""
cmd = ["nvm_vblk erase", self.envs, "0x%x" % address]
status, _, _ = cij.ssh.command(cmd, shell=True)
return status | [
"def",
"vblk_erase",
"(",
"self",
",",
"address",
")",
":",
"cmd",
"=",
"[",
"\"nvm_vblk erase\"",
",",
"self",
".",
"envs",
",",
"\"0x%x\"",
"%",
"address",
"]",
"status",
",",
"_",
",",
"_",
"=",
"cij",
".",
"ssh",
".",
"command",
"(",
"cmd",
","... | nvm_vblk erase | [
"nvm_vblk",
"erase"
] | python | valid | 39.8 |
marcinmiklitz/pywindow | pywindow/utilities.py | https://github.com/marcinmiklitz/pywindow/blob/e5264812157224f22a691741ca2e0aefdc9bd2eb/pywindow/utilities.py#L397-L419 | def shift_com(elements, coordinates, com_adjust=np.zeros(3)):
"""
Return coordinates translated by some vector.
Parameters
----------
elements : numpy.ndarray
An array of all elements (type: str) in a molecule.
coordinates : numpy.ndarray
An array containing molecule's coordina... | [
"def",
"shift_com",
"(",
"elements",
",",
"coordinates",
",",
"com_adjust",
"=",
"np",
".",
"zeros",
"(",
"3",
")",
")",
":",
"com",
"=",
"center_of_mass",
"(",
"elements",
",",
"coordinates",
")",
"com",
"=",
"np",
".",
"array",
"(",
"[",
"com",
"-"... | Return coordinates translated by some vector.
Parameters
----------
elements : numpy.ndarray
An array of all elements (type: str) in a molecule.
coordinates : numpy.ndarray
An array containing molecule's coordinates.
com_adjust : numpy.ndarray (default = [0, 0, 0])
Returns
... | [
"Return",
"coordinates",
"translated",
"by",
"some",
"vector",
"."
] | python | train | 26.043478 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/parallel/controller/scheduler.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/scheduler.py#L701-L707 | def add_job(self, idx):
"""Called after self.targets[idx] just got the job with header.
Override with subclasses. The default ordering is simple LRU.
The default loads are the number of outstanding jobs."""
self.loads[idx] += 1
for lis in (self.targets, self.loads):
... | [
"def",
"add_job",
"(",
"self",
",",
"idx",
")",
":",
"self",
".",
"loads",
"[",
"idx",
"]",
"+=",
"1",
"for",
"lis",
"in",
"(",
"self",
".",
"targets",
",",
"self",
".",
"loads",
")",
":",
"lis",
".",
"append",
"(",
"lis",
".",
"pop",
"(",
"i... | Called after self.targets[idx] just got the job with header.
Override with subclasses. The default ordering is simple LRU.
The default loads are the number of outstanding jobs. | [
"Called",
"after",
"self",
".",
"targets",
"[",
"idx",
"]",
"just",
"got",
"the",
"job",
"with",
"header",
".",
"Override",
"with",
"subclasses",
".",
"The",
"default",
"ordering",
"is",
"simple",
"LRU",
".",
"The",
"default",
"loads",
"are",
"the",
"num... | python | test | 48.285714 |
IdentityPython/pysaml2 | src/saml2/client.py | https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/client.py#L42-L80 | def prepare_for_authenticate(
self, entityid=None, relay_state="",
binding=saml2.BINDING_HTTP_REDIRECT, vorg="", nameid_format=None,
scoping=None, consent=None, extensions=None, sign=None,
response_binding=saml2.BINDING_HTTP_POST, **kwargs):
""" Makes all necessar... | [
"def",
"prepare_for_authenticate",
"(",
"self",
",",
"entityid",
"=",
"None",
",",
"relay_state",
"=",
"\"\"",
",",
"binding",
"=",
"saml2",
".",
"BINDING_HTTP_REDIRECT",
",",
"vorg",
"=",
"\"\"",
",",
"nameid_format",
"=",
"None",
",",
"scoping",
"=",
"None... | Makes all necessary preparations for an authentication request.
:param entityid: The entity ID of the IdP to send the request to
:param relay_state: To where the user should be returned after
successfull log in.
:param binding: Which binding to use for sending the request
:p... | [
"Makes",
"all",
"necessary",
"preparations",
"for",
"an",
"authentication",
"request",
"."
] | python | train | 43.051282 |
sosy-lab/benchexec | benchexec/tablegenerator/util.py | https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/tablegenerator/util.py#L81-L97 | def open_url_seekable(path_url, mode='rt'):
"""Open a URL and ensure that the result is seekable,
copying it into a buffer if necessary."""
logging.debug("Making request to '%s'", path_url)
response = urllib.request.urlopen(path_url)
logging.debug("Got response %s", response.info())
try:
... | [
"def",
"open_url_seekable",
"(",
"path_url",
",",
"mode",
"=",
"'rt'",
")",
":",
"logging",
".",
"debug",
"(",
"\"Making request to '%s'\"",
",",
"path_url",
")",
"response",
"=",
"urllib",
".",
"request",
".",
"urlopen",
"(",
"path_url",
")",
"logging",
"."... | Open a URL and ensure that the result is seekable,
copying it into a buffer if necessary. | [
"Open",
"a",
"URL",
"and",
"ensure",
"that",
"the",
"result",
"is",
"seekable",
"copying",
"it",
"into",
"a",
"buffer",
"if",
"necessary",
"."
] | python | train | 32.294118 |
wummel/linkchecker | linkcheck/cache/urlqueue.py | https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/cache/urlqueue.py#L180-L201 | def join (self, timeout=None):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all... | [
"def",
"join",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"with",
"self",
".",
"all_tasks_done",
":",
"if",
"timeout",
"is",
"None",
":",
"while",
"self",
".",
"unfinished_tasks",
":",
"self",
".",
"all_tasks_done",
".",
"wait",
"(",
")",
"els... | Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the... | [
"Blocks",
"until",
"all",
"items",
"in",
"the",
"Queue",
"have",
"been",
"gotten",
"and",
"processed",
"."
] | python | train | 44.136364 |
ray-project/ray | python/ray/node.py | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/node.py#L692-L703 | def live_processes(self):
"""Return a list of the live processes.
Returns:
A list of the live processes.
"""
result = []
for process_type, process_infos in self.all_processes.items():
for process_info in process_infos:
if process_info.proc... | [
"def",
"live_processes",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"process_type",
",",
"process_infos",
"in",
"self",
".",
"all_processes",
".",
"items",
"(",
")",
":",
"for",
"process_info",
"in",
"process_infos",
":",
"if",
"process_info",
... | Return a list of the live processes.
Returns:
A list of the live processes. | [
"Return",
"a",
"list",
"of",
"the",
"live",
"processes",
"."
] | python | train | 35.166667 |
openstack/horizon | openstack_dashboard/api/_nova.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/openstack_dashboard/api/_nova.py#L99-L111 | def get_auth_params_from_request(request):
"""Extracts properties needed by novaclient call from the request object.
These will be used to memoize the calls to novaclient.
"""
return (
request.user.username,
request.user.token.id,
request.user.tenant_id,
request.user.tok... | [
"def",
"get_auth_params_from_request",
"(",
"request",
")",
":",
"return",
"(",
"request",
".",
"user",
".",
"username",
",",
"request",
".",
"user",
".",
"token",
".",
"id",
",",
"request",
".",
"user",
".",
"tenant_id",
",",
"request",
".",
"user",
"."... | Extracts properties needed by novaclient call from the request object.
These will be used to memoize the calls to novaclient. | [
"Extracts",
"properties",
"needed",
"by",
"novaclient",
"call",
"from",
"the",
"request",
"object",
"."
] | python | train | 32.769231 |
pypa/setuptools | setuptools/msvc.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/msvc.py#L559-L573 | def _guess_vc(self):
"""
Locate Visual C for 2017
"""
if self.vc_ver <= 14.0:
return
default = r'VC\Tools\MSVC'
guess_vc = os.path.join(self.VSInstallDir, default)
# Subdir with VC exact version as name
try:
vc_exact_ver = os.listd... | [
"def",
"_guess_vc",
"(",
"self",
")",
":",
"if",
"self",
".",
"vc_ver",
"<=",
"14.0",
":",
"return",
"default",
"=",
"r'VC\\Tools\\MSVC'",
"guess_vc",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"VSInstallDir",
",",
"default",
")",
"# Subdir w... | Locate Visual C for 2017 | [
"Locate",
"Visual",
"C",
"for",
"2017"
] | python | train | 29.466667 |
brocade/pynos | pynos/versions/base/yang/ietf_netconf.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/yang/ietf_netconf.py#L484-L494 | def commit_input_confirmed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
commit = ET.Element("commit")
config = commit
input = ET.SubElement(commit, "input")
confirmed = ET.SubElement(input, "confirmed")
callback = kwargs.pop('... | [
"def",
"commit_input_confirmed",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"commit",
"=",
"ET",
".",
"Element",
"(",
"\"commit\"",
")",
"config",
"=",
"commit",
"input",
"=",
"ET",
".",... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 33.454545 |
sorend/sshconf | sshconf.py | https://github.com/sorend/sshconf/blob/59f3fc165b1ba9e76ba23444b1205d88462938f3/sshconf.py#L112-L118 | def read_ssh_config(path):
"""
Read ssh config file and return parsed SshConfig
"""
with open(path, "r") as fh_:
lines = fh_.read().splitlines()
return SshConfig(lines) | [
"def",
"read_ssh_config",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"r\"",
")",
"as",
"fh_",
":",
"lines",
"=",
"fh_",
".",
"read",
"(",
")",
".",
"splitlines",
"(",
")",
"return",
"SshConfig",
"(",
"lines",
")"
] | Read ssh config file and return parsed SshConfig | [
"Read",
"ssh",
"config",
"file",
"and",
"return",
"parsed",
"SshConfig"
] | python | train | 27.142857 |
senaite/senaite.jsonapi | src/senaite/jsonapi/api.py | https://github.com/senaite/senaite.jsonapi/blob/871959f4b1c9edbb477e9456325527ca78e13ec6/src/senaite/jsonapi/api.py#L279-L338 | def get_info(brain_or_object, endpoint=None, complete=False):
"""Extract the data from the catalog brain or object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param endpoint: The named URL endpoint for the root... | [
"def",
"get_info",
"(",
"brain_or_object",
",",
"endpoint",
"=",
"None",
",",
"complete",
"=",
"False",
")",
":",
"# also extract the brain data for objects",
"if",
"not",
"is_brain",
"(",
"brain_or_object",
")",
":",
"brain_or_object",
"=",
"get_brain",
"(",
"bra... | Extract the data from the catalog brain or object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param endpoint: The named URL endpoint for the root of the items
:type endpoint: str/unicode
:param complete: Fl... | [
"Extract",
"the",
"data",
"from",
"the",
"catalog",
"brain",
"or",
"object"
] | python | train | 37.566667 |
fermiPy/fermipy | fermipy/diffuse/source_factory.py | https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/source_factory.py#L21-L31 | def make_spatialmap_source(name, Spatial_Filename, spectrum):
"""Construct and return a `fermipy.roi_model.Source` object
"""
data = dict(Spatial_Filename=Spatial_Filename,
ra=0.0, dec=0.0,
SpatialType='SpatialMap',
Source_Name=name)
if spectrum is not No... | [
"def",
"make_spatialmap_source",
"(",
"name",
",",
"Spatial_Filename",
",",
"spectrum",
")",
":",
"data",
"=",
"dict",
"(",
"Spatial_Filename",
"=",
"Spatial_Filename",
",",
"ra",
"=",
"0.0",
",",
"dec",
"=",
"0.0",
",",
"SpatialType",
"=",
"'SpatialMap'",
"... | Construct and return a `fermipy.roi_model.Source` object | [
"Construct",
"and",
"return",
"a",
"fermipy",
".",
"roi_model",
".",
"Source",
"object"
] | python | train | 34.909091 |
UDST/orca | orca/orca.py | https://github.com/UDST/orca/blob/07b34aeef13cc87c966b2e30cbe7e76cc9d3622c/orca/orca.py#L1356-L1381 | def injectable(
name=None, autocall=True, cache=False, cache_scope=_CS_FOREVER,
memoize=False):
"""
Decorates functions that will be injected into other functions.
Decorator version of `add_injectable`. Name defaults to
name of function.
The function's argument names and keyword ar... | [
"def",
"injectable",
"(",
"name",
"=",
"None",
",",
"autocall",
"=",
"True",
",",
"cache",
"=",
"False",
",",
"cache_scope",
"=",
"_CS_FOREVER",
",",
"memoize",
"=",
"False",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"if",
"name",
":",
"n"... | Decorates functions that will be injected into other functions.
Decorator version of `add_injectable`. Name defaults to
name of function.
The function's argument names and keyword argument values
will be matched to registered variables when the function
needs to be evaluated by Orca.
The argum... | [
"Decorates",
"functions",
"that",
"will",
"be",
"injected",
"into",
"other",
"functions",
"."
] | python | train | 30.423077 |
ossobv/dutree | dutree/dutree.py | https://github.com/ossobv/dutree/blob/adceeeb17f9fd70a7ed9c674850d7015d820eb2a/dutree/dutree.py#L217-L258 | def merge_upwards_if_smaller_than(self, small_size, a_or_u):
"""After prune_if_smaller_than is run, we may still have excess
nodes.
For example, with a small_size of 609710690:
7 /*
28815419 /data/*
32 /data/srv/*
925746... | [
"def",
"merge_upwards_if_smaller_than",
"(",
"self",
",",
"small_size",
",",
"a_or_u",
")",
":",
"# Assert that we're not messing things up.",
"prev_app_size",
"=",
"self",
".",
"app_size",
"(",
")",
"prev_use_size",
"=",
"self",
".",
"use_size",
"(",
")",
"small_no... | After prune_if_smaller_than is run, we may still have excess
nodes.
For example, with a small_size of 609710690:
7 /*
28815419 /data/*
32 /data/srv/*
925746 /data/srv/docker.bak/*
12 /data/srv/docker.bak/sh... | [
"After",
"prune_if_smaller_than",
"is",
"run",
"we",
"may",
"still",
"have",
"excess",
"nodes",
"."
] | python | train | 37.47619 |
lappis-unb/salic-ml | src/salicml/metrics/finance/new_providers.py | https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/new_providers.py#L101-L114 | def providers_count(df):
"""
Returns total occurrences of each provider
in the database.
"""
providers_count = {}
cnpj_array = df.values
for a in cnpj_array:
cnpj = a[0]
occurrences = providers_count.get(cnpj, 0)
providers_count[cnpj] = occurrences + 1
return pd... | [
"def",
"providers_count",
"(",
"df",
")",
":",
"providers_count",
"=",
"{",
"}",
"cnpj_array",
"=",
"df",
".",
"values",
"for",
"a",
"in",
"cnpj_array",
":",
"cnpj",
"=",
"a",
"[",
"0",
"]",
"occurrences",
"=",
"providers_count",
".",
"get",
"(",
"cnpj... | Returns total occurrences of each provider
in the database. | [
"Returns",
"total",
"occurrences",
"of",
"each",
"provider",
"in",
"the",
"database",
"."
] | python | train | 25.714286 |
Chilipp/psyplot | psyplot/project.py | https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L1415-L1428 | def load_figure(d, new_fig=True):
"""Create a figure from what is returned by :meth:`inspect_figure`"""
import matplotlib.pyplot as plt
subplotpars = d.pop('subplotpars', None)
if subplotpars is not None:
subplotpars.pop('validate', None)
subplotpars = mfig.Subplo... | [
"def",
"load_figure",
"(",
"d",
",",
"new_fig",
"=",
"True",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"subplotpars",
"=",
"d",
".",
"pop",
"(",
"'subplotpars'",
",",
"None",
")",
"if",
"subplotpars",
"is",
"not",
"None",
":",
"subp... | Create a figure from what is returned by :meth:`inspect_figure` | [
"Create",
"a",
"figure",
"from",
"what",
"is",
"returned",
"by",
":",
"meth",
":",
"inspect_figure"
] | python | train | 44.428571 |
rsmuc/health_monitoring_plugins | health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py | https://github.com/rsmuc/health_monitoring_plugins/blob/7ac29dfb9fe46c055b018cb72ad0d7d8065589b9/health_monitoring_plugins/check_snmp_eaton_ups/check_snmp_eaton_ups.py#L61-L75 | def check_ups_estimated_minutes_remaining(the_session, the_helper, the_snmp_value):
"""
OID .1.3.6.1.2.1.33.1.2.3.0
MIB excerpt
An estimate of the time to battery charge depletion
under the present load conditions if the utility power
is off and remains off, or if it were to be lost and
rema... | [
"def",
"check_ups_estimated_minutes_remaining",
"(",
"the_session",
",",
"the_helper",
",",
"the_snmp_value",
")",
":",
"the_helper",
".",
"add_metric",
"(",
"label",
"=",
"the_helper",
".",
"options",
".",
"type",
",",
"value",
"=",
"the_snmp_value",
",",
"uom",
... | OID .1.3.6.1.2.1.33.1.2.3.0
MIB excerpt
An estimate of the time to battery charge depletion
under the present load conditions if the utility power
is off and remains off, or if it were to be lost and
remain off. | [
"OID",
".",
"1",
".",
"3",
".",
"6",
".",
"1",
".",
"2",
".",
"1",
".",
"33",
".",
"1",
".",
"2",
".",
"3",
".",
"0",
"MIB",
"excerpt",
"An",
"estimate",
"of",
"the",
"time",
"to",
"battery",
"charge",
"depletion",
"under",
"the",
"present",
... | python | train | 35.8 |
clarete/curdling | curdling/index.py | https://github.com/clarete/curdling/blob/27c160ea0adad2771bee12c48a57208a1a3c4d9a/curdling/index.py#L114-L124 | def package_releases(self, package, url_fmt=lambda u: u):
"""List all versions of a package
Along with the version, the caller also receives the file list with all
the available formats.
"""
return [{
'name': package,
'version': version,
'urls... | [
"def",
"package_releases",
"(",
"self",
",",
"package",
",",
"url_fmt",
"=",
"lambda",
"u",
":",
"u",
")",
":",
"return",
"[",
"{",
"'name'",
":",
"package",
",",
"'version'",
":",
"version",
",",
"'urls'",
":",
"[",
"self",
".",
"get_urlhash",
"(",
... | List all versions of a package
Along with the version, the caller also receives the file list with all
the available formats. | [
"List",
"all",
"versions",
"of",
"a",
"package"
] | python | train | 39 |
chrismattmann/tika-python | tika/detector.py | https://github.com/chrismattmann/tika-python/blob/ffd3879ac3eaa9142c0fb6557cc1dc52d458a75a/tika/detector.py#L30-L38 | def from_buffer(string, config_path=None):
'''
Detects MIME type of the buffered content
:param string: buffered content whose type needs to be detected
:return:
'''
status, response = callServer('put', ServerEndpoint, '/detect/stream', string,
{'Accept': 'text/... | [
"def",
"from_buffer",
"(",
"string",
",",
"config_path",
"=",
"None",
")",
":",
"status",
",",
"response",
"=",
"callServer",
"(",
"'put'",
",",
"ServerEndpoint",
",",
"'/detect/stream'",
",",
"string",
",",
"{",
"'Accept'",
":",
"'text/plain'",
"}",
",",
... | Detects MIME type of the buffered content
:param string: buffered content whose type needs to be detected
:return: | [
"Detects",
"MIME",
"type",
"of",
"the",
"buffered",
"content",
":",
"param",
"string",
":",
"buffered",
"content",
"whose",
"type",
"needs",
"to",
"be",
"detected",
":",
"return",
":"
] | python | train | 41.333333 |
gamechanger/dusty | dusty/systems/virtualbox/__init__.py | https://github.com/gamechanger/dusty/blob/dc12de90bb6945023d6f43a8071e984313a1d984/dusty/systems/virtualbox/__init__.py#L64-L71 | def _dusty_vm_exists():
"""We use VBox directly instead of Docker Machine because it
shaves about 0.5 seconds off the runtime of this check."""
existing_vms = check_output_demoted(['VBoxManage', 'list', 'vms'])
for line in existing_vms.splitlines():
if '"{}"'.format(constants.VM_MACHINE_NAME) in... | [
"def",
"_dusty_vm_exists",
"(",
")",
":",
"existing_vms",
"=",
"check_output_demoted",
"(",
"[",
"'VBoxManage'",
",",
"'list'",
",",
"'vms'",
"]",
")",
"for",
"line",
"in",
"existing_vms",
".",
"splitlines",
"(",
")",
":",
"if",
"'\"{}\"'",
".",
"format",
... | We use VBox directly instead of Docker Machine because it
shaves about 0.5 seconds off the runtime of this check. | [
"We",
"use",
"VBox",
"directly",
"instead",
"of",
"Docker",
"Machine",
"because",
"it",
"shaves",
"about",
"0",
".",
"5",
"seconds",
"off",
"the",
"runtime",
"of",
"this",
"check",
"."
] | python | valid | 45 |
MillionIntegrals/vel | vel/models/vision/cifar_resnet_v2.py | https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/models/vision/cifar_resnet_v2.py#L77-L81 | def metrics(self):
""" Set of metrics for this model """
from vel.metrics.loss_metric import Loss
from vel.metrics.accuracy import Accuracy
return [Loss(), Accuracy()] | [
"def",
"metrics",
"(",
"self",
")",
":",
"from",
"vel",
".",
"metrics",
".",
"loss_metric",
"import",
"Loss",
"from",
"vel",
".",
"metrics",
".",
"accuracy",
"import",
"Accuracy",
"return",
"[",
"Loss",
"(",
")",
",",
"Accuracy",
"(",
")",
"]"
] | Set of metrics for this model | [
"Set",
"of",
"metrics",
"for",
"this",
"model"
] | python | train | 39 |
yymao/generic-catalog-reader | GCR/base.py | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L306-L311 | def add_modifier_on_derived_quantities(self, new_quantity, func, *quantities):
"""
Deprecated. Use `add_derived_quantity` instead.
"""
warnings.warn("Use `add_derived_quantity` instead.", DeprecationWarning)
self.add_derived_quantity(new_quantity, func, *quantities) | [
"def",
"add_modifier_on_derived_quantities",
"(",
"self",
",",
"new_quantity",
",",
"func",
",",
"*",
"quantities",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Use `add_derived_quantity` instead.\"",
",",
"DeprecationWarning",
")",
"self",
".",
"add_derived_quantity",
... | Deprecated. Use `add_derived_quantity` instead. | [
"Deprecated",
".",
"Use",
"add_derived_quantity",
"instead",
"."
] | python | train | 50.166667 |
rsheftel/raccoon | raccoon/dataframe.py | https://github.com/rsheftel/raccoon/blob/e5c4b5fb933b51f33aff11e8168c39790e9a7c75/raccoon/dataframe.py#L876-L886 | def rename_columns(self, rename_dict):
"""
Renames the columns
:param rename_dict: dict where the keys are the current column names and the values are the new names
:return: nothing
"""
if not all([x in self._columns for x in rename_dict.keys()]):
raise Value... | [
"def",
"rename_columns",
"(",
"self",
",",
"rename_dict",
")",
":",
"if",
"not",
"all",
"(",
"[",
"x",
"in",
"self",
".",
"_columns",
"for",
"x",
"in",
"rename_dict",
".",
"keys",
"(",
")",
"]",
")",
":",
"raise",
"ValueError",
"(",
"'all dictionary ke... | Renames the columns
:param rename_dict: dict where the keys are the current column names and the values are the new names
:return: nothing | [
"Renames",
"the",
"columns"
] | python | train | 44.272727 |
ncclient/ncclient | ncclient/operations/retrieve.py | https://github.com/ncclient/ncclient/blob/2b75f2c6a06bd2a5d1be67b01bb65c5ffd2e2d7a/ncclient/operations/retrieve.py#L72-L91 | def request(self, filter=None, with_defaults=None):
"""Retrieve running configuration and device state information.
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
*with_defaults* defines an explicit method of retrieving default va... | [
"def",
"request",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"with_defaults",
"=",
"None",
")",
":",
"node",
"=",
"new_ele",
"(",
"\"get\"",
")",
"if",
"filter",
"is",
"not",
"None",
":",
"node",
".",
"append",
"(",
"util",
".",
"build_filter",
"(... | Retrieve running configuration and device state information.
*filter* specifies the portion of the configuration to retrieve (by default entire configuration is retrieved)
*with_defaults* defines an explicit method of retrieving default values from the configuration (see RFC 6243)
:seealso: :... | [
"Retrieve",
"running",
"configuration",
"and",
"device",
"state",
"information",
"."
] | python | train | 39.05 |
smnorris/bcdata | bcdata/wfs.py | https://github.com/smnorris/bcdata/blob/de6b5bbc28d85e36613b51461911ee0a72a146c5/bcdata/wfs.py#L170-L189 | def get_data(
dataset,
query=None,
crs="epsg:4326",
bounds=None,
sortby=None,
pagesize=10000,
max_workers=5,
):
"""Get GeoJSON featurecollection from DataBC WFS
"""
param_dicts = define_request(dataset, query, crs, bounds, sortby, pagesize)
with ThreadPoolExecutor(max_worker... | [
"def",
"get_data",
"(",
"dataset",
",",
"query",
"=",
"None",
",",
"crs",
"=",
"\"epsg:4326\"",
",",
"bounds",
"=",
"None",
",",
"sortby",
"=",
"None",
",",
"pagesize",
"=",
"10000",
",",
"max_workers",
"=",
"5",
",",
")",
":",
"param_dicts",
"=",
"d... | Get GeoJSON featurecollection from DataBC WFS | [
"Get",
"GeoJSON",
"featurecollection",
"from",
"DataBC",
"WFS"
] | python | train | 26.45 |
AnthonyBloomer/daftlistings | daftlistings/listing.py | https://github.com/AnthonyBloomer/daftlistings/blob/f6c1b52425bc740f443b5efe6632a4bf18ee997f/daftlistings/listing.py#L266-L286 | def images(self):
"""
This method returns the listing image.
:return:
"""
try:
uls = self._ad_page_content.find(
"ul", {"class": "smi-gallery-list"})
except Exception as e:
if self._debug:
logging.error(
... | [
"def",
"images",
"(",
"self",
")",
":",
"try",
":",
"uls",
"=",
"self",
".",
"_ad_page_content",
".",
"find",
"(",
"\"ul\"",
",",
"{",
"\"class\"",
":",
"\"smi-gallery-list\"",
"}",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"self",
".",
"_debug... | This method returns the listing image.
:return: | [
"This",
"method",
"returns",
"the",
"listing",
"image",
".",
":",
"return",
":"
] | python | train | 28.285714 |
Becksteinlab/GromacsWrapper | gromacs/qsub.py | https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/qsub.py#L251-L279 | def array(self, directories):
"""Return multiline string for simple array jobs over *directories*.
.. Warning:: The string is in ``bash`` and hence the template must also
be ``bash`` (and *not* ``csh`` or ``sh``).
"""
if not self.has_arrays():
raise NotI... | [
"def",
"array",
"(",
"self",
",",
"directories",
")",
":",
"if",
"not",
"self",
".",
"has_arrays",
"(",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Not known how make array jobs for '",
"'queuing system %(name)s'",
"%",
"vars",
"(",
"self",
")",
")",
"hrule... | Return multiline string for simple array jobs over *directories*.
.. Warning:: The string is in ``bash`` and hence the template must also
be ``bash`` (and *not* ``csh`` or ``sh``). | [
"Return",
"multiline",
"string",
"for",
"simple",
"array",
"jobs",
"over",
"*",
"directories",
"*",
"."
] | python | valid | 41.482759 |
spyder-ide/spyder | spyder/widgets/comboboxes.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/widgets/comboboxes.py#L357-L360 | def selected(self):
"""Action to be executed when a valid item has been selected"""
EditableComboBox.selected(self)
self.open_dir.emit(self.currentText()) | [
"def",
"selected",
"(",
"self",
")",
":",
"EditableComboBox",
".",
"selected",
"(",
"self",
")",
"self",
".",
"open_dir",
".",
"emit",
"(",
"self",
".",
"currentText",
"(",
")",
")"
] | Action to be executed when a valid item has been selected | [
"Action",
"to",
"be",
"executed",
"when",
"a",
"valid",
"item",
"has",
"been",
"selected"
] | python | train | 44.5 |
gwpy/gwpy | gwpy/io/gwf.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/io/gwf.py#L72-L96 | def open_gwf(filename, mode='r'):
"""Open a filename for reading or writing GWF format data
Parameters
----------
filename : `str`
the path to read from, or write to
mode : `str`, optional
either ``'r'`` (read) or ``'w'`` (write)
Returns
-------
`LDAStools.frameCPP.IFr... | [
"def",
"open_gwf",
"(",
"filename",
",",
"mode",
"=",
"'r'",
")",
":",
"if",
"mode",
"not",
"in",
"(",
"'r'",
",",
"'w'",
")",
":",
"raise",
"ValueError",
"(",
"\"mode must be either 'r' or 'w'\"",
")",
"from",
"LDAStools",
"import",
"frameCPP",
"filename",
... | Open a filename for reading or writing GWF format data
Parameters
----------
filename : `str`
the path to read from, or write to
mode : `str`, optional
either ``'r'`` (read) or ``'w'`` (write)
Returns
-------
`LDAStools.frameCPP.IFrameFStream`
the input frame strea... | [
"Open",
"a",
"filename",
"for",
"reading",
"or",
"writing",
"GWF",
"format",
"data"
] | python | train | 31.04 |
numenta/htmresearch | projects/combined_sequences/combined_sequences.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/projects/combined_sequences/combined_sequences.py#L581-L659 | def runExperimentPool(numSequences,
numFeatures,
numLocations,
numObjects,
numWorkers=7,
nTrials=1,
seqLength=10,
figure="",
numRepetitions=1,
... | [
"def",
"runExperimentPool",
"(",
"numSequences",
",",
"numFeatures",
",",
"numLocations",
",",
"numObjects",
",",
"numWorkers",
"=",
"7",
",",
"nTrials",
"=",
"1",
",",
"seqLength",
"=",
"10",
",",
"figure",
"=",
"\"\"",
",",
"numRepetitions",
"=",
"1",
",... | Run a bunch of experiments using a pool of numWorkers multiple processes. For
numSequences, numFeatures, and numLocations pass in a list containing valid
values for that parameter. The cross product of everything is run, and each
combination is run nTrials times.
Returns a list of dict containing detailed resu... | [
"Run",
"a",
"bunch",
"of",
"experiments",
"using",
"a",
"pool",
"of",
"numWorkers",
"multiple",
"processes",
".",
"For",
"numSequences",
"numFeatures",
"and",
"numLocations",
"pass",
"in",
"a",
"list",
"containing",
"valid",
"values",
"for",
"that",
"parameter",... | python | train | 36.607595 |
quantmind/ccy | ccy/core/country.py | https://github.com/quantmind/ccy/blob/068cf6887489087cd26657a937a932e82106b47f/ccy/core/country.py#L76-L104 | def set_country_map(cfrom, cto, name=None, replace=True):
'''
Set a mapping between a country code to another code
'''
global _country_maps
cdb = countries()
cfrom = str(cfrom).upper()
c = cdb.get(cfrom)
if c:
if name:
c = name
cto = str(cto).upper()
i... | [
"def",
"set_country_map",
"(",
"cfrom",
",",
"cto",
",",
"name",
"=",
"None",
",",
"replace",
"=",
"True",
")",
":",
"global",
"_country_maps",
"cdb",
"=",
"countries",
"(",
")",
"cfrom",
"=",
"str",
"(",
"cfrom",
")",
".",
"upper",
"(",
")",
"c",
... | Set a mapping between a country code to another code | [
"Set",
"a",
"mapping",
"between",
"a",
"country",
"code",
"to",
"another",
"code"
] | python | train | 27.758621 |
pyblish/pyblish-qml | pyblish_qml/vendor/Qt.py | https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/vendor/Qt.py#L901-L928 | def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
src_module, src_member = src.split(".")
dst_module, dst_member = dst.split(".")
... | [
"def",
"_reassign_misplaced_members",
"(",
"binding",
")",
":",
"for",
"src",
",",
"dst",
"in",
"_misplaced_members",
"[",
"binding",
"]",
".",
"items",
"(",
")",
":",
"src_module",
",",
"src_member",
"=",
"src",
".",
"split",
"(",
"\".\"",
")",
"dst_modul... | Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members | [
"Apply",
"misplaced",
"members",
"from",
"binding",
"to",
"Qt",
".",
"py"
] | python | train | 29.107143 |
refindlyllc/rets | rets/parsers/get_object.py | https://github.com/refindlyllc/rets/blob/c615dfc272cff0825fd3b50863c46afc3e33916f/rets/parsers/get_object.py#L39-L73 | def _get_multiparts(response):
"""
From this
'multipart/parallel; boundary="874e43d27ec6d83f30f37841bdaf90c7"; charset=utf-8'
get this
--874e43d27ec6d83f30f37841bdaf90c7
"""
boundary = None
for part in response.headers.get('Content-Type', '').split(';'):
... | [
"def",
"_get_multiparts",
"(",
"response",
")",
":",
"boundary",
"=",
"None",
"for",
"part",
"in",
"response",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"''",
")",
".",
"split",
"(",
"';'",
")",
":",
"if",
"'boundary='",
"in",
"part",
":"... | From this
'multipart/parallel; boundary="874e43d27ec6d83f30f37841bdaf90c7"; charset=utf-8'
get this
--874e43d27ec6d83f30f37841bdaf90c7 | [
"From",
"this",
"multipart",
"/",
"parallel",
";",
"boundary",
"=",
"874e43d27ec6d83f30f37841bdaf90c7",
";",
"charset",
"=",
"utf",
"-",
"8",
"get",
"this",
"--",
"874e43d27ec6d83f30f37841bdaf90c7"
] | python | train | 33.714286 |
PyGithub/PyGithub | github/AuthenticatedUser.py | https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/AuthenticatedUser.py#L692-L702 | def get_followers(self):
"""
:calls: `GET /user/followers <http://developer.github.com/v3/users/followers>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return github.PaginatedList.PaginatedList(
github.NamedUser.Name... | [
"def",
"get_followers",
"(",
"self",
")",
":",
"return",
"github",
".",
"PaginatedList",
".",
"PaginatedList",
"(",
"github",
".",
"NamedUser",
".",
"NamedUser",
",",
"self",
".",
"_requester",
",",
"\"/user/followers\"",
",",
"None",
")"
] | :calls: `GET /user/followers <http://developer.github.com/v3/users/followers>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` | [
":",
"calls",
":",
"GET",
"/",
"user",
"/",
"followers",
"<http",
":",
"//",
"developer",
".",
"github",
".",
"com",
"/",
"v3",
"/",
"users",
"/",
"followers",
">",
"_",
":",
"rtype",
":",
":",
"class",
":",
"github",
".",
"PaginatedList",
".",
"Pa... | python | train | 36.636364 |
tariqdaouda/rabaDB | rabaDB/filters.py | https://github.com/tariqdaouda/rabaDB/blob/42e0d6ee65149ae4f1e4c380cc695a9e7d2d1bbc/rabaDB/filters.py#L155-L192 | def getSQLQuery(self, count = False) :
"Returns the query without performing it. If count, the query returned will be a SELECT COUNT() instead of a SELECT"
sqlFilters = []
sqlValues = []
# print self.filters
for f in self.filters :
filt = []
for k, vv in f.iteritems() :
if type(vv) is types.ListType... | [
"def",
"getSQLQuery",
"(",
"self",
",",
"count",
"=",
"False",
")",
":",
"sqlFilters",
"=",
"[",
"]",
"sqlValues",
"=",
"[",
"]",
"# print self.filters",
"for",
"f",
"in",
"self",
".",
"filters",
":",
"filt",
"=",
"[",
"]",
"for",
"k",
",",
"vv",
"... | Returns the query without performing it. If count, the query returned will be a SELECT COUNT() instead of a SELECT | [
"Returns",
"the",
"query",
"without",
"performing",
"it",
".",
"If",
"count",
"the",
"query",
"returned",
"will",
"be",
"a",
"SELECT",
"COUNT",
"()",
"instead",
"of",
"a",
"SELECT"
] | python | train | 33.342105 |
mrcagney/gtfstk | gtfstk/miscellany.py | https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/miscellany.py#L611-L617 | def compute_convex_hull(feed: "Feed") -> Polygon:
"""
Return a Shapely Polygon representing the convex hull formed by
the stops of the given Feed.
"""
m = sg.MultiPoint(feed.stops[["stop_lon", "stop_lat"]].values)
return m.convex_hull | [
"def",
"compute_convex_hull",
"(",
"feed",
":",
"\"Feed\"",
")",
"->",
"Polygon",
":",
"m",
"=",
"sg",
".",
"MultiPoint",
"(",
"feed",
".",
"stops",
"[",
"[",
"\"stop_lon\"",
",",
"\"stop_lat\"",
"]",
"]",
".",
"values",
")",
"return",
"m",
".",
"conve... | Return a Shapely Polygon representing the convex hull formed by
the stops of the given Feed. | [
"Return",
"a",
"Shapely",
"Polygon",
"representing",
"the",
"convex",
"hull",
"formed",
"by",
"the",
"stops",
"of",
"the",
"given",
"Feed",
"."
] | python | train | 36 |
cloudant/python-cloudant | src/cloudant/document.py | https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/document.py#L81-L104 | def document_url(self):
"""
Constructs and returns the document URL.
:returns: Document URL
"""
if '_id' not in self or self['_id'] is None:
return None
# handle design document url
if self['_id'].startswith('_design/'):
return '/'.join((... | [
"def",
"document_url",
"(",
"self",
")",
":",
"if",
"'_id'",
"not",
"in",
"self",
"or",
"self",
"[",
"'_id'",
"]",
"is",
"None",
":",
"return",
"None",
"# handle design document url",
"if",
"self",
"[",
"'_id'",
"]",
".",
"startswith",
"(",
"'_design/'",
... | Constructs and returns the document URL.
:returns: Document URL | [
"Constructs",
"and",
"returns",
"the",
"document",
"URL",
"."
] | python | train | 28.125 |
dagster-io/dagster | python_modules/dagster/dagster/core/definitions/decorators.py | https://github.com/dagster-io/dagster/blob/4119f8c773089de64831b1dfb9e168e353d401dc/python_modules/dagster/dagster/core/definitions/decorators.py#L173-L271 | def solid(name=None, inputs=None, outputs=None, config_field=None, description=None):
'''(decorator) Create a solid with specified parameters.
This shortcut simplifies the core solid API by exploding arguments into kwargs of the
transform function and omitting additional parameters when they are not needed... | [
"def",
"solid",
"(",
"name",
"=",
"None",
",",
"inputs",
"=",
"None",
",",
"outputs",
"=",
"None",
",",
"config_field",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"# This case is for when decorator is used bare, without arguments. e.g. @solid versus @soli... | (decorator) Create a solid with specified parameters.
This shortcut simplifies the core solid API by exploding arguments into kwargs of the
transform function and omitting additional parameters when they are not needed.
Parameters are otherwise as in the core API, :py:class:`SolidDefinition`.
The deco... | [
"(",
"decorator",
")",
"Create",
"a",
"solid",
"with",
"specified",
"parameters",
"."
] | python | test | 35.909091 |
zeromake/aiosqlite3 | aiosqlite3/pool.py | https://github.com/zeromake/aiosqlite3/blob/1a74a062507e2df8f833a70885e69dca0ab3e7e7/aiosqlite3/pool.py#L194-L211 | def sync_close(self):
"""
同步关闭
"""
if self._closed:
return
while self._free:
conn = self._free.popleft()
if not conn.closed:
# pragma: no cover
conn.sync_close()
for conn in self._used:
if not... | [
"def",
"sync_close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"while",
"self",
".",
"_free",
":",
"conn",
"=",
"self",
".",
"_free",
".",
"popleft",
"(",
")",
"if",
"not",
"conn",
".",
"closed",
":",
"# pragma: no cover",
"... | 同步关闭 | [
"同步关闭"
] | python | train | 26.611111 |
mtomwing/purplex | purplex/grammar.py | https://github.com/mtomwing/purplex/blob/4072109e1d4395826983cd9d95ead2c1dfc1184e/purplex/grammar.py#L94-L108 | def first(self, symbols):
"""Computes the intermediate FIRST set using symbols."""
ret = set()
if EPSILON in symbols:
return set([EPSILON])
for symbol in symbols:
ret |= self._first[symbol] - set([EPSILON])
if EPSILON not in self._first[symbol]:
... | [
"def",
"first",
"(",
"self",
",",
"symbols",
")",
":",
"ret",
"=",
"set",
"(",
")",
"if",
"EPSILON",
"in",
"symbols",
":",
"return",
"set",
"(",
"[",
"EPSILON",
"]",
")",
"for",
"symbol",
"in",
"symbols",
":",
"ret",
"|=",
"self",
".",
"_first",
... | Computes the intermediate FIRST set using symbols. | [
"Computes",
"the",
"intermediate",
"FIRST",
"set",
"using",
"symbols",
"."
] | python | valid | 25.733333 |
google/transitfeed | transitfeed/schedule.py | https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/transitfeed/schedule.py#L87-L90 | def AddTableColumn(self, table, column):
"""Add column to table if it is not already there."""
if column not in self._table_columns[table]:
self._table_columns[table].append(column) | [
"def",
"AddTableColumn",
"(",
"self",
",",
"table",
",",
"column",
")",
":",
"if",
"column",
"not",
"in",
"self",
".",
"_table_columns",
"[",
"table",
"]",
":",
"self",
".",
"_table_columns",
"[",
"table",
"]",
".",
"append",
"(",
"column",
")"
] | Add column to table if it is not already there. | [
"Add",
"column",
"to",
"table",
"if",
"it",
"is",
"not",
"already",
"there",
"."
] | python | train | 48 |
Genida/django-meerkat | src/meerkat/logs/boxes.py | https://github.com/Genida/django-meerkat/blob/486502a75bb0800266db785fd32717d8c0eb8deb/src/meerkat/logs/boxes.py#L118-L127 | def widgets(self):
"""Get the items."""
widgets = []
for i, chart in enumerate(most_visited_pages_charts()):
widgets.append(Widget(html_id='most_visited_chart_%d' % i,
content=json.dumps(chart),
template='meerkat/wid... | [
"def",
"widgets",
"(",
"self",
")",
":",
"widgets",
"=",
"[",
"]",
"for",
"i",
",",
"chart",
"in",
"enumerate",
"(",
"most_visited_pages_charts",
"(",
")",
")",
":",
"widgets",
".",
"append",
"(",
"Widget",
"(",
"html_id",
"=",
"'most_visited_chart_%d'",
... | Get the items. | [
"Get",
"the",
"items",
"."
] | python | train | 44 |
capless/warrant | warrant/__init__.py | https://github.com/capless/warrant/blob/ff2e4793d8479e770f2461ef7cbc0c15ee784395/warrant/__init__.py#L349-L371 | def admin_authenticate(self, password):
"""
Authenticate the user using admin super privileges
:param password: User's password
:return:
"""
auth_params = {
'USERNAME': self.username,
'PASSWORD': password
}
self._add_sec... | [
"def",
"admin_authenticate",
"(",
"self",
",",
"password",
")",
":",
"auth_params",
"=",
"{",
"'USERNAME'",
":",
"self",
".",
"username",
",",
"'PASSWORD'",
":",
"password",
"}",
"self",
".",
"_add_secret_hash",
"(",
"auth_params",
",",
"'SECRET_HASH'",
")",
... | Authenticate the user using admin super privileges
:param password: User's password
:return: | [
"Authenticate",
"the",
"user",
"using",
"admin",
"super",
"privileges",
":",
"param",
"password",
":",
"User",
"s",
"password",
":",
"return",
":"
] | python | train | 43.347826 |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_threshold_monitor.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_threshold_monitor.py#L461-L472 | def threshold_monitor_hidden_threshold_monitor_Cpu_actions(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_moni... | [
"def",
"threshold_monitor_hidden_threshold_monitor_Cpu_actions",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"threshold_monitor_hidden",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"threshold... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train | 51.083333 |
QInfer/python-qinfer | src/qinfer/abstract_model.py | https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/abstract_model.py#L284-L307 | def simulate_experiment(self, modelparams, expparams, repeat=1):
"""
Produces data according to the given model parameters and experimental
parameters, structured as a NumPy array.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
array of model parameter ... | [
"def",
"simulate_experiment",
"(",
"self",
",",
"modelparams",
",",
"expparams",
",",
"repeat",
"=",
"1",
")",
":",
"self",
".",
"_sim_count",
"+=",
"modelparams",
".",
"shape",
"[",
"0",
"]",
"*",
"expparams",
".",
"shape",
"[",
"0",
"]",
"*",
"repeat... | Produces data according to the given model parameters and experimental
parameters, structured as a NumPy array.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
array of model parameter vectors describing the hypotheses under
which data should be simulated.
... | [
"Produces",
"data",
"according",
"to",
"the",
"given",
"model",
"parameters",
"and",
"experimental",
"parameters",
"structured",
"as",
"a",
"NumPy",
"array",
"."
] | python | train | 54.708333 |
singularityhub/singularity-python | singularity/analysis/reproduce/hash.py | https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/analysis/reproduce/hash.py#L166-L175 | def get_image_file_hash(image_path):
'''get_image_hash will return an md5 hash of the file based on a criteria level.
:param level: one of LOW, MEDIUM, HIGH
:param image_path: full path to the singularity image
'''
hasher = hashlib.md5()
with open(image_path, "rb") as f:
for chunk in ite... | [
"def",
"get_image_file_hash",
"(",
"image_path",
")",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"image_path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",... | get_image_hash will return an md5 hash of the file based on a criteria level.
:param level: one of LOW, MEDIUM, HIGH
:param image_path: full path to the singularity image | [
"get_image_hash",
"will",
"return",
"an",
"md5",
"hash",
"of",
"the",
"file",
"based",
"on",
"a",
"criteria",
"level",
".",
":",
"param",
"level",
":",
"one",
"of",
"LOW",
"MEDIUM",
"HIGH",
":",
"param",
"image_path",
":",
"full",
"path",
"to",
"the",
... | python | train | 40.3 |
Azure/blobxfer | blobxfer/operations/download.py | https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/download.py#L685-L703 | def _delete_extraneous_files(self):
# type: (Downloader) -> None
"""Delete extraneous files cataloged
:param Downloader self: this
"""
logger.info('attempting to delete {} extraneous files'.format(
len(self._delete_after)))
for file in self._delete_after:
... | [
"def",
"_delete_extraneous_files",
"(",
"self",
")",
":",
"# type: (Downloader) -> None",
"logger",
".",
"info",
"(",
"'attempting to delete {} extraneous files'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"_delete_after",
")",
")",
")",
"for",
"file",
"in",
"s... | Delete extraneous files cataloged
:param Downloader self: this | [
"Delete",
"extraneous",
"files",
"cataloged",
":",
"param",
"Downloader",
"self",
":",
"this"
] | python | train | 41.105263 |
hyperledger/indy-plenum | plenum/server/ledger_req_handler.py | https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/ledger_req_handler.py#L60-L71 | def commit(self, txnCount, stateRoot, txnRoot, ppTime) -> List:
"""
:param txnCount: The number of requests to commit (The actual requests
are picked up from the uncommitted list from the ledger)
:param stateRoot: The state trie root after the txns are committed
:param txnRoot: T... | [
"def",
"commit",
"(",
"self",
",",
"txnCount",
",",
"stateRoot",
",",
"txnRoot",
",",
"ppTime",
")",
"->",
"List",
":",
"return",
"self",
".",
"_commit",
"(",
"self",
".",
"ledger",
",",
"self",
".",
"state",
",",
"txnCount",
",",
"stateRoot",
",",
"... | :param txnCount: The number of requests to commit (The actual requests
are picked up from the uncommitted list from the ledger)
:param stateRoot: The state trie root after the txns are committed
:param txnRoot: The txn merkle root after the txns are committed
:return: list of committed ... | [
":",
"param",
"txnCount",
":",
"The",
"number",
"of",
"requests",
"to",
"commit",
"(",
"The",
"actual",
"requests",
"are",
"picked",
"up",
"from",
"the",
"uncommitted",
"list",
"from",
"the",
"ledger",
")",
":",
"param",
"stateRoot",
":",
"The",
"state",
... | python | train | 46.75 |
jorgenschaefer/elpy | elpy/refactor.py | https://github.com/jorgenschaefer/elpy/blob/ffd982f829b11e53f2be187c7b770423341f29bc/elpy/refactor.py#L283-L289 | def refactor_create_inline(self, offset, only_this):
"""Inline the function call at point."""
refactor = create_inline(self.project, self.resource, offset)
if only_this:
return self._get_changes(refactor, remove=False, only_current=True)
else:
return self._get_cha... | [
"def",
"refactor_create_inline",
"(",
"self",
",",
"offset",
",",
"only_this",
")",
":",
"refactor",
"=",
"create_inline",
"(",
"self",
".",
"project",
",",
"self",
".",
"resource",
",",
"offset",
")",
"if",
"only_this",
":",
"return",
"self",
".",
"_get_c... | Inline the function call at point. | [
"Inline",
"the",
"function",
"call",
"at",
"point",
"."
] | python | train | 51.571429 |
crypto101/merlyn | merlyn/exercise.py | https://github.com/crypto101/merlyn/blob/0f313210b9ea5385cc2e5b725dc766df9dc3284d/merlyn/exercise.py#L50-L58 | def solveAndNotify(proto, exercise):
"""The user at the given AMP protocol has solved the given exercise.
This will log the solution and notify the user.
"""
exercise.solvedBy(proto.user)
proto.callRemote(ce.NotifySolved,
identifier=exercise.identifier,
tit... | [
"def",
"solveAndNotify",
"(",
"proto",
",",
"exercise",
")",
":",
"exercise",
".",
"solvedBy",
"(",
"proto",
".",
"user",
")",
"proto",
".",
"callRemote",
"(",
"ce",
".",
"NotifySolved",
",",
"identifier",
"=",
"exercise",
".",
"identifier",
",",
"title",
... | The user at the given AMP protocol has solved the given exercise.
This will log the solution and notify the user. | [
"The",
"user",
"at",
"the",
"given",
"AMP",
"protocol",
"has",
"solved",
"the",
"given",
"exercise",
"."
] | python | train | 36.666667 |
daler/gffutils | gffutils/interface.py | https://github.com/daler/gffutils/blob/6f7f547cad898738a1bd0a999fd68ba68db2c524/gffutils/interface.py#L199-L212 | def schema(self):
"""
Returns the database schema as a string.
"""
c = self.conn.cursor()
c.execute(
'''
SELECT sql FROM sqlite_master
''')
results = []
for i, in c:
if i is not None:
results.append(i... | [
"def",
"schema",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"'''\n SELECT sql FROM sqlite_master\n '''",
")",
"results",
"=",
"[",
"]",
"for",
"i",
",",
"in",
"c",
":",
"... | Returns the database schema as a string. | [
"Returns",
"the",
"database",
"schema",
"as",
"a",
"string",
"."
] | python | train | 24.428571 |
pypa/setuptools | setuptools/msvc.py | https://github.com/pypa/setuptools/blob/83c667e0b2a98193851c07115d1af65011ed0fb6/setuptools/msvc.py#L1169-L1177 | def UCRTIncludes(self):
"""
Microsoft Universal C Runtime SDK Include
"""
if self.vc_ver < 14.0:
return []
include = os.path.join(self.si.UniversalCRTSdkDir, 'include')
return [os.path.join(include, '%sucrt' % self._ucrt_subdir)] | [
"def",
"UCRTIncludes",
"(",
"self",
")",
":",
"if",
"self",
".",
"vc_ver",
"<",
"14.0",
":",
"return",
"[",
"]",
"include",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"si",
".",
"UniversalCRTSdkDir",
",",
"'include'",
")",
"return",
"[",
... | Microsoft Universal C Runtime SDK Include | [
"Microsoft",
"Universal",
"C",
"Runtime",
"SDK",
"Include"
] | python | train | 31.333333 |
googleapis/google-cloud-python | irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/irm/google/cloud/irm_v1alpha2/gapic/incident_service_client.py#L131-L138 | def tag_path(cls, project, incident, tag):
"""Return a fully-qualified tag string."""
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/tags/{tag}",
project=project,
incident=incident,
tag=tag,
) | [
"def",
"tag_path",
"(",
"cls",
",",
"project",
",",
"incident",
",",
"tag",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/incidents/{incident}/tags/{tag}\"",
",",
"project",
"=",
"project",
",",
"i... | Return a fully-qualified tag string. | [
"Return",
"a",
"fully",
"-",
"qualified",
"tag",
"string",
"."
] | python | train | 37 |
RiotGames/cloud-inquisitor | backend/cloud_inquisitor/__init__.py | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/backend/cloud_inquisitor/__init__.py#L21-L36 | def get_local_aws_session():
"""Returns a session for the local instance, not for a remote account
Returns:
:obj:`boto3:boto3.session.Session`
"""
if not all((app_config.aws_api.access_key, app_config.aws_api.secret_key)):
return boto3.session.Session()
else:
# If we are not... | [
"def",
"get_local_aws_session",
"(",
")",
":",
"if",
"not",
"all",
"(",
"(",
"app_config",
".",
"aws_api",
".",
"access_key",
",",
"app_config",
".",
"aws_api",
".",
"secret_key",
")",
")",
":",
"return",
"boto3",
".",
"session",
".",
"Session",
"(",
")"... | Returns a session for the local instance, not for a remote account
Returns:
:obj:`boto3:boto3.session.Session` | [
"Returns",
"a",
"session",
"for",
"the",
"local",
"instance",
"not",
"for",
"a",
"remote",
"account"
] | python | train | 40.8125 |
Ex-Mente/auxi.0 | auxi/modelling/business/structure.py | https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/modelling/business/structure.py#L233-L246 | def prepare_to_run(self, clock, period_count):
"""
Prepare the component for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to b... | [
"def",
"prepare_to_run",
"(",
"self",
",",
"clock",
",",
"period_count",
")",
":",
"for",
"c",
"in",
"self",
".",
"components",
":",
"c",
".",
"prepare_to_run",
"(",
"clock",
",",
"period_count",
")",
"for",
"a",
"in",
"self",
".",
"activities",
":",
"... | Prepare the component for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to be run for. | [
"Prepare",
"the",
"component",
"for",
"execution",
"."
] | python | valid | 35.571429 |
openstax/cnx-epub | cnxepub/formatters.py | https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/formatters.py#L98-L143 | def _generate_ids(self, document, content):
"""Generate unique ids for html elements in page content so that it's
possible to link to them.
"""
existing_ids = content.xpath('//*/@id')
elements = [
'p', 'dl', 'dt', 'dd', 'table', 'div', 'section', 'figure',
... | [
"def",
"_generate_ids",
"(",
"self",
",",
"document",
",",
"content",
")",
":",
"existing_ids",
"=",
"content",
".",
"xpath",
"(",
"'//*/@id'",
")",
"elements",
"=",
"[",
"'p'",
",",
"'dl'",
",",
"'dt'",
",",
"'dd'",
",",
"'table'",
",",
"'div'",
",",
... | Generate unique ids for html elements in page content so that it's
possible to link to them. | [
"Generate",
"unique",
"ids",
"for",
"html",
"elements",
"in",
"page",
"content",
"so",
"that",
"it",
"s",
"possible",
"to",
"link",
"to",
"them",
"."
] | python | train | 43.782609 |
dshean/pygeotools | pygeotools/lib/filtlib.py | https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/filtlib.py#L315-L339 | def rolling_fltr(dem, f=np.nanmedian, size=3, circular=True, origmask=False):
"""General rolling filter (default operator is median filter)
Can input any function f
Efficient for smaller arrays, correclty handles NaN, fills gaps
"""
print("Applying rolling filter: %s with size %s" % (f.__name__, s... | [
"def",
"rolling_fltr",
"(",
"dem",
",",
"f",
"=",
"np",
".",
"nanmedian",
",",
"size",
"=",
"3",
",",
"circular",
"=",
"True",
",",
"origmask",
"=",
"False",
")",
":",
"print",
"(",
"\"Applying rolling filter: %s with size %s\"",
"%",
"(",
"f",
".",
"__n... | General rolling filter (default operator is median filter)
Can input any function f
Efficient for smaller arrays, correclty handles NaN, fills gaps | [
"General",
"rolling",
"filter",
"(",
"default",
"operator",
"is",
"median",
"filter",
")"
] | python | train | 36.44 |
JasonKessler/scattertext | scattertext/termsignificance/ScaledFScoreSignificance.py | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termsignificance/ScaledFScoreSignificance.py#L28-L45 | def get_p_vals(self, X):
'''
Imputes p-values from the Z-scores of `ScaledFScore` scores. Assuming incorrectly
that the scaled f-scores are normally distributed.
Parameters
----------
X : np.array
Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the
positive class, while X[:,... | [
"def",
"get_p_vals",
"(",
"self",
",",
"X",
")",
":",
"z_scores",
"=",
"ScaledFZScore",
"(",
"self",
".",
"scaler_algo",
",",
"self",
".",
"beta",
")",
".",
"get_scores",
"(",
"X",
"[",
":",
",",
"0",
"]",
",",
"X",
"[",
":",
",",
"1",
"]",
")"... | Imputes p-values from the Z-scores of `ScaledFScore` scores. Assuming incorrectly
that the scaled f-scores are normally distributed.
Parameters
----------
X : np.array
Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the
positive class, while X[:,1] is the negative class.
Retu... | [
"Imputes",
"p",
"-",
"values",
"from",
"the",
"Z",
"-",
"scores",
"of",
"ScaledFScore",
"scores",
".",
"Assuming",
"incorrectly",
"that",
"the",
"scaled",
"f",
"-",
"scores",
"are",
"normally",
"distributed",
"."
] | python | train | 27.222222 |
trec-kba/streamcorpus-pipeline | streamcorpus_pipeline/_pycassa_simple_table.py | https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_pycassa_simple_table.py#L199-L240 | def get_random_available(self, max_iter=10000):
'''
get a random key out of the first max_iter rows
'''
c = 1
keeper = None
## note the ConsistencyLevel here. If we do not do this, and
## get all slick with things like column_count=0 and filter
## empty F... | [
"def",
"get_random_available",
"(",
"self",
",",
"max_iter",
"=",
"10000",
")",
":",
"c",
"=",
"1",
"keeper",
"=",
"None",
"## note the ConsistencyLevel here. If we do not do this, and",
"## get all slick with things like column_count=0 and filter",
"## empty False, then we can ... | get a random key out of the first max_iter rows | [
"get",
"a",
"random",
"key",
"out",
"of",
"the",
"first",
"max_iter",
"rows"
] | python | test | 44.952381 |
matousc89/padasip | padasip/misc/error_evaluation.py | https://github.com/matousc89/padasip/blob/c969eadd7fa181a84da0554d737fc13c6450d16f/padasip/misc/error_evaluation.py#L152-L173 | def MAE(x1, x2=-1):
"""
Mean absolute error - this function accepts two series of data or directly
one series with error.
**Args:**
* `x1` - first data series or error (1d array)
**Kwargs:**
* `x2` - second series (1d array) if first series was not error directly,\\
then this sho... | [
"def",
"MAE",
"(",
"x1",
",",
"x2",
"=",
"-",
"1",
")",
":",
"e",
"=",
"get_valid_error",
"(",
"x1",
",",
"x2",
")",
"return",
"np",
".",
"sum",
"(",
"np",
".",
"abs",
"(",
"e",
")",
")",
"/",
"float",
"(",
"len",
"(",
"e",
")",
")"
] | Mean absolute error - this function accepts two series of data or directly
one series with error.
**Args:**
* `x1` - first data series or error (1d array)
**Kwargs:**
* `x2` - second series (1d array) if first series was not error directly,\\
then this should be the second series
**... | [
"Mean",
"absolute",
"error",
"-",
"this",
"function",
"accepts",
"two",
"series",
"of",
"data",
"or",
"directly",
"one",
"series",
"with",
"error",
"."
] | python | train | 24.409091 |
Nekroze/partpy | partpy/sourcestring.py | https://github.com/Nekroze/partpy/blob/dbb7d2fb285464fc43d85bc31f5af46192d301f6/partpy/sourcestring.py#L71-L79 | def eol_distance_last(self, offset=0):
"""Return the ammount of characters until the last newline."""
distance = 0
for char in reversed(self.string[:self.pos + offset]):
if char == '\n':
break
else:
distance += 1
return distance | [
"def",
"eol_distance_last",
"(",
"self",
",",
"offset",
"=",
"0",
")",
":",
"distance",
"=",
"0",
"for",
"char",
"in",
"reversed",
"(",
"self",
".",
"string",
"[",
":",
"self",
".",
"pos",
"+",
"offset",
"]",
")",
":",
"if",
"char",
"==",
"'\\n'",
... | Return the ammount of characters until the last newline. | [
"Return",
"the",
"ammount",
"of",
"characters",
"until",
"the",
"last",
"newline",
"."
] | python | train | 34.222222 |
tanghaibao/jcvi | jcvi/projects/age.py | https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/age.py#L338-L354 | def correlation(args):
"""
%prog correlation postgenomic-s.tsv
Plot correlation of age vs. postgenomic features.
"""
p = OptionParser(correlation.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="12x8")
if len(args) != 1:
sys.exit(not p.print_help())
tsvfile, = a... | [
"def",
"correlation",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"correlation",
".",
"__doc__",
")",
"opts",
",",
"args",
",",
"iopts",
"=",
"p",
".",
"set_image_options",
"(",
"args",
",",
"figsize",
"=",
"\"12x8\"",
")",
"if",
"len",
"(",
... | %prog correlation postgenomic-s.tsv
Plot correlation of age vs. postgenomic features. | [
"%prog",
"correlation",
"postgenomic",
"-",
"s",
".",
"tsv"
] | python | train | 28.470588 |
SystemRDL/systemrdl-compiler | systemrdl/rdltypes.py | https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/rdltypes.py#L147-L174 | def get_html_desc(self, markdown_inst=None):
"""
Translates the enum's 'desc' property into HTML.
Any RDLFormatCode tags used in the description are converted to HTML.
The text is also fed through a Markdown processor.
The additional Markdown processing allows designers the cho... | [
"def",
"get_html_desc",
"(",
"self",
",",
"markdown_inst",
"=",
"None",
")",
":",
"desc_str",
"=",
"self",
".",
"_rdl_desc_",
"if",
"desc_str",
"is",
"None",
":",
"return",
"None",
"return",
"rdlformatcode",
".",
"rdlfc_to_html",
"(",
"desc_str",
",",
"md",
... | Translates the enum's 'desc' property into HTML.
Any RDLFormatCode tags used in the description are converted to HTML.
The text is also fed through a Markdown processor.
The additional Markdown processing allows designers the choice to use a
more modern lightweight markup language as a... | [
"Translates",
"the",
"enum",
"s",
"desc",
"property",
"into",
"HTML",
"."
] | python | train | 36.142857 |
nprapps/copydoc | copydoc.py | https://github.com/nprapps/copydoc/blob/e1ab09b287beb0439748c319cf165cbc06c66624/copydoc.py#L189-L195 | def _parse_href(self, href):
"""
Extract "real" URL from Google redirected url by getting `q`
querystring parameter.
"""
params = parse_qs(urlsplit(href).query)
return params.get('q') | [
"def",
"_parse_href",
"(",
"self",
",",
"href",
")",
":",
"params",
"=",
"parse_qs",
"(",
"urlsplit",
"(",
"href",
")",
".",
"query",
")",
"return",
"params",
".",
"get",
"(",
"'q'",
")"
] | Extract "real" URL from Google redirected url by getting `q`
querystring parameter. | [
"Extract",
"real",
"URL",
"from",
"Google",
"redirected",
"url",
"by",
"getting",
"q",
"querystring",
"parameter",
"."
] | python | test | 32.142857 |
toumorokoshi/sprinter | sprinter/core/globals.py | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/globals.py#L85-L94 | def create_default_config():
""" Create a default configuration object, with all parameters filled """
config = configparser.RawConfigParser()
config.add_section('global')
config.set('global', 'env_source_rc', False)
config.add_section('shell')
config.set('shell', 'bash', "true")
config.set(... | [
"def",
"create_default_config",
"(",
")",
":",
"config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"config",
".",
"add_section",
"(",
"'global'",
")",
"config",
".",
"set",
"(",
"'global'",
",",
"'env_source_rc'",
",",
"False",
")",
"config",
".... | Create a default configuration object, with all parameters filled | [
"Create",
"a",
"default",
"configuration",
"object",
"with",
"all",
"parameters",
"filled"
] | python | train | 39.1 |
aestrivex/bctpy | bct/algorithms/generative.py | https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/generative.py#L529-L596 | def evaluate_generative_model(A, Atgt, D, eta, gamma=None,
model_type='matching', model_var='powerlaw', epsilon=1e-6, seed=None):
'''
Generates synthetic networks with parameters provided and evaluates their
energy function. The energy function is defined as in Betzel et al. 2016.
Basically it take... | [
"def",
"evaluate_generative_model",
"(",
"A",
",",
"Atgt",
",",
"D",
",",
"eta",
",",
"gamma",
"=",
"None",
",",
"model_type",
"=",
"'matching'",
",",
"model_var",
"=",
"'powerlaw'",
",",
"epsilon",
"=",
"1e-6",
",",
"seed",
"=",
"None",
")",
":",
"m",... | Generates synthetic networks with parameters provided and evaluates their
energy function. The energy function is defined as in Betzel et al. 2016.
Basically it takes the Kolmogorov-Smirnov statistics of 4 network
measures; comparing the degree distributions, clustering coefficients,
betweenness central... | [
"Generates",
"synthetic",
"networks",
"with",
"parameters",
"provided",
"and",
"evaluates",
"their",
"energy",
"function",
".",
"The",
"energy",
"function",
"is",
"defined",
"as",
"in",
"Betzel",
"et",
"al",
".",
"2016",
".",
"Basically",
"it",
"takes",
"the",... | python | train | 32.044118 |
mulkieran/justbases | src/justbases/_nats.py | https://github.com/mulkieran/justbases/blob/dd52ff4b3d11609f54b2673599ee4eeb20f9734f/src/justbases/_nats.py#L59-L91 | def convert_to_int(value, from_base):
"""
Convert value to an int.
:param value: the value to convert
:type value: sequence of int
:param int from_base: base of value
:returns: the conversion result
:rtype: int
:raises ConvertError: if from_base is less t... | [
"def",
"convert_to_int",
"(",
"value",
",",
"from_base",
")",
":",
"if",
"from_base",
"<",
"2",
":",
"raise",
"BasesValueError",
"(",
"from_base",
",",
"\"from_base\"",
",",
"\"must be greater than 2\"",
")",
"if",
"any",
"(",
"x",
"<",
"0",
"or",
"x",
">=... | Convert value to an int.
:param value: the value to convert
:type value: sequence of int
:param int from_base: base of value
:returns: the conversion result
:rtype: int
:raises ConvertError: if from_base is less than 2
:raises ConvertError: if elements in value o... | [
"Convert",
"value",
"to",
"an",
"int",
"."
] | python | train | 31.666667 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/csv_io.py | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/csv_io.py#L56-L113 | def index_row_dict_from_csv(path,
index_col=None,
iterator=False,
chunksize=None,
skiprows=None,
nrows=None,
use_ordered_dict=True,
... | [
"def",
"index_row_dict_from_csv",
"(",
"path",
",",
"index_col",
"=",
"None",
",",
"iterator",
"=",
"False",
",",
"chunksize",
"=",
"None",
",",
"skiprows",
"=",
"None",
",",
"nrows",
"=",
"None",
",",
"use_ordered_dict",
"=",
"True",
",",
"*",
"*",
"kwa... | Read the csv into a dictionary. The key is it's index, the value
is the dictionary form of the row.
:param path: csv file path.
:param index_col: None or str, the column that used as index.
:param iterator:
:param chunksize:
:param skiprows:
:param nrows:
:param use_ordered_dict:
:... | [
"Read",
"the",
"csv",
"into",
"a",
"dictionary",
".",
"The",
"key",
"is",
"it",
"s",
"index",
"the",
"value",
"is",
"the",
"dictionary",
"form",
"of",
"the",
"row",
"."
] | python | train | 29.12069 |
softlayer/softlayer-python | SoftLayer/CLI/account/event_detail.py | https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/account/event_detail.py#L32-L45 | def basic_event_table(event):
"""Formats a basic event table"""
table = formatting.Table(["Id", "Status", "Type", "Start", "End"],
title=utils.clean_splitlines(event.get('subject')))
table.add_row([
event.get('id'),
utils.lookup(event, 'statusCode', 'name'),
... | [
"def",
"basic_event_table",
"(",
"event",
")",
":",
"table",
"=",
"formatting",
".",
"Table",
"(",
"[",
"\"Id\"",
",",
"\"Status\"",
",",
"\"Type\"",
",",
"\"Start\"",
",",
"\"End\"",
"]",
",",
"title",
"=",
"utils",
".",
"clean_splitlines",
"(",
"event",
... | Formats a basic event table | [
"Formats",
"a",
"basic",
"event",
"table"
] | python | train | 35.714286 |
achedeuzot/django-timestampable | django_timestampable/models.py | https://github.com/achedeuzot/django-timestampable/blob/44d774655c383e43d931e64ac5e1d41dd737873d/django_timestampable/models.py#L31-L41 | def update_timestampable_model(sender, instance, *args, **kwargs):
'''
Using signals guarantees that timestamps are set no matter what:
loading fixtures, bulk inserts, bulk updates, etc.
Indeed, the `save()` method is *not* called when using fixtures.
'''
if not isinstance(instance, Timestampabl... | [
"def",
"update_timestampable_model",
"(",
"sender",
",",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"instance",
",",
"TimestampableModel",
")",
":",
"return",
"if",
"not",
"instance",
".",
"pk",
":",
... | Using signals guarantees that timestamps are set no matter what:
loading fixtures, bulk inserts, bulk updates, etc.
Indeed, the `save()` method is *not* called when using fixtures. | [
"Using",
"signals",
"guarantees",
"that",
"timestamps",
"are",
"set",
"no",
"matter",
"what",
":",
"loading",
"fixtures",
"bulk",
"inserts",
"bulk",
"updates",
"etc",
".",
"Indeed",
"the",
"save",
"()",
"method",
"is",
"*",
"not",
"*",
"called",
"when",
"u... | python | train | 38.636364 |
obriencj/python-javatools | javatools/change.py | https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/change.py#L471-L488 | def is_ignored(self, options):
"""
If we have changed children and all the children which are changes
are ignored, then we are ignored. Otherwise, we are not
ignored
"""
if not self.is_change():
return False
changes = self.collect()
if not ch... | [
"def",
"is_ignored",
"(",
"self",
",",
"options",
")",
":",
"if",
"not",
"self",
".",
"is_change",
"(",
")",
":",
"return",
"False",
"changes",
"=",
"self",
".",
"collect",
"(",
")",
"if",
"not",
"changes",
":",
"return",
"False",
"for",
"change",
"i... | If we have changed children and all the children which are changes
are ignored, then we are ignored. Otherwise, we are not
ignored | [
"If",
"we",
"have",
"changed",
"children",
"and",
"all",
"the",
"children",
"which",
"are",
"changes",
"are",
"ignored",
"then",
"we",
"are",
"ignored",
".",
"Otherwise",
"we",
"are",
"not",
"ignored"
] | python | train | 26.944444 |
pandas-dev/pandas | pandas/core/arrays/categorical.py | https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/arrays/categorical.py#L776-L846 | def set_categories(self, new_categories, ordered=None, rename=False,
inplace=False):
"""
Set the categories to the specified new_categories.
`new_categories` can include new categories (which will result in
unused categories) or remove old categories (which result... | [
"def",
"set_categories",
"(",
"self",
",",
"new_categories",
",",
"ordered",
"=",
"None",
",",
"rename",
"=",
"False",
",",
"inplace",
"=",
"False",
")",
":",
"inplace",
"=",
"validate_bool_kwarg",
"(",
"inplace",
",",
"'inplace'",
")",
"if",
"ordered",
"i... | Set the categories to the specified new_categories.
`new_categories` can include new categories (which will result in
unused categories) or remove old categories (which results in values
set to NaN). If `rename==True`, the categories will simple be renamed
(less or more items than in ol... | [
"Set",
"the",
"categories",
"to",
"the",
"specified",
"new_categories",
"."
] | python | train | 40.549296 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.