repo stringlengths 7 54 | path stringlengths 4 192 | url stringlengths 87 284 | code stringlengths 78 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|
BernardFW/bernard | src/bernard/i18n/utils.py | https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/utils.py#L14-L27 | def split_locale(locale: Text) -> Tuple[Text, Optional[Text]]:
"""
Decompose the locale into a normalized tuple.
The first item is the locale (as lowercase letters) while the second item
is either the country as lower case either None if no country was supplied.
"""
items = re.split(r'[_\-]', ... | [
"def",
"split_locale",
"(",
"locale",
":",
"Text",
")",
"->",
"Tuple",
"[",
"Text",
",",
"Optional",
"[",
"Text",
"]",
"]",
":",
"items",
"=",
"re",
".",
"split",
"(",
"r'[_\\-]'",
",",
"locale",
".",
"lower",
"(",
")",
",",
"1",
")",
"try",
":",... | Decompose the locale into a normalized tuple.
The first item is the locale (as lowercase letters) while the second item
is either the country as lower case either None if no country was supplied. | [
"Decompose",
"the",
"locale",
"into",
"a",
"normalized",
"tuple",
"."
] | python | train |
tcalmant/ipopo | pelix/ipopo/handlers/provides.py | https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L189-L224 | def manipulate(self, stored_instance, component_instance):
"""
Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
"""
# Store the stored instance
self._ipopo_instance = s... | [
"def",
"manipulate",
"(",
"self",
",",
"stored_instance",
",",
"component_instance",
")",
":",
"# Store the stored instance",
"self",
".",
"_ipopo_instance",
"=",
"stored_instance",
"if",
"self",
".",
"__controller",
"is",
"None",
":",
"# No controller: do nothing",
"... | Manipulates the component instance
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance | [
"Manipulates",
"the",
"component",
"instance"
] | python | train |
shapiromatron/bmds | bmds/models/base.py | https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L155-L163 | def execution_duration(self):
"""
Returns total BMDS execution time, in seconds.
"""
duration = None
if self.execution_start and self.execution_end:
delta = self.execution_end - self.execution_start
duration = delta.total_seconds()
return duration | [
"def",
"execution_duration",
"(",
"self",
")",
":",
"duration",
"=",
"None",
"if",
"self",
".",
"execution_start",
"and",
"self",
".",
"execution_end",
":",
"delta",
"=",
"self",
".",
"execution_end",
"-",
"self",
".",
"execution_start",
"duration",
"=",
"de... | Returns total BMDS execution time, in seconds. | [
"Returns",
"total",
"BMDS",
"execution",
"time",
"in",
"seconds",
"."
] | python | train |
Microsoft/nni | examples/trials/ga_squad/train_model.py | https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/ga_squad/train_model.py#L87-L233 | def build_net(self, is_training):
"""Build the whole neural network for the QA model."""
cfg = self.cfg
with tf.device('/cpu:0'):
word_embed = tf.get_variable(
name='word_embed', initializer=self.embed, dtype=tf.float32, trainable=False)
char_embed = tf.ge... | [
"def",
"build_net",
"(",
"self",
",",
"is_training",
")",
":",
"cfg",
"=",
"self",
".",
"cfg",
"with",
"tf",
".",
"device",
"(",
"'/cpu:0'",
")",
":",
"word_embed",
"=",
"tf",
".",
"get_variable",
"(",
"name",
"=",
"'word_embed'",
",",
"initializer",
"... | Build the whole neural network for the QA model. | [
"Build",
"the",
"whole",
"neural",
"network",
"for",
"the",
"QA",
"model",
"."
] | python | train |
bachya/pyflunearyou | pyflunearyou/report.py | https://github.com/bachya/pyflunearyou/blob/16a2f839c8df851e925e010a6b5c5708386febac/pyflunearyou/report.py#L45-L70 | async def nearest_by_coordinates(
self, latitude: float, longitude: float) -> dict:
"""Get the nearest report (with local and state info) to a lat/lon."""
# Since user data is more granular than state or CDC data, find the
# user report whose coordinates are closest to the provided
... | [
"async",
"def",
"nearest_by_coordinates",
"(",
"self",
",",
"latitude",
":",
"float",
",",
"longitude",
":",
"float",
")",
"->",
"dict",
":",
"# Since user data is more granular than state or CDC data, find the",
"# user report whose coordinates are closest to the provided",
"#... | Get the nearest report (with local and state info) to a lat/lon. | [
"Get",
"the",
"nearest",
"report",
"(",
"with",
"local",
"and",
"state",
"info",
")",
"to",
"a",
"lat",
"/",
"lon",
"."
] | python | train |
ethereum/py-evm | eth/chains/base.py | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L443-L451 | def from_genesis_header(cls,
base_db: BaseAtomicDB,
genesis_header: BlockHeader) -> 'BaseChain':
"""
Initializes the chain from the genesis header.
"""
chaindb = cls.get_chaindb_class()(base_db)
chaindb.persist_header(genesi... | [
"def",
"from_genesis_header",
"(",
"cls",
",",
"base_db",
":",
"BaseAtomicDB",
",",
"genesis_header",
":",
"BlockHeader",
")",
"->",
"'BaseChain'",
":",
"chaindb",
"=",
"cls",
".",
"get_chaindb_class",
"(",
")",
"(",
"base_db",
")",
"chaindb",
".",
"persist_he... | Initializes the chain from the genesis header. | [
"Initializes",
"the",
"chain",
"from",
"the",
"genesis",
"header",
"."
] | python | train |
openpermissions/koi | koi/commands.py | https://github.com/openpermissions/koi/blob/d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281/koi/commands.py#L224-L240 | def run(func):
"""Execute the provided function if there are no subcommands"""
@defaults.command(help='Run the service')
@click.pass_context
def runserver(ctx, *args, **kwargs):
if (ctx.parent.invoked_subcommand and
ctx.command.name != ctx.parent.invoked_subcommand):
... | [
"def",
"run",
"(",
"func",
")",
":",
"@",
"defaults",
".",
"command",
"(",
"help",
"=",
"'Run the service'",
")",
"@",
"click",
".",
"pass_context",
"def",
"runserver",
"(",
"ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"ct... | Execute the provided function if there are no subcommands | [
"Execute",
"the",
"provided",
"function",
"if",
"there",
"are",
"no",
"subcommands"
] | python | train |
chrisspen/burlap | burlap/git.py | https://github.com/chrisspen/burlap/blob/a92b0a8e5206850bb777c74af8421ea8b33779bd/burlap/git.py#L179-L216 | def pull(self, path, use_sudo=False, user=None, force=False):
"""
Fetch changes from the default remote repository and merge them.
:param path: Path of the working copy directory. This directory must exist
and be a Git working copy with a default remote to pull from.
... | [
"def",
"pull",
"(",
"self",
",",
"path",
",",
"use_sudo",
"=",
"False",
",",
"user",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"path",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Path to the working copy is needed to pull from a remote rep... | Fetch changes from the default remote repository and merge them.
:param path: Path of the working copy directory. This directory must exist
and be a Git working copy with a default remote to pull from.
:type path: str
:param use_sudo: If ``True`` execute ``git`` with
... | [
"Fetch",
"changes",
"from",
"the",
"default",
"remote",
"repository",
"and",
"merge",
"them",
"."
] | python | valid |
Erotemic/utool | utool/util_setup.py | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_setup.py#L103-L110 | def setup_chmod(setup_fpath, setup_dir, chmod_patterns):
""" Gives files matching pattern the same chmod flags as setup.py """
#st_mode = os.stat(setup_fpath).st_mode
st_mode = 33277
for pattern in chmod_patterns:
for fpath in util_path.glob(setup_dir, pattern, recursive=True):
print... | [
"def",
"setup_chmod",
"(",
"setup_fpath",
",",
"setup_dir",
",",
"chmod_patterns",
")",
":",
"#st_mode = os.stat(setup_fpath).st_mode",
"st_mode",
"=",
"33277",
"for",
"pattern",
"in",
"chmod_patterns",
":",
"for",
"fpath",
"in",
"util_path",
".",
"glob",
"(",
"se... | Gives files matching pattern the same chmod flags as setup.py | [
"Gives",
"files",
"matching",
"pattern",
"the",
"same",
"chmod",
"flags",
"as",
"setup",
".",
"py"
] | python | train |
camsci/meteor-pi | src/pythonModules/meteorpi_db/meteorpi_db/__init__.py | https://github.com/camsci/meteor-pi/blob/7b01527650bd1b2b76d6f364e8122e25b8812c8d/src/pythonModules/meteorpi_db/meteorpi_db/__init__.py#L580-L597 | def get_observation(self, observation_id):
"""
Retrieve an existing :class:`meteorpi_model.Observation` by its ID
:param string observation_id:
UUID of the observation
:return:
A :class:`meteorpi_model.Observation` instance, or None if not found
"""
... | [
"def",
"get_observation",
"(",
"self",
",",
"observation_id",
")",
":",
"search",
"=",
"mp",
".",
"ObservationSearch",
"(",
"observation_id",
"=",
"observation_id",
")",
"b",
"=",
"search_observations_sql_builder",
"(",
"search",
")",
"sql",
"=",
"b",
".",
"ge... | Retrieve an existing :class:`meteorpi_model.Observation` by its ID
:param string observation_id:
UUID of the observation
:return:
A :class:`meteorpi_model.Observation` instance, or None if not found | [
"Retrieve",
"an",
"existing",
":",
"class",
":",
"meteorpi_model",
".",
"Observation",
"by",
"its",
"ID"
] | python | train |
klahnakoski/pyLibrary | mo_math/__init__.py | https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/__init__.py#L190-L202 | def mod(value, mod=1):
"""
RETURN NON-NEGATIVE MODULO
RETURN None WHEN GIVEN INVALID ARGUMENTS
"""
if value == None:
return None
elif mod <= 0:
return None
elif value < 0:
return (value % mod + mod) % mod
else:
return value % mod | [
"def",
"mod",
"(",
"value",
",",
"mod",
"=",
"1",
")",
":",
"if",
"value",
"==",
"None",
":",
"return",
"None",
"elif",
"mod",
"<=",
"0",
":",
"return",
"None",
"elif",
"value",
"<",
"0",
":",
"return",
"(",
"value",
"%",
"mod",
"+",
"mod",
")"... | RETURN NON-NEGATIVE MODULO
RETURN None WHEN GIVEN INVALID ARGUMENTS | [
"RETURN",
"NON",
"-",
"NEGATIVE",
"MODULO",
"RETURN",
"None",
"WHEN",
"GIVEN",
"INVALID",
"ARGUMENTS"
] | python | train |
Crunch-io/crunch-cube | src/cr/cube/measures/wishart_pairwise_significance.py | https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/measures/wishart_pairwise_significance.py#L176-L182 | def _pairwise_chisq(self):
"""Pairwise comparisons (Chi-Square) along axis, as numpy.ndarray.
Returns a square, symmetric matrix of test statistics for the null
hypothesis that each vector along *axis* is equal to each other.
"""
return self._chi_squared(self._proportions, self.... | [
"def",
"_pairwise_chisq",
"(",
"self",
")",
":",
"return",
"self",
".",
"_chi_squared",
"(",
"self",
".",
"_proportions",
",",
"self",
".",
"_margin",
",",
"self",
".",
"_observed",
")"
] | Pairwise comparisons (Chi-Square) along axis, as numpy.ndarray.
Returns a square, symmetric matrix of test statistics for the null
hypothesis that each vector along *axis* is equal to each other. | [
"Pairwise",
"comparisons",
"(",
"Chi",
"-",
"Square",
")",
"along",
"axis",
"as",
"numpy",
".",
"ndarray",
"."
] | python | train |
google/grr | grr/server/grr_response_server/databases/mysql_users.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_users.py#L24-L52 | def _ResponseToApprovalsWithGrants(response):
"""Converts a generator with approval rows into ApprovalRequest objects."""
prev_triplet = None
cur_approval_request = None
for (approval_id_int, approval_timestamp, approval_request_bytes,
grantor_username, grant_timestamp) in response:
cur_triplet = (a... | [
"def",
"_ResponseToApprovalsWithGrants",
"(",
"response",
")",
":",
"prev_triplet",
"=",
"None",
"cur_approval_request",
"=",
"None",
"for",
"(",
"approval_id_int",
",",
"approval_timestamp",
",",
"approval_request_bytes",
",",
"grantor_username",
",",
"grant_timestamp",
... | Converts a generator with approval rows into ApprovalRequest objects. | [
"Converts",
"a",
"generator",
"with",
"approval",
"rows",
"into",
"ApprovalRequest",
"objects",
"."
] | python | train |
Capitains/MyCapytain | MyCapytain/resources/prototypes/cts/inventory.py | https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/cts/inventory.py#L360-L367 | def get_description(self, lang=None):
""" Get the DC description of the object
:param lang: Lang to retrieve
:return: Description string representation
:rtype: Literal
"""
return self.metadata.get_single(key=RDF_NAMESPACES.CTS.description, lang=lang) | [
"def",
"get_description",
"(",
"self",
",",
"lang",
"=",
"None",
")",
":",
"return",
"self",
".",
"metadata",
".",
"get_single",
"(",
"key",
"=",
"RDF_NAMESPACES",
".",
"CTS",
".",
"description",
",",
"lang",
"=",
"lang",
")"
] | Get the DC description of the object
:param lang: Lang to retrieve
:return: Description string representation
:rtype: Literal | [
"Get",
"the",
"DC",
"description",
"of",
"the",
"object"
] | python | train |
LogicalDash/LiSE | ELiDE/ELiDE/board/pawnspot.py | https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/pawnspot.py#L91-L116 | def finalize(self, initial=True):
"""Call this after you've created all the PawnSpot you need and are ready to add them to the board."""
if getattr(self, '_finalized', False):
return
if (
self.proxy is None or
not hasattr(self.proxy, 'name')
):... | [
"def",
"finalize",
"(",
"self",
",",
"initial",
"=",
"True",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'_finalized'",
",",
"False",
")",
":",
"return",
"if",
"(",
"self",
".",
"proxy",
"is",
"None",
"or",
"not",
"hasattr",
"(",
"self",
".",
"pr... | Call this after you've created all the PawnSpot you need and are ready to add them to the board. | [
"Call",
"this",
"after",
"you",
"ve",
"created",
"all",
"the",
"PawnSpot",
"you",
"need",
"and",
"are",
"ready",
"to",
"add",
"them",
"to",
"the",
"board",
"."
] | python | train |
theosysbio/means | src/means/simulation/ssa.py | https://github.com/theosysbio/means/blob/fe164916a1d84ab2a4fa039871d38ccdf638b1db/src/means/simulation/ssa.py#L215-L234 | def _gssa(self, initial_conditions, t_max):
"""
This function is inspired from Yoav Ram's code available at:
http://nbviewer.ipython.org/github/yoavram/ipython-notebooks/blob/master/GSSA.ipynb
:param initial_conditions: the initial conditions of the system
:param t_max: the tim... | [
"def",
"_gssa",
"(",
"self",
",",
"initial_conditions",
",",
"t_max",
")",
":",
"# set the initial conditions and t0 = 0.",
"species_over_time",
"=",
"[",
"np",
".",
"array",
"(",
"initial_conditions",
")",
".",
"astype",
"(",
"\"int16\"",
")",
"]",
"t",
"=",
... | This function is inspired from Yoav Ram's code available at:
http://nbviewer.ipython.org/github/yoavram/ipython-notebooks/blob/master/GSSA.ipynb
:param initial_conditions: the initial conditions of the system
:param t_max: the time when the simulation should stop
:return: | [
"This",
"function",
"is",
"inspired",
"from",
"Yoav",
"Ram",
"s",
"code",
"available",
"at",
":",
"http",
":",
"//",
"nbviewer",
".",
"ipython",
".",
"org",
"/",
"github",
"/",
"yoavram",
"/",
"ipython",
"-",
"notebooks",
"/",
"blob",
"/",
"master",
"/... | python | train |
d0c-s4vage/pfp | pfp/fields.py | https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/fields.py#L1410-L1423 | def _pfp__parse(self, stream, save_offset=False):
"""Parse the IO stream for this enum
:stream: An IO stream that can be read from
:returns: The number of bytes parsed
"""
res = super(Enum, self)._pfp__parse(stream, save_offset)
if self._pfp__value in self.enum_vals:
... | [
"def",
"_pfp__parse",
"(",
"self",
",",
"stream",
",",
"save_offset",
"=",
"False",
")",
":",
"res",
"=",
"super",
"(",
"Enum",
",",
"self",
")",
".",
"_pfp__parse",
"(",
"stream",
",",
"save_offset",
")",
"if",
"self",
".",
"_pfp__value",
"in",
"self"... | Parse the IO stream for this enum
:stream: An IO stream that can be read from
:returns: The number of bytes parsed | [
"Parse",
"the",
"IO",
"stream",
"for",
"this",
"enum"
] | python | train |
ruipgil/TrackToTrip | tracktotrip/smooth.py | https://github.com/ruipgil/TrackToTrip/blob/5537c14ee9748091b5255b658ab528e1d6227f99/tracktotrip/smooth.py#L47-L58 | def with_extrapolation(points, noise, n_points):
""" Smooths a set of points, but it extrapolates some points at the beginning
Args:
points (:obj:`list` of :obj:`Point`)
noise (float): Expected noise, the higher it is the more the path will
be smoothed.
Returns:
:obj:`li... | [
"def",
"with_extrapolation",
"(",
"points",
",",
"noise",
",",
"n_points",
")",
":",
"n_points",
"=",
"10",
"return",
"kalman_filter",
"(",
"extrapolate_points",
"(",
"points",
",",
"n_points",
")",
"+",
"points",
",",
"noise",
")",
"[",
"n_points",
":",
"... | Smooths a set of points, but it extrapolates some points at the beginning
Args:
points (:obj:`list` of :obj:`Point`)
noise (float): Expected noise, the higher it is the more the path will
be smoothed.
Returns:
:obj:`list` of :obj:`Point` | [
"Smooths",
"a",
"set",
"of",
"points",
"but",
"it",
"extrapolates",
"some",
"points",
"at",
"the",
"beginning"
] | python | train |
Kozea/wdb | client/wdb/__init__.py | https://github.com/Kozea/wdb/blob/6af7901b02e866d76f8b0a697a8c078e5b70d1aa/client/wdb/__init__.py#L758-L776 | def receive(self, timeout=None):
"""Receive data through websocket"""
log.debug('Receiving')
if not self._socket:
log.warn('No connection')
return
try:
if timeout:
rv = self._socket.poll(timeout)
if not rv:
... | [
"def",
"receive",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'Receiving'",
")",
"if",
"not",
"self",
".",
"_socket",
":",
"log",
".",
"warn",
"(",
"'No connection'",
")",
"return",
"try",
":",
"if",
"timeout",
":",... | Receive data through websocket | [
"Receive",
"data",
"through",
"websocket"
] | python | train |
ambitioninc/rabbitmq-admin | rabbitmq_admin/base.py | https://github.com/ambitioninc/rabbitmq-admin/blob/ff65054115f19991da153f0e4f4e45e526545fea/rabbitmq_admin/base.py#L112-L123 | def _api_delete(self, url, **kwargs):
"""
A convenience wrapper for _delete. Adds headers, auth and base url by
default
"""
kwargs['url'] = self.url + url
kwargs['auth'] = self.auth
headers = deepcopy(self.headers)
headers.update(kwargs.get('headers', {})... | [
"def",
"_api_delete",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'url'",
"]",
"=",
"self",
".",
"url",
"+",
"url",
"kwargs",
"[",
"'auth'",
"]",
"=",
"self",
".",
"auth",
"headers",
"=",
"deepcopy",
"(",
"self",
"... | A convenience wrapper for _delete. Adds headers, auth and base url by
default | [
"A",
"convenience",
"wrapper",
"for",
"_delete",
".",
"Adds",
"headers",
"auth",
"and",
"base",
"url",
"by",
"default"
] | python | train |
Accelize/pycosio | pycosio/storage/azure.py | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L140-L154 | def _secured_storage_parameters(self):
"""
Updates storage parameters with unsecure mode.
Returns:
dict: Updated storage_parameters.
"""
parameters = self._storage_parameters or dict()
# Handles unsecure mode
if self._unsecure:
parameters... | [
"def",
"_secured_storage_parameters",
"(",
"self",
")",
":",
"parameters",
"=",
"self",
".",
"_storage_parameters",
"or",
"dict",
"(",
")",
"# Handles unsecure mode",
"if",
"self",
".",
"_unsecure",
":",
"parameters",
"=",
"parameters",
".",
"copy",
"(",
")",
... | Updates storage parameters with unsecure mode.
Returns:
dict: Updated storage_parameters. | [
"Updates",
"storage",
"parameters",
"with",
"unsecure",
"mode",
"."
] | python | train |
perrygeo/simanneal | examples/watershed/shapefile.py | https://github.com/perrygeo/simanneal/blob/293bc81b5bc4bf0ba7760a0e4df5ba97fdcf2881/examples/watershed/shapefile.py#L569-L599 | def __shapefileHeader(self, fileObj, headerType='shp'):
"""Writes the specified header type to the specified file-like object.
Several of the shapefile formats are so similar that a single generic
method to read or write them is warranted."""
f = self.__getFileObj(fileObj)
f... | [
"def",
"__shapefileHeader",
"(",
"self",
",",
"fileObj",
",",
"headerType",
"=",
"'shp'",
")",
":",
"f",
"=",
"self",
".",
"__getFileObj",
"(",
"fileObj",
")",
"f",
".",
"seek",
"(",
"0",
")",
"# File code, Unused bytes\r",
"f",
".",
"write",
"(",
"pack"... | Writes the specified header type to the specified file-like object.
Several of the shapefile formats are so similar that a single generic
method to read or write them is warranted. | [
"Writes",
"the",
"specified",
"header",
"type",
"to",
"the",
"specified",
"file",
"-",
"like",
"object",
".",
"Several",
"of",
"the",
"shapefile",
"formats",
"are",
"so",
"similar",
"that",
"a",
"single",
"generic",
"method",
"to",
"read",
"or",
"write",
"... | python | train |
explosion/spaCy | spacy/displacy/render.py | https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/render.py#L172-L197 | def get_arrowhead(self, direction, x, y, end):
"""Render individual arrow head.
direction (unicode): Arrow direction, 'left' or 'right'.
x (int): X-coordinate of arrow start point.
y (int): Y-coordinate of arrow start and end point.
end (int): X-coordinate of arrow end point.
... | [
"def",
"get_arrowhead",
"(",
"self",
",",
"direction",
",",
"x",
",",
"y",
",",
"end",
")",
":",
"if",
"direction",
"==",
"\"left\"",
":",
"pos1",
",",
"pos2",
",",
"pos3",
"=",
"(",
"x",
",",
"x",
"-",
"self",
".",
"arrow_width",
"+",
"2",
",",
... | Render individual arrow head.
direction (unicode): Arrow direction, 'left' or 'right'.
x (int): X-coordinate of arrow start point.
y (int): Y-coordinate of arrow start and end point.
end (int): X-coordinate of arrow end point.
RETURNS (unicode): Definition of the arrow head path... | [
"Render",
"individual",
"arrow",
"head",
"."
] | python | train |
phoebe-project/phoebe2 | phoebe/backend/mesh.py | https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/backend/mesh.py#L395-L406 | def averages(self):
"""
Access to the average of the values at the vertices for each triangle.
If the quantities are defined at centers instead of vertices, this
will return None. Also see :method:`centers`.
:return: numpy array or None
"""
if not self.mesh._com... | [
"def",
"averages",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"mesh",
".",
"_compute_at_vertices",
":",
"return",
"None",
"return",
"np",
".",
"mean",
"(",
"self",
".",
"vertices_per_triangle",
",",
"axis",
"=",
"1",
")"
] | Access to the average of the values at the vertices for each triangle.
If the quantities are defined at centers instead of vertices, this
will return None. Also see :method:`centers`.
:return: numpy array or None | [
"Access",
"to",
"the",
"average",
"of",
"the",
"values",
"at",
"the",
"vertices",
"for",
"each",
"triangle",
".",
"If",
"the",
"quantities",
"are",
"defined",
"at",
"centers",
"instead",
"of",
"vertices",
"this",
"will",
"return",
"None",
".",
"Also",
"see... | python | train |
fabaff/python-mystrom | pymystrom/cli.py | https://github.com/fabaff/python-mystrom/blob/86410f8952104651ef76ad37c84c29740c50551e/pymystrom/cli.py#L35-L40 | def read_config(ip, mac):
"""Read the current configuration of a myStrom device."""
click.echo("Read configuration from %s" % ip)
request = requests.get(
'http://{}/{}/{}/'.format(ip, URI, mac), timeout=TIMEOUT)
print(request.json()) | [
"def",
"read_config",
"(",
"ip",
",",
"mac",
")",
":",
"click",
".",
"echo",
"(",
"\"Read configuration from %s\"",
"%",
"ip",
")",
"request",
"=",
"requests",
".",
"get",
"(",
"'http://{}/{}/{}/'",
".",
"format",
"(",
"ip",
",",
"URI",
",",
"mac",
")",
... | Read the current configuration of a myStrom device. | [
"Read",
"the",
"current",
"configuration",
"of",
"a",
"myStrom",
"device",
"."
] | python | train |
saltstack/salt | salt/modules/cloud.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cloud.py#L156-L183 | def get_instance(name, provider=None):
'''
Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
... | [
"def",
"get_instance",
"(",
"name",
",",
"provider",
"=",
"None",
")",
":",
"data",
"=",
"action",
"(",
"fun",
"=",
"'show_instance'",
",",
"names",
"=",
"[",
"name",
"]",
",",
"provider",
"=",
"provider",
")",
"info",
"=",
"salt",
".",
"utils",
".",... | Return details on an instance.
Similar to the cloud action show_instance
but returns only the instance details.
CLI Example:
.. code-block:: bash
salt minionname cloud.get_instance myinstance
SLS Example:
.. code-block:: bash
{{ salt['cloud.get_instance']('myinstance')['ma... | [
"Return",
"details",
"on",
"an",
"instance",
"."
] | python | train |
eyurtsev/FlowCytometryTools | FlowCytometryTools/gui/fc_widget.py | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/gui/fc_widget.py#L730-L750 | def change_axis(self, axis_num, channel_name):
"""
TODO: refactor that and set_axes
what to do with ax?
axis_num: int
axis number
channel_name: str
new channel to plot on that axis
"""
current_channels = list(self.current_channels)
i... | [
"def",
"change_axis",
"(",
"self",
",",
"axis_num",
",",
"channel_name",
")",
":",
"current_channels",
"=",
"list",
"(",
"self",
".",
"current_channels",
")",
"if",
"len",
"(",
"current_channels",
")",
"==",
"1",
":",
"if",
"axis_num",
"==",
"0",
":",
"n... | TODO: refactor that and set_axes
what to do with ax?
axis_num: int
axis number
channel_name: str
new channel to plot on that axis | [
"TODO",
":",
"refactor",
"that",
"and",
"set_axes",
"what",
"to",
"do",
"with",
"ax?"
] | python | train |
wavefrontHQ/python-client | wavefront_api_client/api/dashboard_api.py | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/dashboard_api.py#L1399-L1420 | def set_dashboard_tags(self, id, **kwargs): # noqa: E501
"""Set all tags associated with a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.... | [
"def",
"set_dashboard_tags",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"set_dashb... | Set all tags associated with a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.set_dashboard_tags(id, async_req=True)
>>> result = thread.ge... | [
"Set",
"all",
"tags",
"associated",
"with",
"a",
"specific",
"dashboard",
"#",
"noqa",
":",
"E501"
] | python | train |
buildbot/buildbot | master/buildbot/changes/hgpoller.py | https://github.com/buildbot/buildbot/blob/5df3cfae6d760557d99156633c32b1822a1e130c/master/buildbot/changes/hgpoller.py#L148-L163 | def _initRepository(self):
"""Have mercurial init the workdir as a repository (hg init) if needed.
hg init will also create all needed intermediate directories.
"""
if self._isRepositoryReady():
return defer.succeed(None)
log.msg('hgpoller: initializing working dir f... | [
"def",
"_initRepository",
"(",
"self",
")",
":",
"if",
"self",
".",
"_isRepositoryReady",
"(",
")",
":",
"return",
"defer",
".",
"succeed",
"(",
"None",
")",
"log",
".",
"msg",
"(",
"'hgpoller: initializing working dir from %s'",
"%",
"self",
".",
"repourl",
... | Have mercurial init the workdir as a repository (hg init) if needed.
hg init will also create all needed intermediate directories. | [
"Have",
"mercurial",
"init",
"the",
"workdir",
"as",
"a",
"repository",
"(",
"hg",
"init",
")",
"if",
"needed",
"."
] | python | train |
psss/did | did/plugins/trac.py | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/trac.py#L119-L124 | def closed(self):
""" True if ticket was closed in given time frame """
for who, what, old, new in self.history():
if what == "status" and new == "closed":
return True
return False | [
"def",
"closed",
"(",
"self",
")",
":",
"for",
"who",
",",
"what",
",",
"old",
",",
"new",
"in",
"self",
".",
"history",
"(",
")",
":",
"if",
"what",
"==",
"\"status\"",
"and",
"new",
"==",
"\"closed\"",
":",
"return",
"True",
"return",
"False"
] | True if ticket was closed in given time frame | [
"True",
"if",
"ticket",
"was",
"closed",
"in",
"given",
"time",
"frame"
] | python | train |
xzased/lvm2py | lvm2py/vg.py | https://github.com/xzased/lvm2py/blob/34ce69304531a474c2fe4a4009ca445a8c103cd6/lvm2py/vg.py#L348-L380 | def remove_pv(self, pv):
"""
Removes a physical volume from the volume group::
from lvm2py import *
lvm = LVM()
vg = lvm.get_vg("myvg", "w")
pv = vg.pvscan()[0]
vg.remove_pv(pv)
*Args:*
* pv (obj): A PhysicalVolu... | [
"def",
"remove_pv",
"(",
"self",
",",
"pv",
")",
":",
"name",
"=",
"pv",
".",
"name",
"self",
".",
"open",
"(",
")",
"rm",
"=",
"lvm_vg_reduce",
"(",
"self",
".",
"handle",
",",
"name",
")",
"if",
"rm",
"!=",
"0",
":",
"self",
".",
"close",
"("... | Removes a physical volume from the volume group::
from lvm2py import *
lvm = LVM()
vg = lvm.get_vg("myvg", "w")
pv = vg.pvscan()[0]
vg.remove_pv(pv)
*Args:*
* pv (obj): A PhysicalVolume instance.
*Raises:*
* ... | [
"Removes",
"a",
"physical",
"volume",
"from",
"the",
"volume",
"group",
"::"
] | python | train |
hsolbrig/PyShEx | pyshex/shape_expressions_language/p5_4_node_constraints.py | https://github.com/hsolbrig/PyShEx/blob/9d659cc36e808afd66d4a6d60e8ea21cb12eb744/pyshex/shape_expressions_language/p5_4_node_constraints.py#L216-L269 | def _nodeSatisfiesValue(cntxt: Context, n: Node, vsv: ShExJ.valueSetValue) -> bool:
"""
A term matches a valueSetValue if:
* vsv is an objectValue and n = vsv.
* vsv is a Language with langTag lt and n is a language-tagged string with a language tag l and l = lt.
* vsv is a IriStem, Lite... | [
"def",
"_nodeSatisfiesValue",
"(",
"cntxt",
":",
"Context",
",",
"n",
":",
"Node",
",",
"vsv",
":",
"ShExJ",
".",
"valueSetValue",
")",
"->",
"bool",
":",
"vsv",
"=",
"map_object_literal",
"(",
"vsv",
")",
"if",
"isinstance_",
"(",
"vsv",
",",
"ShExJ",
... | A term matches a valueSetValue if:
* vsv is an objectValue and n = vsv.
* vsv is a Language with langTag lt and n is a language-tagged string with a language tag l and l = lt.
* vsv is a IriStem, LiteralStem or LanguageStem with stem st and nodeIn(n, st).
* vsv is a IriStemRange, Literal... | [
"A",
"term",
"matches",
"a",
"valueSetValue",
"if",
":",
"*",
"vsv",
"is",
"an",
"objectValue",
"and",
"n",
"=",
"vsv",
".",
"*",
"vsv",
"is",
"a",
"Language",
"with",
"langTag",
"lt",
"and",
"n",
"is",
"a",
"language",
"-",
"tagged",
"string",
"with... | python | train |
ihgazni2/edict | edict/edict.py | https://github.com/ihgazni2/edict/blob/44a08ccc10b196aa3854619b4c51ddb246778a34/edict/edict.py#L109-L129 | def _reorder_via_klist(d,nkl,**kwargs):
'''
d = {'scheme': 'http', 'path': '/index.php', 'params': 'params', 'query': 'username=query', 'fragment': 'frag', 'username': '', 'password': '', 'hostname': 'www.baidu.com', 'port': ''}
pobj(d)
nkl = ['scheme', 'username', 'password', 'hostname', 'p... | [
"def",
"_reorder_via_klist",
"(",
"d",
",",
"nkl",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"'deepcopy'",
"in",
"kwargs",
")",
":",
"deepcopy",
"=",
"kwargs",
"[",
"'deepcopy'",
"]",
"else",
":",
"deepcopy",
"=",
"True",
"if",
"(",
"deepcopy",
"... | d = {'scheme': 'http', 'path': '/index.php', 'params': 'params', 'query': 'username=query', 'fragment': 'frag', 'username': '', 'password': '', 'hostname': 'www.baidu.com', 'port': ''}
pobj(d)
nkl = ['scheme', 'username', 'password', 'hostname', 'port', 'path', 'params', 'query', 'fragment']
pob... | [
"d",
"=",
"{",
"scheme",
":",
"http",
"path",
":",
"/",
"index",
".",
"php",
"params",
":",
"params",
"query",
":",
"username",
"=",
"query",
"fragment",
":",
"frag",
"username",
":",
"password",
":",
"hostname",
":",
"www",
".",
"baidu",
".",
"com",... | python | train |
casacore/python-casacore | casacore/images/image.py | https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L586-L612 | def view(self, tempname='/tmp/tempimage'):
"""Display the image using casaviewer.
If the image is not persistent, a copy will be made that the user
has to delete once viewing has finished. The name of the copy can be
given in argument `tempname`. Default is '/tmp/tempimage'.
""... | [
"def",
"view",
"(",
"self",
",",
"tempname",
"=",
"'/tmp/tempimage'",
")",
":",
"import",
"os",
"# Test if casaviewer can be found.",
"# On OS-X 'which' always returns 0, so use test on top of it.",
"if",
"os",
".",
"system",
"(",
"'test -x `which casaviewer` > /dev/null 2>&1'"... | Display the image using casaviewer.
If the image is not persistent, a copy will be made that the user
has to delete once viewing has finished. The name of the copy can be
given in argument `tempname`. Default is '/tmp/tempimage'. | [
"Display",
"the",
"image",
"using",
"casaviewer",
"."
] | python | train |
CiscoUcs/UcsPythonSDK | src/UcsSdk/UcsBase.py | https://github.com/CiscoUcs/UcsPythonSDK/blob/bf6b07d6abeacb922c92b198352eda4eb9e4629b/src/UcsSdk/UcsBase.py#L829-L842 | def Expandkey(key, clen):
""" Internal method supporting encryption and decryption functionality. """
import sha
from string import join
from array import array
blocks = (clen + 19) / 20
xkey = []
seed = key
for i in xrange(blocks):
seed = sha.new(key + seed).digest()
xkey.append(seed)
j = join... | [
"def",
"Expandkey",
"(",
"key",
",",
"clen",
")",
":",
"import",
"sha",
"from",
"string",
"import",
"join",
"from",
"array",
"import",
"array",
"blocks",
"=",
"(",
"clen",
"+",
"19",
")",
"/",
"20",
"xkey",
"=",
"[",
"]",
"seed",
"=",
"key",
"for",... | Internal method supporting encryption and decryption functionality. | [
"Internal",
"method",
"supporting",
"encryption",
"and",
"decryption",
"functionality",
"."
] | python | train |
KnowledgeLinks/rdfframework | rdfframework/search/esmappings.py | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/search/esmappings.py#L134-L198 | def send_es_mapping(self, es_map, **kwargs):
"""
sends the mapping to elasticsearch
args:
es_map: dictionary of the index mapping
kwargs:
reset_idx: WARNING! If True the current referenced es index
will be deleted destroying all data... | [
"def",
"send_es_mapping",
"(",
"self",
",",
"es_map",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"setLevel",
"(",
"kwargs",
".",
"get",
"(",
"'log_level'",
",",
"self",
".",
"log_level",
")",
")",
"def",
"next_es_index_version",
"(",
"curr_alias",
")... | sends the mapping to elasticsearch
args:
es_map: dictionary of the index mapping
kwargs:
reset_idx: WARNING! If True the current referenced es index
will be deleted destroying all data in that index in
elasticsearch. if False an i... | [
"sends",
"the",
"mapping",
"to",
"elasticsearch",
"args",
":",
"es_map",
":",
"dictionary",
"of",
"the",
"index",
"mapping",
"kwargs",
":",
"reset_idx",
":",
"WARNING!",
"If",
"True",
"the",
"current",
"referenced",
"es",
"index",
"will",
"be",
"deleted",
"d... | python | train |
openego/eDisGo | edisgo/grid/network.py | https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/grid/network.py#L43-L75 | def plot_mv_grid_topology(self, technologies=False, **kwargs):
"""
Plots plain MV grid topology and optionally nodes by technology type
(e.g. station or generator).
Parameters
----------
technologies : :obj:`Boolean`
If True plots stations, generators, etc. i... | [
"def",
"plot_mv_grid_topology",
"(",
"self",
",",
"technologies",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"network",
".",
"pypsa",
"is",
"None",
":",
"try",
":",
"timesteps",
"=",
"self",
".",
"network",
".",
"timeseries",
"... | Plots plain MV grid topology and optionally nodes by technology type
(e.g. station or generator).
Parameters
----------
technologies : :obj:`Boolean`
If True plots stations, generators, etc. in the grid in different
colors. If False does not plot any nodes. Defau... | [
"Plots",
"plain",
"MV",
"grid",
"topology",
"and",
"optionally",
"nodes",
"by",
"technology",
"type",
"(",
"e",
".",
"g",
".",
"station",
"or",
"generator",
")",
"."
] | python | train |
the01/python-floscraper | floscraper/models.py | https://github.com/the01/python-floscraper/blob/d578cd3d6381070d9a07dade1e10387ae33e9a65/floscraper/models.py#L115-L131 | def from_dict(d):
"""
Response from dict
:param d: Dict to load
:type d: dict
:return: response
:rtype: Response
"""
if d is None:
return None
return Response(
d.get('html'),
CacheInfo.from_dict(d.get('cache_inf... | [
"def",
"from_dict",
"(",
"d",
")",
":",
"if",
"d",
"is",
"None",
":",
"return",
"None",
"return",
"Response",
"(",
"d",
".",
"get",
"(",
"'html'",
")",
",",
"CacheInfo",
".",
"from_dict",
"(",
"d",
".",
"get",
"(",
"'cache_info'",
")",
")",
",",
... | Response from dict
:param d: Dict to load
:type d: dict
:return: response
:rtype: Response | [
"Response",
"from",
"dict"
] | python | train |
pyQode/pyqode.core | pyqode/core/api/code_edit.py | https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/api/code_edit.py#L788-L796 | def zoom_in(self, increment=1):
"""
Zooms in the editor (makes the font bigger).
:param increment: zoom level increment. Default is 1.
"""
self.zoom_level += increment
TextHelper(self).mark_whole_doc_dirty()
self._reset_stylesheet() | [
"def",
"zoom_in",
"(",
"self",
",",
"increment",
"=",
"1",
")",
":",
"self",
".",
"zoom_level",
"+=",
"increment",
"TextHelper",
"(",
"self",
")",
".",
"mark_whole_doc_dirty",
"(",
")",
"self",
".",
"_reset_stylesheet",
"(",
")"
] | Zooms in the editor (makes the font bigger).
:param increment: zoom level increment. Default is 1. | [
"Zooms",
"in",
"the",
"editor",
"(",
"makes",
"the",
"font",
"bigger",
")",
"."
] | python | train |
etcher-be/emiz | emiz/avwx/core.py | https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L795-L824 | def get_flight_rules(vis: Number, ceiling: Cloud) -> int:
"""
Returns int based on current flight rules from parsed METAR data
0=VFR, 1=MVFR, 2=IFR, 3=LIFR
Note: Common practice is to report IFR if visibility unavailable
"""
# Parse visibility
if not vis:
return 2
if vis.repr =... | [
"def",
"get_flight_rules",
"(",
"vis",
":",
"Number",
",",
"ceiling",
":",
"Cloud",
")",
"->",
"int",
":",
"# Parse visibility",
"if",
"not",
"vis",
":",
"return",
"2",
"if",
"vis",
".",
"repr",
"==",
"'CAVOK'",
"or",
"vis",
".",
"repr",
".",
"startswi... | Returns int based on current flight rules from parsed METAR data
0=VFR, 1=MVFR, 2=IFR, 3=LIFR
Note: Common practice is to report IFR if visibility unavailable | [
"Returns",
"int",
"based",
"on",
"current",
"flight",
"rules",
"from",
"parsed",
"METAR",
"data"
] | python | train |
klen/zeta-library | zetalibrary/scss/__init__.py | https://github.com/klen/zeta-library/blob/b76f89000f467e10ddcc94aded3f6c6bf4a0e5bd/zetalibrary/scss/__init__.py#L2976-L3000 | def _inline_image(image, mime_type=None):
"""
Embeds the contents of a file directly inside your stylesheet, eliminating
the need for another HTTP request. For small files such images or fonts,
this can be a performance benefit at the cost of a larger generated CSS
file.
"""
file = StringVal... | [
"def",
"_inline_image",
"(",
"image",
",",
"mime_type",
"=",
"None",
")",
":",
"file",
"=",
"StringValue",
"(",
"image",
")",
".",
"value",
"mime_type",
"=",
"StringValue",
"(",
"mime_type",
")",
".",
"value",
"or",
"mimetypes",
".",
"guess_type",
"(",
"... | Embeds the contents of a file directly inside your stylesheet, eliminating
the need for another HTTP request. For small files such images or fonts,
this can be a performance benefit at the cost of a larger generated CSS
file. | [
"Embeds",
"the",
"contents",
"of",
"a",
"file",
"directly",
"inside",
"your",
"stylesheet",
"eliminating",
"the",
"need",
"for",
"another",
"HTTP",
"request",
".",
"For",
"small",
"files",
"such",
"images",
"or",
"fonts",
"this",
"can",
"be",
"a",
"performan... | python | train |
brocade/pynos | pynos/versions/ver_6/ver_6_0_1/yang/brocade_port_profile.py | https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_port_profile.py#L433-L446 | def port_profile_qos_profile_qos_trust_trust_cos(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile")
name_key = ET.SubElement(port_profile, "name")
... | [
"def",
"port_profile_qos_profile_qos_trust_trust_cos",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"port_profile",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"port-profile\"",
",",
"xmln... | Auto Generated Code | [
"Auto",
"Generated",
"Code"
] | python | train |
NikolayDachev/jadm | lib/paramiko-1.14.1/paramiko/_winapi.py | https://github.com/NikolayDachev/jadm/blob/12bb550445edfcd87506f7cba7a6a35d413c5511/lib/paramiko-1.14.1/paramiko/_winapi.py#L145-L152 | def read(self, n):
"""
Read n bytes from mapped view.
"""
out = ctypes.create_string_buffer(n)
ctypes.windll.kernel32.RtlMoveMemory(out, self.view + self.pos, n)
self.pos += n
return out.raw | [
"def",
"read",
"(",
"self",
",",
"n",
")",
":",
"out",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"n",
")",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"RtlMoveMemory",
"(",
"out",
",",
"self",
".",
"view",
"+",
"self",
".",
"pos",
",",
"n... | Read n bytes from mapped view. | [
"Read",
"n",
"bytes",
"from",
"mapped",
"view",
"."
] | python | train |
alephdata/memorious | memorious/logic/http.py | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/http.py#L162-L185 | def fetch(self):
"""Lazily trigger download of the data when requested."""
if self._file_path is not None:
return self._file_path
temp_path = self.context.work_path
if self._content_hash is not None:
self._file_path = storage.load_file(self._content_hash,
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"if",
"self",
".",
"_file_path",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_file_path",
"temp_path",
"=",
"self",
".",
"context",
".",
"work_path",
"if",
"self",
".",
"_content_hash",
"is",
"not",
"None",
... | Lazily trigger download of the data when requested. | [
"Lazily",
"trigger",
"download",
"of",
"the",
"data",
"when",
"requested",
"."
] | python | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/text_format.py#L1167-L1180 | def ConsumeString(self):
"""Consumes a string value.
Returns:
The string parsed.
Raises:
ParseError: If a string value couldn't be consumed.
"""
the_bytes = self.ConsumeByteString()
try:
return six.text_type(the_bytes, 'utf-8')
except UnicodeDecodeError as e:
raise ... | [
"def",
"ConsumeString",
"(",
"self",
")",
":",
"the_bytes",
"=",
"self",
".",
"ConsumeByteString",
"(",
")",
"try",
":",
"return",
"six",
".",
"text_type",
"(",
"the_bytes",
",",
"'utf-8'",
")",
"except",
"UnicodeDecodeError",
"as",
"e",
":",
"raise",
"sel... | Consumes a string value.
Returns:
The string parsed.
Raises:
ParseError: If a string value couldn't be consumed. | [
"Consumes",
"a",
"string",
"value",
"."
] | python | train |
ZELLMECHANIK-DRESDEN/dclab | dclab/parse_funcs.py | https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/parse_funcs.py#L43-L52 | def fintlist(alist):
"""A list of integers"""
outlist = []
if not isinstance(alist, (list, tuple)):
# we have a string (comma-separated integers)
alist = alist.strip().strip("[] ").split(",")
for it in alist:
if it:
outlist.append(fint(it))
return outlist | [
"def",
"fintlist",
"(",
"alist",
")",
":",
"outlist",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"alist",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"# we have a string (comma-separated integers)",
"alist",
"=",
"alist",
".",
"strip",
"(",
")",
"... | A list of integers | [
"A",
"list",
"of",
"integers"
] | python | train |
apache/incubator-mxnet | python/mxnet/model.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/model.py#L753-L802 | def score(self, X, eval_metric='acc', num_batch=None, batch_end_callback=None, reset=True):
"""Run the model given an input and calculate the score
as assessed by an evaluation metric.
Parameters
----------
X : mxnet.DataIter
eval_metric : metric.metric
The m... | [
"def",
"score",
"(",
"self",
",",
"X",
",",
"eval_metric",
"=",
"'acc'",
",",
"num_batch",
"=",
"None",
",",
"batch_end_callback",
"=",
"None",
",",
"reset",
"=",
"True",
")",
":",
"# setup metric",
"if",
"not",
"isinstance",
"(",
"eval_metric",
",",
"me... | Run the model given an input and calculate the score
as assessed by an evaluation metric.
Parameters
----------
X : mxnet.DataIter
eval_metric : metric.metric
The metric for calculating score.
num_batch : int or None
The number of batches to run. ... | [
"Run",
"the",
"model",
"given",
"an",
"input",
"and",
"calculate",
"the",
"score",
"as",
"assessed",
"by",
"an",
"evaluation",
"metric",
"."
] | python | train |
DataBiosphere/toil | src/toil/job.py | https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/job.py#L1364-L1379 | def _runner(self, jobGraph, jobStore, fileStore):
"""
This method actually runs the job, and serialises the next jobs.
:param class jobGraph: Instance of a jobGraph object
:param class jobStore: Instance of the job store
:param toil.fileStore.FileStore fileStore: Instance of a C... | [
"def",
"_runner",
"(",
"self",
",",
"jobGraph",
",",
"jobStore",
",",
"fileStore",
")",
":",
"# Make fileStore available as an attribute during run() ...",
"self",
".",
"_fileStore",
"=",
"fileStore",
"# ... but also pass it to run() as an argument for backwards compatibility.",
... | This method actually runs the job, and serialises the next jobs.
:param class jobGraph: Instance of a jobGraph object
:param class jobStore: Instance of the job store
:param toil.fileStore.FileStore fileStore: Instance of a Cached on uncached
filestore
:return: | [
"This",
"method",
"actually",
"runs",
"the",
"job",
"and",
"serialises",
"the",
"next",
"jobs",
"."
] | python | train |
gmr/tinman | tinman/application.py | https://github.com/gmr/tinman/blob/98f0acd15a228d752caa1864cdf02aaa3d492a9f/tinman/application.py#L124-L137 | def _prepare_paths(self):
"""Set the value of {{base}} in paths if the base path is set in the
configuration.
:raises: ValueError
"""
if config.BASE in self.paths:
for path in [path for path in self.paths if path != config.BASE]:
if config.BASE_VARIA... | [
"def",
"_prepare_paths",
"(",
"self",
")",
":",
"if",
"config",
".",
"BASE",
"in",
"self",
".",
"paths",
":",
"for",
"path",
"in",
"[",
"path",
"for",
"path",
"in",
"self",
".",
"paths",
"if",
"path",
"!=",
"config",
".",
"BASE",
"]",
":",
"if",
... | Set the value of {{base}} in paths if the base path is set in the
configuration.
:raises: ValueError | [
"Set",
"the",
"value",
"of",
"{{",
"base",
"}}",
"in",
"paths",
"if",
"the",
"base",
"path",
"is",
"set",
"in",
"the",
"configuration",
"."
] | python | train |
inasafe/inasafe | safe/gui/tools/wizard/step_fc90_analysis.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L312-L319 | def hide_busy(self):
"""Unlock buttons A helper function to indicate processing is done."""
self.progress_bar.hide()
self.parent.pbnNext.setEnabled(True)
self.parent.pbnBack.setEnabled(True)
self.parent.pbnCancel.setEnabled(True)
self.parent.repaint()
disable_busy... | [
"def",
"hide_busy",
"(",
"self",
")",
":",
"self",
".",
"progress_bar",
".",
"hide",
"(",
")",
"self",
".",
"parent",
".",
"pbnNext",
".",
"setEnabled",
"(",
"True",
")",
"self",
".",
"parent",
".",
"pbnBack",
".",
"setEnabled",
"(",
"True",
")",
"se... | Unlock buttons A helper function to indicate processing is done. | [
"Unlock",
"buttons",
"A",
"helper",
"function",
"to",
"indicate",
"processing",
"is",
"done",
"."
] | python | train |
mitsei/dlkit | dlkit/json_/grading/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/grading/sessions.py#L1883-L1905 | def get_grade_entries_by_genus_type(self, grade_entry_genus_type):
"""Gets a ``GradeEntryList`` corresponding to the given grade entry genus ``Type`` which does not include grade entries of genus types derived from the specified ``Type``.
arg: grade_entry_genus_type (osid.type.Type): a grade entry
... | [
"def",
"get_grade_entries_by_genus_type",
"(",
"self",
",",
"grade_entry_genus_type",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resources_by_genus_type",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClie... | Gets a ``GradeEntryList`` corresponding to the given grade entry genus ``Type`` which does not include grade entries of genus types derived from the specified ``Type``.
arg: grade_entry_genus_type (osid.type.Type): a grade entry
genus type
return: (osid.grading.GradeEntryList) - the ... | [
"Gets",
"a",
"GradeEntryList",
"corresponding",
"to",
"the",
"given",
"grade",
"entry",
"genus",
"Type",
"which",
"does",
"not",
"include",
"grade",
"entries",
"of",
"genus",
"types",
"derived",
"from",
"the",
"specified",
"Type",
"."
] | python | train |
pantsbuild/pants | src/python/pants/backend/jvm/subsystems/jvm_platform.py | https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/backend/jvm/subsystems/jvm_platform.py#L155-L175 | def parse_java_version(cls, version):
"""Parses the java version (given a string or Revision object).
Handles java version-isms, converting things like '7' -> '1.7' appropriately.
Truncates input versions down to just the major and minor numbers (eg, 1.6), ignoring extra
versioning information after t... | [
"def",
"parse_java_version",
"(",
"cls",
",",
"version",
")",
":",
"conversion",
"=",
"{",
"str",
"(",
"i",
")",
":",
"'1.{}'",
".",
"format",
"(",
"i",
")",
"for",
"i",
"in",
"cls",
".",
"SUPPORTED_CONVERSION_VERSIONS",
"}",
"if",
"str",
"(",
"version... | Parses the java version (given a string or Revision object).
Handles java version-isms, converting things like '7' -> '1.7' appropriately.
Truncates input versions down to just the major and minor numbers (eg, 1.6), ignoring extra
versioning information after the second number.
:param version: the in... | [
"Parses",
"the",
"java",
"version",
"(",
"given",
"a",
"string",
"or",
"Revision",
"object",
")",
"."
] | python | train |
google/apitools | apitools/base/py/base_api.py | https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/base_api.py#L689-L731 | def _RunMethod(self, method_config, request, global_params=None,
upload=None, upload_config=None, download=None):
"""Call this method with request."""
if upload is not None and download is not None:
# TODO(craigcitro): This just involves refactoring the logic
#... | [
"def",
"_RunMethod",
"(",
"self",
",",
"method_config",
",",
"request",
",",
"global_params",
"=",
"None",
",",
"upload",
"=",
"None",
",",
"upload_config",
"=",
"None",
",",
"download",
"=",
"None",
")",
":",
"if",
"upload",
"is",
"not",
"None",
"and",
... | Call this method with request. | [
"Call",
"this",
"method",
"with",
"request",
"."
] | python | train |
saltstack/salt | salt/utils/extend.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/extend.py#L45-L61 | def _get_template(path, option_key):
'''
Get the contents of a template file and provide it as a module type
:param path: path to the template.yml file
:type path: ``str``
:param option_key: The unique key of this template
:type option_key: ``str``
:returns: Details about the template
... | [
"def",
"_get_template",
"(",
"path",
",",
"option_key",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"path",
",",
"'r'",
")",
"as",
"template_f",
":",
"template",
"=",
"deserialize",
"(",
"template_f",
")",
"info",
"=",
"(",... | Get the contents of a template file and provide it as a module type
:param path: path to the template.yml file
:type path: ``str``
:param option_key: The unique key of this template
:type option_key: ``str``
:returns: Details about the template
:rtype: ``tuple`` | [
"Get",
"the",
"contents",
"of",
"a",
"template",
"file",
"and",
"provide",
"it",
"as",
"a",
"module",
"type"
] | python | train |
praekeltfoundation/seed-identity-store | identities/views.py | https://github.com/praekeltfoundation/seed-identity-store/blob/194e5756b5a74ebce9798c390de958cf5305b105/identities/views.py#L131-L210 | def get_queryset(self):
"""
This view should return a list of all the Identities
for the supplied query parameters. The query parameters
should be in the form:
{"address_type": "address"}
e.g.
{"msisdn": "+27123"}
{"email": "foo@bar.com"}
A specia... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"query_params",
"=",
"list",
"(",
"self",
".",
"request",
".",
"query_params",
".",
"keys",
"(",
")",
")",
"# variable that stores criteria to filter identities by",
"filter_criteria",
"=",
"{",
"}",
"# variable that sto... | This view should return a list of all the Identities
for the supplied query parameters. The query parameters
should be in the form:
{"address_type": "address"}
e.g.
{"msisdn": "+27123"}
{"email": "foo@bar.com"}
A special query paramater "include_inactive" can als... | [
"This",
"view",
"should",
"return",
"a",
"list",
"of",
"all",
"the",
"Identities",
"for",
"the",
"supplied",
"query",
"parameters",
".",
"The",
"query",
"parameters",
"should",
"be",
"in",
"the",
"form",
":",
"{",
"address_type",
":",
"address",
"}",
"e",
... | python | train |
resonai/ybt | yabt/caching.py | https://github.com/resonai/ybt/blob/5b40df0922ef3383eb85f2b04a26a2db4b81b3fd/yabt/caching.py#L177-L197 | def copy_artifact(src_path: str, artifact_hash: str, conf: Config):
"""Copy the artifact at `src_path` with hash `artifact_hash` to artifacts
cache dir.
If an artifact already exists at that location, it is assumed to be
identical (since it's based on hash), and the copy is skipped.
TODO: pruni... | [
"def",
"copy_artifact",
"(",
"src_path",
":",
"str",
",",
"artifact_hash",
":",
"str",
",",
"conf",
":",
"Config",
")",
":",
"cache_dir",
"=",
"conf",
".",
"get_artifacts_cache_dir",
"(",
")",
"if",
"not",
"isdir",
"(",
"cache_dir",
")",
":",
"makedirs",
... | Copy the artifact at `src_path` with hash `artifact_hash` to artifacts
cache dir.
If an artifact already exists at that location, it is assumed to be
identical (since it's based on hash), and the copy is skipped.
TODO: pruning policy to limit cache size. | [
"Copy",
"the",
"artifact",
"at",
"src_path",
"with",
"hash",
"artifact_hash",
"to",
"artifacts",
"cache",
"dir",
"."
] | python | train |
mpapi/lazylights | lazylights.py | https://github.com/mpapi/lazylights/blob/536dbd3ce75c28b3545cf66f25fc72589488063f/lazylights.py#L140-L162 | def _retry(event, attempts, delay):
"""
An iterator of pairs of (attempt number, event set), checking whether
`event` is set up to `attempts` number of times, and delaying `delay`
seconds in between.
Terminates as soon as `event` is set, or until `attempts` have been made.
Intended to be used ... | [
"def",
"_retry",
"(",
"event",
",",
"attempts",
",",
"delay",
")",
":",
"event",
".",
"clear",
"(",
")",
"attempted",
"=",
"0",
"while",
"attempted",
"<",
"attempts",
"and",
"not",
"event",
".",
"is_set",
"(",
")",
":",
"yield",
"attempted",
",",
"ev... | An iterator of pairs of (attempt number, event set), checking whether
`event` is set up to `attempts` number of times, and delaying `delay`
seconds in between.
Terminates as soon as `event` is set, or until `attempts` have been made.
Intended to be used in a loop, as in:
for num, ok in _retry... | [
"An",
"iterator",
"of",
"pairs",
"of",
"(",
"attempt",
"number",
"event",
"set",
")",
"checking",
"whether",
"event",
"is",
"set",
"up",
"to",
"attempts",
"number",
"of",
"times",
"and",
"delaying",
"delay",
"seconds",
"in",
"between",
"."
] | python | train |
python-openxml/python-docx | docx/blkcntnr.py | https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/blkcntnr.py#L42-L51 | def add_table(self, rows, cols, width):
"""
Return a table of *width* having *rows* rows and *cols* columns,
newly appended to the content in this container. *width* is evenly
distributed between the table columns.
"""
from .table import Table
tbl = CT_Tbl.new_tbl... | [
"def",
"add_table",
"(",
"self",
",",
"rows",
",",
"cols",
",",
"width",
")",
":",
"from",
".",
"table",
"import",
"Table",
"tbl",
"=",
"CT_Tbl",
".",
"new_tbl",
"(",
"rows",
",",
"cols",
",",
"width",
")",
"self",
".",
"_element",
".",
"_insert_tbl"... | Return a table of *width* having *rows* rows and *cols* columns,
newly appended to the content in this container. *width* is evenly
distributed between the table columns. | [
"Return",
"a",
"table",
"of",
"*",
"width",
"*",
"having",
"*",
"rows",
"*",
"rows",
"and",
"*",
"cols",
"*",
"columns",
"newly",
"appended",
"to",
"the",
"content",
"in",
"this",
"container",
".",
"*",
"width",
"*",
"is",
"evenly",
"distributed",
"bet... | python | train |
twilio/twilio-python | twilio/rest/messaging/v1/service/alpha_sender.py | https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/messaging/v1/service/alpha_sender.py#L137-L146 | def get(self, sid):
"""
Constructs a AlphaSenderContext
:param sid: The sid
:returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext
:rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext
"""
return AlphaSenderContext(self._ve... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"AlphaSenderContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | Constructs a AlphaSenderContext
:param sid: The sid
:returns: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext
:rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderContext | [
"Constructs",
"a",
"AlphaSenderContext"
] | python | train |
denisenkom/pytds | src/pytds/tds.py | https://github.com/denisenkom/pytds/blob/7d875cab29134afdef719406831c1c6a0d7af48a/src/pytds/tds.py#L947-L960 | def _convert_params(self, parameters):
""" Converts a dict of list of parameters into a list of :class:`Column` instances.
:param parameters: Can be a list of parameter values, or a dict of parameter names to values.
:return: A list of :class:`Column` instances.
"""
if isinstanc... | [
"def",
"_convert_params",
"(",
"self",
",",
"parameters",
")",
":",
"if",
"isinstance",
"(",
"parameters",
",",
"dict",
")",
":",
"return",
"[",
"self",
".",
"make_param",
"(",
"name",
",",
"value",
")",
"for",
"name",
",",
"value",
"in",
"parameters",
... | Converts a dict of list of parameters into a list of :class:`Column` instances.
:param parameters: Can be a list of parameter values, or a dict of parameter names to values.
:return: A list of :class:`Column` instances. | [
"Converts",
"a",
"dict",
"of",
"list",
"of",
"parameters",
"into",
"a",
"list",
"of",
":",
"class",
":",
"Column",
"instances",
"."
] | python | train |
sony/nnabla | python/src/nnabla/parameter.py | https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parameter.py#L149-L167 | def pop_parameter(key):
'''Remove and get parameter by key.
Args:
key(str): Key of parameter.
Returns: ~nnabla.Variable
Parameter if key found, otherwise None.
'''
names = key.split('/')
if len(names) > 1:
with parameter_scope(names[0]):
return pop_paramete... | [
"def",
"pop_parameter",
"(",
"key",
")",
":",
"names",
"=",
"key",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"names",
")",
">",
"1",
":",
"with",
"parameter_scope",
"(",
"names",
"[",
"0",
"]",
")",
":",
"return",
"pop_parameter",
"(",
"'/'"... | Remove and get parameter by key.
Args:
key(str): Key of parameter.
Returns: ~nnabla.Variable
Parameter if key found, otherwise None. | [
"Remove",
"and",
"get",
"parameter",
"by",
"key",
"."
] | python | train |
harlowja/failure | failure/finders.py | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/finders.py#L100-L110 | def combine_or(matcher, *more_matchers):
"""Combines more than one matcher together (first that matches wins)."""
def matcher(cause):
for sub_matcher in itertools.chain([matcher], more_matchers):
cause_cls = sub_matcher(cause)
if cause_cls is not None:
return cau... | [
"def",
"combine_or",
"(",
"matcher",
",",
"*",
"more_matchers",
")",
":",
"def",
"matcher",
"(",
"cause",
")",
":",
"for",
"sub_matcher",
"in",
"itertools",
".",
"chain",
"(",
"[",
"matcher",
"]",
",",
"more_matchers",
")",
":",
"cause_cls",
"=",
"sub_ma... | Combines more than one matcher together (first that matches wins). | [
"Combines",
"more",
"than",
"one",
"matcher",
"together",
"(",
"first",
"that",
"matches",
"wins",
")",
"."
] | python | train |
deepmind/sonnet | sonnet/python/modules/basic.py | https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/basic.py#L868-L874 | def transpose(self, name=None):
"""Returns transpose batch reshape."""
if name is None:
name = self.module_name + "_transpose"
return BatchReshape(shape=lambda: self.input_shape,
preserve_dims=self._preserve_dims,
name=name) | [
"def",
"transpose",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"module_name",
"+",
"\"_transpose\"",
"return",
"BatchReshape",
"(",
"shape",
"=",
"lambda",
":",
"self",
".",
"input_shape",
... | Returns transpose batch reshape. | [
"Returns",
"transpose",
"batch",
"reshape",
"."
] | python | train |
pypa/pipenv | pipenv/vendor/pipdeptree.py | https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/pipdeptree.py#L460-L476 | def conflicting_deps(tree):
"""Returns dependencies which are not present or conflict with the
requirements of other packages.
e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed
:param tree: the requirements tree (dict)
:returns: dict of DistPackage -> list of unsatisfied/unknown... | [
"def",
"conflicting_deps",
"(",
"tree",
")",
":",
"conflicting",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"p",
",",
"rs",
"in",
"tree",
".",
"items",
"(",
")",
":",
"for",
"req",
"in",
"rs",
":",
"if",
"req",
".",
"is_conflicting",
"(",
")",
":... | Returns dependencies which are not present or conflict with the
requirements of other packages.
e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed
:param tree: the requirements tree (dict)
:returns: dict of DistPackage -> list of unsatisfied/unknown ReqPackage
:rtype: dict | [
"Returns",
"dependencies",
"which",
"are",
"not",
"present",
"or",
"conflict",
"with",
"the",
"requirements",
"of",
"other",
"packages",
"."
] | python | train |
Jammy2211/PyAutoLens | autolens/model/profiles/mass_profiles.py | https://github.com/Jammy2211/PyAutoLens/blob/91e50369c7a9c048c83d217625578b72423cd5a7/autolens/model/profiles/mass_profiles.py#L1438-L1450 | def deflections_from_grid(self, grid):
"""
Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
"""
... | [
"def",
"deflections_from_grid",
"(",
"self",
",",
"grid",
")",
":",
"eta",
"=",
"np",
".",
"multiply",
"(",
"1.",
"/",
"self",
".",
"scale_radius",
",",
"self",
".",
"grid_to_grid_radii",
"(",
"grid",
"=",
"grid",
")",
")",
"deflection_r",
"=",
"np",
"... | Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on. | [
"Calculate",
"the",
"deflection",
"angles",
"at",
"a",
"given",
"set",
"of",
"arc",
"-",
"second",
"gridded",
"coordinates",
"."
] | python | valid |
quantopian/zipline | zipline/data/hdf5_daily_bars.py | https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/hdf5_daily_bars.py#L360-L391 | def compute_asset_lifetimes(frames):
"""
Parameters
----------
frames : dict[str, pd.DataFrame]
A dict mapping each OHLCV field to a dataframe with a row for
each date and a column for each sid, as passed to write().
Returns
-------
start_date_ixs : np.array[int64]
T... | [
"def",
"compute_asset_lifetimes",
"(",
"frames",
")",
":",
"# Build a 2D array (dates x sids), where an entry is True if all",
"# fields are nan for the given day and sid.",
"is_null_matrix",
"=",
"np",
".",
"logical_and",
".",
"reduce",
"(",
"[",
"frames",
"[",
"field",
"]",... | Parameters
----------
frames : dict[str, pd.DataFrame]
A dict mapping each OHLCV field to a dataframe with a row for
each date and a column for each sid, as passed to write().
Returns
-------
start_date_ixs : np.array[int64]
The index of the first date with non-nan values, f... | [
"Parameters",
"----------",
"frames",
":",
"dict",
"[",
"str",
"pd",
".",
"DataFrame",
"]",
"A",
"dict",
"mapping",
"each",
"OHLCV",
"field",
"to",
"a",
"dataframe",
"with",
"a",
"row",
"for",
"each",
"date",
"and",
"a",
"column",
"for",
"each",
"sid",
... | python | train |
thavel/synolopy | synolopy/cgi.py | https://github.com/thavel/synolopy/blob/fdb23cdde693b13a59af9873f03b2afab35cb50e/synolopy/cgi.py#L80-L86 | def auth_required(self):
"""
If any ancestor required an authentication, this node needs it too.
"""
if self._auth:
return self._auth, self
return self.__parent__.auth_required() | [
"def",
"auth_required",
"(",
"self",
")",
":",
"if",
"self",
".",
"_auth",
":",
"return",
"self",
".",
"_auth",
",",
"self",
"return",
"self",
".",
"__parent__",
".",
"auth_required",
"(",
")"
] | If any ancestor required an authentication, this node needs it too. | [
"If",
"any",
"ancestor",
"required",
"an",
"authentication",
"this",
"node",
"needs",
"it",
"too",
"."
] | python | train |
Azure/azure-sdk-for-python | azure-servicebus/azure/servicebus/control_client/servicebusservice.py | https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicebus/azure/servicebus/control_client/servicebusservice.py#L535-L568 | def create_subscription(self, topic_name, subscription_name,
subscription=None, fail_on_exist=False):
'''
Creates a new subscription. Once created, this subscription resource
manifest is immutable.
topic_name:
Name of the topic.
subscripti... | [
"def",
"create_subscription",
"(",
"self",
",",
"topic_name",
",",
"subscription_name",
",",
"subscription",
"=",
"None",
",",
"fail_on_exist",
"=",
"False",
")",
":",
"_validate_not_none",
"(",
"'topic_name'",
",",
"topic_name",
")",
"_validate_not_none",
"(",
"'... | Creates a new subscription. Once created, this subscription resource
manifest is immutable.
topic_name:
Name of the topic.
subscription_name:
Name of the subscription.
fail_on_exist:
Specify whether throw exception when subscription exists. | [
"Creates",
"a",
"new",
"subscription",
".",
"Once",
"created",
"this",
"subscription",
"resource",
"manifest",
"is",
"immutable",
"."
] | python | test |
limpyd/redis-limpyd | limpyd/fields.py | https://github.com/limpyd/redis-limpyd/blob/3c745dde1390a0bd09690b77a089dcc08c6c7e43/limpyd/fields.py#L100-L115 | def _call_command(self, name, *args, **kwargs):
"""
Check if the command to be executed is a modifier, to connect the object.
Then call _traverse_command.
"""
obj = getattr(self, '_instance', self) # _instance if a field, self if an instance
# The object may not be alre... | [
"def",
"_call_command",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"getattr",
"(",
"self",
",",
"'_instance'",
",",
"self",
")",
"# _instance if a field, self if an instance",
"# The object may not be already connect... | Check if the command to be executed is a modifier, to connect the object.
Then call _traverse_command. | [
"Check",
"if",
"the",
"command",
"to",
"be",
"executed",
"is",
"a",
"modifier",
"to",
"connect",
"the",
"object",
".",
"Then",
"call",
"_traverse_command",
"."
] | python | train |
StackStorm/pybind | pybind/slxos/v17s_1_02/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/__init__.py#L6912-L6935 | def _set_mpls_state(self, v, load=False):
"""
Setter method for mpls_state, mapped from YANG variable /mpls_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_state is considered as a private
method. Backends looking to populate this variable shou... | [
"def",
"_set_mpls_state",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"bas... | Setter method for mpls_state, mapped from YANG variable /mpls_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mpls_state() dir... | [
"Setter",
"method",
"for",
"mpls_state",
"mapped",
"from",
"YANG",
"variable",
"/",
"mpls_state",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false",
")",
"in",
"the",
"source",
"YANG",
"file",
"then",
... | python | train |
fracpete/python-weka-wrapper3 | python/weka/flow/source.py | https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/source.py#L317-L334 | def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(Get... | [
"def",
"fix_config",
"(",
"self",
",",
"options",
")",
":",
"options",
"=",
"super",
"(",
"GetStorageValue",
",",
"self",
")",
".",
"fix_config",
"(",
"options",
")",
"opt",
"=",
"\"storage_name\"",
"if",
"opt",
"not",
"in",
"options",
":",
"options",
"[... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | [
"Fixes",
"the",
"options",
"if",
"necessary",
".",
"I",
".",
"e",
".",
"it",
"adds",
"all",
"required",
"elements",
"to",
"the",
"dictionary",
"."
] | python | train |
newville/wxmplot | examples/tifffile.py | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/tifffile.py#L874-L989 | def _process_tags(self):
"""Validate standard tags and initialize attributes.
Raise ValueError if tag values are not supported.
"""
tags = self.tags
for code, (name, default, dtype, count, validate) in TIFF_TAGS.items():
if not (name in tags or default is None):
... | [
"def",
"_process_tags",
"(",
"self",
")",
":",
"tags",
"=",
"self",
".",
"tags",
"for",
"code",
",",
"(",
"name",
",",
"default",
",",
"dtype",
",",
"count",
",",
"validate",
")",
"in",
"TIFF_TAGS",
".",
"items",
"(",
")",
":",
"if",
"not",
"(",
... | Validate standard tags and initialize attributes.
Raise ValueError if tag values are not supported. | [
"Validate",
"standard",
"tags",
"and",
"initialize",
"attributes",
"."
] | python | train |
SmokinCaterpillar/pypet | pypet/naturalnaming.py | https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/naturalnaming.py#L981-L1071 | def _add_prefix(self, split_names, start_node, group_type_name):
"""Adds the correct sub branch prefix to a given name.
Usually the prefix is the full name of the parent node. In case items are added
directly to the trajectory the prefixes are chosen according to the matching subbranch.
... | [
"def",
"_add_prefix",
"(",
"self",
",",
"split_names",
",",
"start_node",
",",
"group_type_name",
")",
":",
"root",
"=",
"self",
".",
"_root_instance",
"# If the start node of our insertion is root or one below root",
"# we might need to add prefixes.",
"# In case of derived pa... | Adds the correct sub branch prefix to a given name.
Usually the prefix is the full name of the parent node. In case items are added
directly to the trajectory the prefixes are chosen according to the matching subbranch.
For example, this could be 'parameters' for parameters or 'results.run_000... | [
"Adds",
"the",
"correct",
"sub",
"branch",
"prefix",
"to",
"a",
"given",
"name",
"."
] | python | test |
takluyver/entrypoints | entrypoints.py | https://github.com/takluyver/entrypoints/blob/d7db29fd6136f86498d8c374f531d4c198d66bf6/entrypoints.py#L90-L106 | def from_string(cls, epstr, name, distro=None):
"""Parse an entry point from the syntax in entry_points.txt
:param str epstr: The entry point string (not including 'name =')
:param str name: The name of this entry point
:param Distribution distro: The distribution in which the entry poi... | [
"def",
"from_string",
"(",
"cls",
",",
"epstr",
",",
"name",
",",
"distro",
"=",
"None",
")",
":",
"m",
"=",
"entry_point_pattern",
".",
"match",
"(",
"epstr",
")",
"if",
"m",
":",
"mod",
",",
"obj",
",",
"extras",
"=",
"m",
".",
"group",
"(",
"'... | Parse an entry point from the syntax in entry_points.txt
:param str epstr: The entry point string (not including 'name =')
:param str name: The name of this entry point
:param Distribution distro: The distribution in which the entry point was found
:rtype: EntryPoint
:raises Bad... | [
"Parse",
"an",
"entry",
"point",
"from",
"the",
"syntax",
"in",
"entry_points",
".",
"txt"
] | python | test |
spulec/moto | moto/ssm/models.py | https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/ssm/models.py#L355-L370 | def list_commands(self, **kwargs):
"""
https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListCommands.html
"""
commands = self._commands
command_id = kwargs.get('CommandId', None)
if command_id:
commands = [self.get_command_by_id(command_id)... | [
"def",
"list_commands",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"commands",
"=",
"self",
".",
"_commands",
"command_id",
"=",
"kwargs",
".",
"get",
"(",
"'CommandId'",
",",
"None",
")",
"if",
"command_id",
":",
"commands",
"=",
"[",
"self",
"."... | https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_ListCommands.html | [
"https",
":",
"//",
"docs",
".",
"aws",
".",
"amazon",
".",
"com",
"/",
"systems",
"-",
"manager",
"/",
"latest",
"/",
"APIReference",
"/",
"API_ListCommands",
".",
"html"
] | python | train |
GNS3/gns3-server | gns3server/controller/link.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/link.py#L339-L345 | def stop_capture(self):
"""
Stop capture on the link
"""
self._capturing = False
self._project.controller.notification.emit("link.updated", self.__json__()) | [
"def",
"stop_capture",
"(",
"self",
")",
":",
"self",
".",
"_capturing",
"=",
"False",
"self",
".",
"_project",
".",
"controller",
".",
"notification",
".",
"emit",
"(",
"\"link.updated\"",
",",
"self",
".",
"__json__",
"(",
")",
")"
] | Stop capture on the link | [
"Stop",
"capture",
"on",
"the",
"link"
] | python | train |
SpriteLink/NIPAP | nipap-www/nipapwww/controllers/error.py | https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap-www/nipapwww/controllers/error.py#L22-L57 | def document(self):
"""Render the error document"""
request = self._py_object.request
resp = request.environ.get('pylons.original_response')
content = literal(resp.body) or cgi.escape(request.GET.get('message', ''))
page = """<!DOCTYPE html>
<html lang="en">
<head>
<... | [
"def",
"document",
"(",
"self",
")",
":",
"request",
"=",
"self",
".",
"_py_object",
".",
"request",
"resp",
"=",
"request",
".",
"environ",
".",
"get",
"(",
"'pylons.original_response'",
")",
"content",
"=",
"literal",
"(",
"resp",
".",
"body",
")",
"or... | Render the error document | [
"Render",
"the",
"error",
"document"
] | python | train |
googledatalab/pydatalab | datalab/context/_project.py | https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/context/_project.py#L97-L107 | def get_default_id(credentials=None):
""" Get default project id.
Returns: the default project id if there is one, or None.
"""
project_id = _utils.get_project_id()
if project_id is None:
projects, _ = Projects(credentials)._retrieve_projects(None, 2)
if len(projects) == 1:
proj... | [
"def",
"get_default_id",
"(",
"credentials",
"=",
"None",
")",
":",
"project_id",
"=",
"_utils",
".",
"get_project_id",
"(",
")",
"if",
"project_id",
"is",
"None",
":",
"projects",
",",
"_",
"=",
"Projects",
"(",
"credentials",
")",
".",
"_retrieve_projects"... | Get default project id.
Returns: the default project id if there is one, or None. | [
"Get",
"default",
"project",
"id",
"."
] | python | train |
zibertscrem/hexdi | hexdi/__init__.py | https://github.com/zibertscrem/hexdi/blob/4875598299c53f984f2bb1b37060fd42bb7aba84/hexdi/__init__.py#L68-L76 | def bind_type(type_to_bind: hexdi.core.restype, accessor: hexdi.core.clstype, lifetime_manager: hexdi.core.ltype):
"""
shortcut for bind_type on root container
:param type_to_bind: type that will be resolved by accessor
:param accessor: accessor for resolving object
:param lifetime_manager: type of... | [
"def",
"bind_type",
"(",
"type_to_bind",
":",
"hexdi",
".",
"core",
".",
"restype",
",",
"accessor",
":",
"hexdi",
".",
"core",
".",
"clstype",
",",
"lifetime_manager",
":",
"hexdi",
".",
"core",
".",
"ltype",
")",
":",
"hexdi",
".",
"core",
".",
"get_... | shortcut for bind_type on root container
:param type_to_bind: type that will be resolved by accessor
:param accessor: accessor for resolving object
:param lifetime_manager: type of lifetime manager for this binding | [
"shortcut",
"for",
"bind_type",
"on",
"root",
"container"
] | python | train |
spyder-ide/spyder | spyder/plugins/variableexplorer/widgets/arrayeditor.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/arrayeditor.py#L573-L578 | def accept_changes(self):
"""Accept changes"""
for (i, j), value in list(self.model.changes.items()):
self.data[i, j] = value
if self.old_data_shape is not None:
self.data.shape = self.old_data_shape | [
"def",
"accept_changes",
"(",
"self",
")",
":",
"for",
"(",
"i",
",",
"j",
")",
",",
"value",
"in",
"list",
"(",
"self",
".",
"model",
".",
"changes",
".",
"items",
"(",
")",
")",
":",
"self",
".",
"data",
"[",
"i",
",",
"j",
"]",
"=",
"value... | Accept changes | [
"Accept",
"changes"
] | python | train |
numenta/htmresearch | htmresearch/frameworks/location/location_network_creation.py | https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/frameworks/location/location_network_creation.py#L512-L555 | def learn(self, objects):
"""
Learns all provided objects
:param objects: dict mapping object name to array of sensations, where each
sensation is composed of location and feature SDR for each
column. For example:
{'obj1' : [[[1,1,1],[101,205,523,... | [
"def",
"learn",
"(",
"self",
",",
"objects",
")",
":",
"self",
".",
"setLearning",
"(",
"True",
")",
"for",
"objectName",
",",
"sensationList",
"in",
"objects",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"sendReset",
"(",
")",
"print",
"\"Learning :\"... | Learns all provided objects
:param objects: dict mapping object name to array of sensations, where each
sensation is composed of location and feature SDR for each
column. For example:
{'obj1' : [[[1,1,1],[101,205,523, ..., 1021]],...], ...}
... | [
"Learns",
"all",
"provided",
"objects"
] | python | train |
qiniu/python-sdk | qiniu/auth.py | https://github.com/qiniu/python-sdk/blob/a69fbef4e3e6ea1ebe09f4610a5b18bb2c17de59/qiniu/auth.py#L230-L271 | def token_of_request(
self,
method,
host,
url,
qheaders,
content_type=None,
body=None):
"""
<Method> <PathWithRawQuery>
Host: <Host>
Content-Type: <ContentType>
[<X-Qiniu-*> Headers]
[<Bo... | [
"def",
"token_of_request",
"(",
"self",
",",
"method",
",",
"host",
",",
"url",
",",
"qheaders",
",",
"content_type",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"netloc",
"=",
"parsed_url",
".",
"ne... | <Method> <PathWithRawQuery>
Host: <Host>
Content-Type: <ContentType>
[<X-Qiniu-*> Headers]
[<Body>] #这里的 <Body> 只有在 <ContentType> 存在且不为 application/octet-stream 时才签进去。 | [
"<Method",
">",
"<PathWithRawQuery",
">",
"Host",
":",
"<Host",
">",
"Content",
"-",
"Type",
":",
"<ContentType",
">",
"[",
"<X",
"-",
"Qiniu",
"-",
"*",
">",
"Headers",
"]"
] | python | train |
lrq3000/pyFileFixity | pyFileFixity/lib/sortedcontainers/sortedlist.py | https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/sortedcontainers/sortedlist.py#L1517-L1539 | def update(self, iterable):
"""Update the list by adding all elements from *iterable*."""
_maxes, _lists, _keys = self._maxes, self._lists, self._keys
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.fro... | [
"def",
"update",
"(",
"self",
",",
"iterable",
")",
":",
"_maxes",
",",
"_lists",
",",
"_keys",
"=",
"self",
".",
"_maxes",
",",
"self",
".",
"_lists",
",",
"self",
".",
"_keys",
"values",
"=",
"sorted",
"(",
"iterable",
",",
"key",
"=",
"self",
".... | Update the list by adding all elements from *iterable*. | [
"Update",
"the",
"list",
"by",
"adding",
"all",
"elements",
"from",
"*",
"iterable",
"*",
"."
] | python | train |
merll/docker-map | dockermap/dep.py | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/dep.py#L159-L181 | def merge_dependency(self, item, resolve_parent, parents):
"""
Merge dependencies of element with further dependencies. First parent dependencies are checked, and then
immediate dependencies of the current element should be added to the list, but without duplicating any entries.
:param ... | [
"def",
"merge_dependency",
"(",
"self",
",",
"item",
",",
"resolve_parent",
",",
"parents",
")",
":",
"dep",
"=",
"[",
"]",
"for",
"parent_key",
"in",
"parents",
":",
"if",
"item",
"==",
"parent_key",
":",
"raise",
"CircularDependency",
"(",
"item",
",",
... | Merge dependencies of element with further dependencies. First parent dependencies are checked, and then
immediate dependencies of the current element should be added to the list, but without duplicating any entries.
:param item: Item.
:param resolve_parent: Function to resolve parent dependenc... | [
"Merge",
"dependencies",
"of",
"element",
"with",
"further",
"dependencies",
".",
"First",
"parent",
"dependencies",
"are",
"checked",
"and",
"then",
"immediate",
"dependencies",
"of",
"the",
"current",
"element",
"should",
"be",
"added",
"to",
"the",
"list",
"b... | python | train |
maas/python-libmaas | maas/client/utils/diff.py | https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/utils/diff.py#L25-L44 | def calculate_dict_diff(old_params: dict, new_params: dict):
"""Return the parameters based on the difference.
If a parameter exists in `old_params` but not in `new_params` then
parameter will be set to an empty string.
"""
# Ignore all None values as those cannot be saved.
old_params = remove_... | [
"def",
"calculate_dict_diff",
"(",
"old_params",
":",
"dict",
",",
"new_params",
":",
"dict",
")",
":",
"# Ignore all None values as those cannot be saved.",
"old_params",
"=",
"remove_None",
"(",
"old_params",
")",
"new_params",
"=",
"remove_None",
"(",
"new_params",
... | Return the parameters based on the difference.
If a parameter exists in `old_params` but not in `new_params` then
parameter will be set to an empty string. | [
"Return",
"the",
"parameters",
"based",
"on",
"the",
"difference",
"."
] | python | train |
CQCL/pytket | pytket/cirq/cirq_convert.py | https://github.com/CQCL/pytket/blob/ae68f7402dcb5fb45221832cc6185d267bdd7a71/pytket/cirq/cirq_convert.py#L113-L157 | def tk_to_cirq(tkcirc: Circuit, indexed_qubits: List[QubitId]) -> cirq.Circuit:
"""Converts a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` object to a Cirq :py:class:`Circuit`.
:param tkcirc: The input :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit`
:param indexed_qubits: Map from :math:`\\m... | [
"def",
"tk_to_cirq",
"(",
"tkcirc",
":",
"Circuit",
",",
"indexed_qubits",
":",
"List",
"[",
"QubitId",
"]",
")",
"->",
"cirq",
".",
"Circuit",
":",
"grid",
"=",
"tkcirc",
".",
"_int_routing_grid",
"(",
")",
"qubits",
"=",
"_grid_to_qubits",
"(",
"grid",
... | Converts a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit` object to a Cirq :py:class:`Circuit`.
:param tkcirc: The input :math:`\\mathrm{t|ket}\\rangle` :py:class:`Circuit`
:param indexed_qubits: Map from :math:`\\mathrm{t|ket}\\rangle` qubit indices to Cirq :py:class:`QubitId` s
:return: The... | [
"Converts",
"a",
":",
"math",
":",
"\\\\",
"mathrm",
"{",
"t|ket",
"}",
"\\\\",
"rangle",
":",
"py",
":",
"class",
":",
"Circuit",
"object",
"to",
"a",
"Cirq",
":",
"py",
":",
"class",
":",
"Circuit",
".",
":",
"param",
"tkcirc",
":",
"The",
"input... | python | train |
hydpy-dev/hydpy | hydpy/auxs/xmltools.py | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/xmltools.py#L1695-L1733 | def get_subsequencesinsertion(cls, subsequences, indent) -> str:
"""Return the insertion string required for the given group of
sequences.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> from hydpy import prepare_model
>>> model = prepare_model('hland_v1')
>>> print(XS... | [
"def",
"get_subsequencesinsertion",
"(",
"cls",
",",
"subsequences",
",",
"indent",
")",
"->",
"str",
":",
"blanks",
"=",
"' '",
"*",
"(",
"indent",
"*",
"4",
")",
"lines",
"=",
"[",
"f'{blanks}<element name=\"{subsequences.name}\"'",
",",
"f'{blanks} minO... | Return the insertion string required for the given group of
sequences.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> from hydpy import prepare_model
>>> model = prepare_model('hland_v1')
>>> print(XSDWriter.get_subsequencesinsertion(
... model.sequences.fluxes, 1... | [
"Return",
"the",
"insertion",
"string",
"required",
"for",
"the",
"given",
"group",
"of",
"sequences",
"."
] | python | train |
tensorflow/mesh | examples/mnist.py | https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist.py#L207-L236 | def run_mnist():
"""Run MNIST training and eval loop."""
mnist_classifier = tf.estimator.Estimator(
model_fn=model_fn,
model_dir=FLAGS.model_dir)
# Set up training and evaluation input functions.
def train_input_fn():
"""Prepare data for training."""
# When choosing shuffle buffer sizes, l... | [
"def",
"run_mnist",
"(",
")",
":",
"mnist_classifier",
"=",
"tf",
".",
"estimator",
".",
"Estimator",
"(",
"model_fn",
"=",
"model_fn",
",",
"model_dir",
"=",
"FLAGS",
".",
"model_dir",
")",
"# Set up training and evaluation input functions.",
"def",
"train_input_fn... | Run MNIST training and eval loop. | [
"Run",
"MNIST",
"training",
"and",
"eval",
"loop",
"."
] | python | train |
Aperture-py/aperture-lib | aperturelib/watermark.py | https://github.com/Aperture-py/aperture-lib/blob/5c54af216319f297ddf96181a16f088cf1ba23f3/aperturelib/watermark.py#L59-L152 | def watermark_text(image, text, corner=2):
'''Adds a text watermark to an instance of a PIL Image.
The text will be sized so that the height of the text is
roughly 1/20th the height of the base image. The text will
be white with a thin black outline.
Args:
image: An instance of a PIL Imag... | [
"def",
"watermark_text",
"(",
"image",
",",
"text",
",",
"corner",
"=",
"2",
")",
":",
"# Load Font",
"FONT_PATH",
"=",
"''",
"if",
"resource_exists",
"(",
"__name__",
",",
"'resources/fonts/SourceSansPro-Regular.ttf'",
")",
":",
"FONT_PATH",
"=",
"resource_filena... | Adds a text watermark to an instance of a PIL Image.
The text will be sized so that the height of the text is
roughly 1/20th the height of the base image. The text will
be white with a thin black outline.
Args:
image: An instance of a PIL Image. This is the base image.
text: Text to u... | [
"Adds",
"a",
"text",
"watermark",
"to",
"an",
"instance",
"of",
"a",
"PIL",
"Image",
"."
] | python | train |
timmahrt/ProMo | promo/morph_utils/morph_sequence.py | https://github.com/timmahrt/ProMo/blob/99d9f5cc01ff328a62973c5a5da910cc905ae4d5/promo/morph_utils/morph_sequence.py#L79-L95 | def _makeTimingAbsolute(relativeDataList, startTime, endTime):
'''
Maps values from 0 to 1 to the provided start and end time
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...]
'''
timingSeq = [row[0] for row in relativeDataList]
valueSeq = [list(row[1:]) for row... | [
"def",
"_makeTimingAbsolute",
"(",
"relativeDataList",
",",
"startTime",
",",
"endTime",
")",
":",
"timingSeq",
"=",
"[",
"row",
"[",
"0",
"]",
"for",
"row",
"in",
"relativeDataList",
"]",
"valueSeq",
"=",
"[",
"list",
"(",
"row",
"[",
"1",
":",
"]",
"... | Maps values from 0 to 1 to the provided start and end time
Input is a list of tuples of the form
([(time1, pitch1), (time2, pitch2),...] | [
"Maps",
"values",
"from",
"0",
"to",
"1",
"to",
"the",
"provided",
"start",
"and",
"end",
"time"
] | python | train |
vertexproject/synapse | synapse/cortex.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/cortex.py#L1570-L1580 | async def eval(self, text, opts=None, user=None):
'''
Evaluate a storm query and yield Nodes only.
'''
if user is None:
user = self.auth.getUserByName('root')
await self.boss.promote('storm', user=user, info={'query': text})
async with await self.snap(user=us... | [
"async",
"def",
"eval",
"(",
"self",
",",
"text",
",",
"opts",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"self",
".",
"auth",
".",
"getUserByName",
"(",
"'root'",
")",
"await",
"self",
".",
"bo... | Evaluate a storm query and yield Nodes only. | [
"Evaluate",
"a",
"storm",
"query",
"and",
"yield",
"Nodes",
"only",
"."
] | python | train |
spencerahill/aospy | aospy/region.py | https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/region.py#L232-L264 | def mask_var(self, data, lon_cyclic=True, lon_str=LON_STR,
lat_str=LAT_STR):
"""Mask the given data outside this region.
Parameters
----------
data : xarray.DataArray
The array to be regionally masked.
lon_cyclic : bool, optional (default True)
... | [
"def",
"mask_var",
"(",
"self",
",",
"data",
",",
"lon_cyclic",
"=",
"True",
",",
"lon_str",
"=",
"LON_STR",
",",
"lat_str",
"=",
"LAT_STR",
")",
":",
"# TODO: is this still necessary?",
"if",
"not",
"lon_cyclic",
":",
"if",
"self",
".",
"west_bound",
">",
... | Mask the given data outside this region.
Parameters
----------
data : xarray.DataArray
The array to be regionally masked.
lon_cyclic : bool, optional (default True)
Whether or not the longitudes of ``data`` span the whole globe,
meaning that they shou... | [
"Mask",
"the",
"given",
"data",
"outside",
"this",
"region",
"."
] | python | train |
linode/linode_api4-python | linode_api4/objects/linode.py | https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L321-L328 | def invalidate(self):
""" Clear out cached properties """
if hasattr(self, '_avail_backups'):
del self._avail_backups
if hasattr(self, '_ips'):
del self._ips
Base.invalidate(self) | [
"def",
"invalidate",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_avail_backups'",
")",
":",
"del",
"self",
".",
"_avail_backups",
"if",
"hasattr",
"(",
"self",
",",
"'_ips'",
")",
":",
"del",
"self",
".",
"_ips",
"Base",
".",
"invalida... | Clear out cached properties | [
"Clear",
"out",
"cached",
"properties"
] | python | train |
astropy/astropy-helpers | astropy_helpers/version_helpers.py | https://github.com/astropy/astropy-helpers/blob/f5a27d3f84a98ea0eebb85e0cf3e7214c6bc0d09/astropy_helpers/version_helpers.py#L43-L85 | def _version_split(version):
"""
Split a version string into major, minor, and bugfix numbers. If any of
those numbers are missing the default is zero. Any pre/post release
modifiers are ignored.
Examples
========
>>> _version_split('1.2.3')
(1, 2, 3)
>>> _version_split('1.2')
... | [
"def",
"_version_split",
"(",
"version",
")",
":",
"parsed_version",
"=",
"pkg_resources",
".",
"parse_version",
"(",
"version",
")",
"if",
"hasattr",
"(",
"parsed_version",
",",
"'base_version'",
")",
":",
"# New version parsing for setuptools >= 8.0",
"if",
"parsed_... | Split a version string into major, minor, and bugfix numbers. If any of
those numbers are missing the default is zero. Any pre/post release
modifiers are ignored.
Examples
========
>>> _version_split('1.2.3')
(1, 2, 3)
>>> _version_split('1.2')
(1, 2, 0)
>>> _version_split('1.2rc1... | [
"Split",
"a",
"version",
"string",
"into",
"major",
"minor",
"and",
"bugfix",
"numbers",
".",
"If",
"any",
"of",
"those",
"numbers",
"are",
"missing",
"the",
"default",
"is",
"zero",
".",
"Any",
"pre",
"/",
"post",
"release",
"modifiers",
"are",
"ignored",... | python | train |
tensorflow/lucid | lucid/misc/io/serialize_array.py | https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/misc/io/serialize_array.py#L126-L161 | def array_to_jsbuffer(array):
"""Serialize 1d NumPy array to JS TypedArray.
Data is serialized to base64-encoded string, which is much faster
and memory-efficient than json list serialization.
Args:
array: 1d NumPy array, dtype must be one of JS_ARRAY_TYPES.
Returns:
JS code that evaluates to a Typ... | [
"def",
"array_to_jsbuffer",
"(",
"array",
")",
":",
"if",
"array",
".",
"ndim",
"!=",
"1",
":",
"raise",
"TypeError",
"(",
"'Only 1d arrays can be converted JS TypedArray.'",
")",
"if",
"array",
".",
"dtype",
".",
"name",
"not",
"in",
"JS_ARRAY_TYPES",
":",
"r... | Serialize 1d NumPy array to JS TypedArray.
Data is serialized to base64-encoded string, which is much faster
and memory-efficient than json list serialization.
Args:
array: 1d NumPy array, dtype must be one of JS_ARRAY_TYPES.
Returns:
JS code that evaluates to a TypedArray as string.
Raises:
T... | [
"Serialize",
"1d",
"NumPy",
"array",
"to",
"JS",
"TypedArray",
"."
] | python | train |
alefnula/tea | tea/console/format.py | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L97-L123 | def print_page(text):
"""Format the text and prints it on stdout.
Text is formatted by adding a ASCII frame around it and coloring the text.
Colors can be added to text using color tags, for example:
My [FG_BLUE]blue[NORMAL] text.
My [BG_BLUE]blue background[NORMAL] text.
"""
... | [
"def",
"print_page",
"(",
"text",
")",
":",
"color_re",
"=",
"re",
".",
"compile",
"(",
"r\"\\[(?P<color>[FB]G_[A-Z_]+|NORMAL)\\]\"",
")",
"width",
"=",
"max",
"(",
"[",
"len",
"(",
"strip_colors",
"(",
"x",
")",
")",
"for",
"x",
"in",
"text",
".",
"spli... | Format the text and prints it on stdout.
Text is formatted by adding a ASCII frame around it and coloring the text.
Colors can be added to text using color tags, for example:
My [FG_BLUE]blue[NORMAL] text.
My [BG_BLUE]blue background[NORMAL] text. | [
"Format",
"the",
"text",
"and",
"prints",
"it",
"on",
"stdout",
".",
"Text",
"is",
"formatted",
"by",
"adding",
"a",
"ASCII",
"frame",
"around",
"it",
"and",
"coloring",
"the",
"text",
".",
"Colors",
"can",
"be",
"added",
"to",
"text",
"using",
"color",
... | python | train |
Valuehorizon/valuehorizon-companies | companies/models.py | https://github.com/Valuehorizon/valuehorizon-companies/blob/5366e230da69ee30fcdc1bf4beddc99310f6b767/companies/models.py#L215-L231 | def get_all_related_companies(self, include_self=False):
"""
Return all parents and subsidiaries of the company
Include the company if include_self = True
"""
parents = self.get_all_parents()
subsidiaries = self.get_all_children()
related_companies = parents | sub... | [
"def",
"get_all_related_companies",
"(",
"self",
",",
"include_self",
"=",
"False",
")",
":",
"parents",
"=",
"self",
".",
"get_all_parents",
"(",
")",
"subsidiaries",
"=",
"self",
".",
"get_all_children",
"(",
")",
"related_companies",
"=",
"parents",
"|",
"s... | Return all parents and subsidiaries of the company
Include the company if include_self = True | [
"Return",
"all",
"parents",
"and",
"subsidiaries",
"of",
"the",
"company",
"Include",
"the",
"company",
"if",
"include_self",
"=",
"True"
] | python | train |
benfred/implicit | setup.py | https://github.com/benfred/implicit/blob/6b16c50d1d514a814f2e5b8cf2a829ff23dbba63/setup.py#L81-L98 | def extract_gcc_binaries():
"""Try to find GCC on OSX for OpenMP support."""
patterns = ['/opt/local/bin/g++-mp-[0-9].[0-9]',
'/opt/local/bin/g++-mp-[0-9]',
'/usr/local/bin/g++-[0-9].[0-9]',
'/usr/local/bin/g++-[0-9]']
if 'darwin' in platform.platform().lower(... | [
"def",
"extract_gcc_binaries",
"(",
")",
":",
"patterns",
"=",
"[",
"'/opt/local/bin/g++-mp-[0-9].[0-9]'",
",",
"'/opt/local/bin/g++-mp-[0-9]'",
",",
"'/usr/local/bin/g++-[0-9].[0-9]'",
",",
"'/usr/local/bin/g++-[0-9]'",
"]",
"if",
"'darwin'",
"in",
"platform",
".",
"platfo... | Try to find GCC on OSX for OpenMP support. | [
"Try",
"to",
"find",
"GCC",
"on",
"OSX",
"for",
"OpenMP",
"support",
"."
] | python | train |
ryanpetrello/cleaver | cleaver/reports/web/bottle.py | https://github.com/ryanpetrello/cleaver/blob/0ef266e1a0603c6d414df4b9926ce2a59844db35/cleaver/reports/web/bottle.py#L581-L618 | def mount(self, prefix, app, **options):
''' Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it ends in a slash,
that slash is m... | [
"def",
"mount",
"(",
"self",
",",
"prefix",
",",
"app",
",",
"*",
"*",
"options",
")",
":",
"if",
"isinstance",
"(",
"app",
",",
"basestring",
")",
":",
"prefix",
",",
"app",
"=",
"app",
",",
"prefix",
"depr",
"(",
"'Parameter order of Bottle.mount() cha... | Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it ends in a slash,
that slash is mandatory.
:param app: an instance of :cla... | [
"Mount",
"an",
"application",
"(",
":",
"class",
":",
"Bottle",
"or",
"plain",
"WSGI",
")",
"to",
"a",
"specific",
"URL",
"prefix",
".",
"Example",
"::"
] | python | train |
AndrewAnnex/SpiceyPy | spiceypy/spiceypy.py | https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L8077-L8102 | def lstlec(string, n, lenvals, array):
"""
Given a character string and an ordered array of character
strings, find the index of the largest array element less than
or equal to the given string.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstlec_c.html
:param string: Upper bound va... | [
"def",
"lstlec",
"(",
"string",
",",
"n",
",",
"lenvals",
",",
"array",
")",
":",
"string",
"=",
"stypes",
".",
"stringToCharP",
"(",
"string",
")",
"array",
"=",
"stypes",
".",
"listToCharArrayPtr",
"(",
"array",
",",
"xLen",
"=",
"lenvals",
",",
"yLe... | Given a character string and an ordered array of character
strings, find the index of the largest array element less than
or equal to the given string.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lstlec_c.html
:param string: Upper bound value to search against.
:type string: str
:p... | [
"Given",
"a",
"character",
"string",
"and",
"an",
"ordered",
"array",
"of",
"character",
"strings",
"find",
"the",
"index",
"of",
"the",
"largest",
"array",
"element",
"less",
"than",
"or",
"equal",
"to",
"the",
"given",
"string",
"."
] | python | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.