repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/utils/reactor.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/reactor.py#L250-L325 | def run(self):
'''
Enter into the server loop
'''
salt.utils.process.appendproctitle(self.__class__.__name__)
# instantiate some classes inside our new process
self.event = salt.utils.event.get_event(
self.opts['__role'],
self.opts['sock_d... | [
"def",
"run",
"(",
"self",
")",
":",
"salt",
".",
"utils",
".",
"process",
".",
"appendproctitle",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
"# instantiate some classes inside our new process",
"self",
".",
"event",
"=",
"salt",
".",
"utils",
".",
... | Enter into the server loop | [
"Enter",
"into",
"the",
"server",
"loop"
] | python | train | 50.828947 |
theno/fabsetup | fabsetup/fabutils.py | https://github.com/theno/fabsetup/blob/ced728abff93551ba5677e63bc1bdc0ef5ca5777/fabsetup/fabutils.py#L172-L188 | def needs_packages(*packages):
'''Decorator: ensure that packages are installed on host given by fabric
argument `-H` (local or remote).
'''
def real_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
non_installed = _non_installed(packages)
if non_insta... | [
"def",
"needs_packages",
"(",
"*",
"packages",
")",
":",
"def",
"real_decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"non_installed",
"=",
"_non_installed",
"(",... | Decorator: ensure that packages are installed on host given by fabric
argument `-H` (local or remote). | [
"Decorator",
":",
"ensure",
"that",
"packages",
"are",
"installed",
"on",
"host",
"given",
"by",
"fabric",
"argument",
"-",
"H",
"(",
"local",
"or",
"remote",
")",
"."
] | python | train | 30.764706 |
joeyespo/nosey | nosey/watcher.py | https://github.com/joeyespo/nosey/blob/8194c3e1b06d95ab623b561fd0f26b2d3017446c/nosey/watcher.py#L38-L59 | def watch(directory=None, auto_clear=False, extensions=[]):
"""Starts a server to render the specified file or directory containing a README."""
if directory and not os.path.isdir(directory):
raise ValueError('Directory not found: ' + directory)
directory = os.path.abspath(directory)
# Initial ... | [
"def",
"watch",
"(",
"directory",
"=",
"None",
",",
"auto_clear",
"=",
"False",
",",
"extensions",
"=",
"[",
"]",
")",
":",
"if",
"directory",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"directory",
")",
":",
"raise",
"ValueError",
"(",
"'Di... | Starts a server to render the specified file or directory containing a README. | [
"Starts",
"a",
"server",
"to",
"render",
"the",
"specified",
"file",
"or",
"directory",
"containing",
"a",
"README",
"."
] | python | train | 32.5 |
jazzband/django-ddp | dddp/main.py | https://github.com/jazzband/django-ddp/blob/1e1954b06fe140346acea43582515991685e4e01/dddp/main.py#L241-L274 | def addr(val, default_port=8000, defualt_host='localhost'):
"""
Convert a string of format host[:port] into Addr(host, port).
>>> addr('0:80')
Addr(host='0', port=80)
>>> addr('127.0.0.1:80')
Addr(host='127.0.0.1', port=80)
>>> addr('0.0.0.0', default_port=8000)
Addr(host='0.0.0.0', p... | [
"def",
"addr",
"(",
"val",
",",
"default_port",
"=",
"8000",
",",
"defualt_host",
"=",
"'localhost'",
")",
":",
"import",
"re",
"import",
"socket",
"match",
"=",
"re",
".",
"match",
"(",
"r'\\A(?P<host>.*?)(:(?P<port>(\\d+|\\w+)))?\\Z'",
",",
"val",
")",
"if",... | Convert a string of format host[:port] into Addr(host, port).
>>> addr('0:80')
Addr(host='0', port=80)
>>> addr('127.0.0.1:80')
Addr(host='127.0.0.1', port=80)
>>> addr('0.0.0.0', default_port=8000)
Addr(host='0.0.0.0', port=8000) | [
"Convert",
"a",
"string",
"of",
"format",
"host",
"[",
":",
"port",
"]",
"into",
"Addr",
"(",
"host",
"port",
")",
"."
] | python | test | 23.794118 |
saltstack/salt | salt/modules/debuild_pkgbuild.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/debuild_pkgbuild.py#L234-L283 | def _create_pbuilders(env, runas='root'):
'''
Create the .pbuilder family of files in user's home directory
env
A list or dictionary of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
- env:
- DEB_BUILD_OPTIONS: 'noche... | [
"def",
"_create_pbuilders",
"(",
"env",
",",
"runas",
"=",
"'root'",
")",
":",
"home",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~{0}'",
".",
"format",
"(",
"runas",
")",
")",
"pbuilderrc",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
... | Create the .pbuilder family of files in user's home directory
env
A list or dictionary of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
- env:
- DEB_BUILD_OPTIONS: 'nocheck'
.. warning::
The above illus... | [
"Create",
"the",
".",
"pbuilder",
"family",
"of",
"files",
"in",
"user",
"s",
"home",
"directory"
] | python | train | 34.7 |
totalgood/nlpia | src/nlpia/talk.py | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/talk.py#L67-L80 | def transcribe(decoder, audio_file, libdir=None):
""" Decode streaming audio data from raw binary file on disk. """
decoder = get_decoder()
decoder.start_utt()
stream = open(audio_file, 'rb')
while True:
buf = stream.read(1024)
if buf:
decoder.process_raw(buf, False, Fal... | [
"def",
"transcribe",
"(",
"decoder",
",",
"audio_file",
",",
"libdir",
"=",
"None",
")",
":",
"decoder",
"=",
"get_decoder",
"(",
")",
"decoder",
".",
"start_utt",
"(",
")",
"stream",
"=",
"open",
"(",
"audio_file",
",",
"'rb'",
")",
"while",
"True",
"... | Decode streaming audio data from raw binary file on disk. | [
"Decode",
"streaming",
"audio",
"data",
"from",
"raw",
"binary",
"file",
"on",
"disk",
"."
] | python | train | 28.642857 |
saltstack/salt | salt/modules/panos.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/panos.py#L865-L888 | def get_local_admins():
'''
Show all local administrator accounts.
CLI Example:
.. code-block:: bash
salt '*' panos.get_local_admins
'''
admin_list = get_users_config()
response = []
if 'users' not in admin_list['result']:
return response
if isinstance(admin_lis... | [
"def",
"get_local_admins",
"(",
")",
":",
"admin_list",
"=",
"get_users_config",
"(",
")",
"response",
"=",
"[",
"]",
"if",
"'users'",
"not",
"in",
"admin_list",
"[",
"'result'",
"]",
":",
"return",
"response",
"if",
"isinstance",
"(",
"admin_list",
"[",
"... | Show all local administrator accounts.
CLI Example:
.. code-block:: bash
salt '*' panos.get_local_admins | [
"Show",
"all",
"local",
"administrator",
"accounts",
"."
] | python | train | 22.541667 |
cloudendpoints/endpoints-management-python | endpoints_management/control/distribution.py | https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/distribution.py#L121-L145 | def add_sample(a_float, dist):
"""Adds `a_float` to `dist`, updating its existing buckets.
Args:
a_float (float): a new value
dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
the Distribution being updated
Raises:
ValueError: if `dist` does not ha... | [
"def",
"add_sample",
"(",
"a_float",
",",
"dist",
")",
":",
"dist_type",
",",
"_",
"=",
"_detect_bucket_option",
"(",
"dist",
")",
"if",
"dist_type",
"==",
"u'exponentialBuckets'",
":",
"_update_general_statistics",
"(",
"a_float",
",",
"dist",
")",
"_update_exp... | Adds `a_float` to `dist`, updating its existing buckets.
Args:
a_float (float): a new value
dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
the Distribution being updated
Raises:
ValueError: if `dist` does not have known bucket options defined
... | [
"Adds",
"a_float",
"to",
"dist",
"updating",
"its",
"existing",
"buckets",
"."
] | python | train | 41.32 |
python-odin/odinweb | odinweb/data_structures.py | https://github.com/python-odin/odinweb/blob/198424133584acc18cb41c8d18d91f803abc810f/odinweb/data_structures.py#L744-L758 | def get(self, key, default=None, type_=None):
"""
Return the last data value for the passed key. If key doesn't exist
or value is an empty list, return `default`.
"""
try:
rv = self[key]
except KeyError:
return default
if type_ is not None:... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"type_",
"=",
"None",
")",
":",
"try",
":",
"rv",
"=",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"return",
"default",
"if",
"type_",
"is",
"not",
"None",
":",
"try... | Return the last data value for the passed key. If key doesn't exist
or value is an empty list, return `default`. | [
"Return",
"the",
"last",
"data",
"value",
"for",
"the",
"passed",
"key",
".",
"If",
"key",
"doesn",
"t",
"exist",
"or",
"value",
"is",
"an",
"empty",
"list",
"return",
"default",
"."
] | python | train | 28.8 |
Scoppio/RagnarokEngine3 | RagnarokEngine3/RE3.py | https://github.com/Scoppio/RagnarokEngine3/blob/4395d419ccd64fe9327c41f200b72ee0176ad896/RagnarokEngine3/RE3.py#L3021-L3034 | def check_bounds(self):
"""Make sure the camera is not outside if its legal range."""
if not (self.camera_bounds == None):
if self.__pan.X < self.camera_bounds.Left:
self.__pan[0] = self.camera_bounds.Left
if self.__pan.X > self.camera_bounds.Right:
... | [
"def",
"check_bounds",
"(",
"self",
")",
":",
"if",
"not",
"(",
"self",
".",
"camera_bounds",
"==",
"None",
")",
":",
"if",
"self",
".",
"__pan",
".",
"X",
"<",
"self",
".",
"camera_bounds",
".",
"Left",
":",
"self",
".",
"__pan",
"[",
"0",
"]",
... | Make sure the camera is not outside if its legal range. | [
"Make",
"sure",
"the",
"camera",
"is",
"not",
"outside",
"if",
"its",
"legal",
"range",
"."
] | python | train | 41.142857 |
StanfordVL/robosuite | robosuite/models/arenas/table_arena.py | https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/models/arenas/table_arena.py#L47-L50 | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | [
"def",
"table_top_abs",
"(",
"self",
")",
":",
"table_height",
"=",
"np",
".",
"array",
"(",
"[",
"0",
",",
"0",
",",
"self",
".",
"table_full_size",
"[",
"2",
"]",
"]",
")",
"return",
"string_to_array",
"(",
"self",
".",
"floor",
".",
"get",
"(",
... | Returns the absolute position of table top | [
"Returns",
"the",
"absolute",
"position",
"of",
"table",
"top"
] | python | train | 53 |
allenai/allennlp | allennlp/state_machines/transition_functions/transition_function.py | https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/transition_function.py#L23-L82 | def take_step(self,
state: StateType,
max_actions: int = None,
allowed_actions: List[Set] = None) -> List[StateType]:
"""
The main method in the ``TransitionFunction`` API. This function defines the computation
done at each step of decoding ... | [
"def",
"take_step",
"(",
"self",
",",
"state",
":",
"StateType",
",",
"max_actions",
":",
"int",
"=",
"None",
",",
"allowed_actions",
":",
"List",
"[",
"Set",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"StateType",
"]",
":",
"raise",
"NotImplementedError"... | The main method in the ``TransitionFunction`` API. This function defines the computation
done at each step of decoding and returns a ranked list of next states.
The input state is `grouped`, to allow for efficient computation, but the output states
should all have a ``group_size`` of 1, to mak... | [
"The",
"main",
"method",
"in",
"the",
"TransitionFunction",
"API",
".",
"This",
"function",
"defines",
"the",
"computation",
"done",
"at",
"each",
"step",
"of",
"decoding",
"and",
"returns",
"a",
"ranked",
"list",
"of",
"next",
"states",
"."
] | python | train | 60.7 |
aganezov/bg | bg/breakpoint_graph.py | https://github.com/aganezov/bg/blob/1ec758193441e49e7b34e0da09571480f4c24455/bg/breakpoint_graph.py#L505-L526 | def split_edge(self, vertex1, vertex2, multicolor, guidance=None, sorted_guidance=False,
account_for_colors_multiplicity_in_guidance=True, key=None):
""" Splits an edge in current :class:`BreakpointGraph` most similar to supplied data (if no unique identifier ``key`` is provided) with respect... | [
"def",
"split_edge",
"(",
"self",
",",
"vertex1",
",",
"vertex2",
",",
"multicolor",
",",
"guidance",
"=",
"None",
",",
"sorted_guidance",
"=",
"False",
",",
"account_for_colors_multiplicity_in_guidance",
"=",
"True",
",",
"key",
"=",
"None",
")",
":",
"self",... | Splits an edge in current :class:`BreakpointGraph` most similar to supplied data (if no unique identifier ``key`` is provided) with respect to supplied guidance.
Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__split_bgedge` method.
:param vertex1: a first vertex out of two the edge to be sp... | [
"Splits",
"an",
"edge",
"in",
"current",
":",
"class",
":",
"BreakpointGraph",
"most",
"similar",
"to",
"supplied",
"data",
"(",
"if",
"no",
"unique",
"identifier",
"key",
"is",
"provided",
")",
"with",
"respect",
"to",
"supplied",
"guidance",
"."
] | python | train | 74.590909 |
AguaClara/aguaclara | aguaclara/unit_process_design/ent_tank.py | https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/ent_tank.py#L9-L42 | def drain_OD(q_plant, T, depth_end, SDR):
"""Return the nominal diameter of the entrance tank drain pipe. Depth at the
end of the flocculator is used for headloss and length calculation inputs in
the diam_pipe calculation.
Parameters
----------
q_plant: float
Plant flow rate
T: flo... | [
"def",
"drain_OD",
"(",
"q_plant",
",",
"T",
",",
"depth_end",
",",
"SDR",
")",
":",
"nu",
"=",
"pc",
".",
"viscosity_kinematic",
"(",
"T",
")",
"K_minor",
"=",
"con",
".",
"PIPE_ENTRANCE_K_MINOR",
"+",
"con",
".",
"PIPE_EXIT_K_MINOR",
"+",
"con",
".",
... | Return the nominal diameter of the entrance tank drain pipe. Depth at the
end of the flocculator is used for headloss and length calculation inputs in
the diam_pipe calculation.
Parameters
----------
q_plant: float
Plant flow rate
T: float
Design temperature
depth_end: flo... | [
"Return",
"the",
"nominal",
"diameter",
"of",
"the",
"entrance",
"tank",
"drain",
"pipe",
".",
"Depth",
"at",
"the",
"end",
"of",
"the",
"flocculator",
"is",
"used",
"for",
"headloss",
"and",
"length",
"calculation",
"inputs",
"in",
"the",
"diam_pipe",
"calc... | python | train | 25.529412 |
bcbio/bcbio-nextgen | bcbio/cwl/workflow.py | https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/workflow.py#L251-L263 | def _nest_variable(v, check_records=False):
"""Nest a variable when moving from scattered back to consolidated.
check_records -- avoid re-nesting a record input if it comes from a previous
step and is already nested, don't need to re-array.
"""
if (check_records and is_cwl_record(v) and len(v["id"]... | [
"def",
"_nest_variable",
"(",
"v",
",",
"check_records",
"=",
"False",
")",
":",
"if",
"(",
"check_records",
"and",
"is_cwl_record",
"(",
"v",
")",
"and",
"len",
"(",
"v",
"[",
"\"id\"",
"]",
".",
"split",
"(",
"\"/\"",
")",
")",
">",
"1",
"and",
"... | Nest a variable when moving from scattered back to consolidated.
check_records -- avoid re-nesting a record input if it comes from a previous
step and is already nested, don't need to re-array. | [
"Nest",
"a",
"variable",
"when",
"moving",
"from",
"scattered",
"back",
"to",
"consolidated",
"."
] | python | train | 39.307692 |
xsleonard/pystmark | pystmark.py | https://github.com/xsleonard/pystmark/blob/329ccae1a7c8d57f28fa72cd8dbbee3e39413ed6/pystmark.py#L1164-L1200 | def get(self, bounce_type=None, inactive=None, email_filter=None,
message_id=None, count=None, offset=None, api_key=None,
secure=None, test=None, **request_args):
'''Builds query string params from inputs. It handles offset and
count defaults and validation.
:param bounc... | [
"def",
"get",
"(",
"self",
",",
"bounce_type",
"=",
"None",
",",
"inactive",
"=",
"None",
",",
"email_filter",
"=",
"None",
",",
"message_id",
"=",
"None",
",",
"count",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"secu... | Builds query string params from inputs. It handles offset and
count defaults and validation.
:param bounce_type: The type of bounces retrieve. See `bounce_types`
for a list of types, or read the Postmark API docs. Defaults to
`None`.
:param inactive: If `True`, retrieves... | [
"Builds",
"query",
"string",
"params",
"from",
"inputs",
".",
"It",
"handles",
"offset",
"and",
"count",
"defaults",
"and",
"validation",
"."
] | python | train | 53.243243 |
CitrineInformatics/dftparse | dftparse/pwscf/stdout_parser.py | https://github.com/CitrineInformatics/dftparse/blob/53a1bf19945cf1c195d6af9beccb3d1b7f4a4c1d/dftparse/pwscf/stdout_parser.py#L92-L145 | def _parse_forces(line, lines):
"""Parse the forces block, including individual terms (e.g. Hubbard)"""
units = line.split()[4].rstrip(":")
next(lines)
newline = next(lines)
total = []; non_local = []; ionic = []; local = []; core_correction = []
hubbard = []; scf = []; types = []
while (not... | [
"def",
"_parse_forces",
"(",
"line",
",",
"lines",
")",
":",
"units",
"=",
"line",
".",
"split",
"(",
")",
"[",
"4",
"]",
".",
"rstrip",
"(",
"\":\"",
")",
"next",
"(",
"lines",
")",
"newline",
"=",
"next",
"(",
"lines",
")",
"total",
"=",
"[",
... | Parse the forces block, including individual terms (e.g. Hubbard) | [
"Parse",
"the",
"forces",
"block",
"including",
"individual",
"terms",
"(",
"e",
".",
"g",
".",
"Hubbard",
")"
] | python | train | 44.481481 |
xmikos/soapy_power | soapypower/power.py | https://github.com/xmikos/soapy_power/blob/46e12659b8d08af764dc09a1f31b0e85a68f808f/soapypower/power.py#L59-L71 | def nearest_bins(self, bins, even=False, pow2=False):
"""Return nearest number of FFT bins (even or power of two)"""
if pow2:
bins_log2 = math.log(bins, 2)
if bins_log2 % 1 != 0:
bins = 2**math.ceil(bins_log2)
logger.warning('number of FFT bins sho... | [
"def",
"nearest_bins",
"(",
"self",
",",
"bins",
",",
"even",
"=",
"False",
",",
"pow2",
"=",
"False",
")",
":",
"if",
"pow2",
":",
"bins_log2",
"=",
"math",
".",
"log",
"(",
"bins",
",",
"2",
")",
"if",
"bins_log2",
"%",
"1",
"!=",
"0",
":",
"... | Return nearest number of FFT bins (even or power of two) | [
"Return",
"nearest",
"number",
"of",
"FFT",
"bins",
"(",
"even",
"or",
"power",
"of",
"two",
")"
] | python | test | 44 |
datasift/datasift-python | datasift/historics.py | https://github.com/datasift/datasift-python/blob/bfaca1a47501a18e11065ecf630d9c31df818f65/datasift/historics.py#L84-L102 | def status(self, start, end, sources=None):
""" Check the data coverage in the Historics archive for a given interval.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstatus
:param start: Unix timestamp for the start time
:type start: int... | [
"def",
"status",
"(",
"self",
",",
"start",
",",
"end",
",",
"sources",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'start'",
":",
"start",
",",
"'end'",
":",
"end",
"}",
"if",
"sources",
":",
"params",
"[",
"'sources'",
"]",
"=",
"','",
".",
"jo... | Check the data coverage in the Historics archive for a given interval.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsstatus
:param start: Unix timestamp for the start time
:type start: int
:param end: Unix timestamp for the start ti... | [
"Check",
"the",
"data",
"coverage",
"in",
"the",
"Historics",
"archive",
"for",
"a",
"given",
"interval",
"."
] | python | train | 47.578947 |
allianceauth/allianceauth | allianceauth/eveonline/autogroups/models.py | https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/eveonline/autogroups/models.py#L32-L47 | def update_groups_for_user(self, user: User, state: State = None):
"""
Update the Group memberships for the given users state
:param user: User to update for
:param state: State to update user for
:return:
"""
if state is None:
state = user.profile.sta... | [
"def",
"update_groups_for_user",
"(",
"self",
",",
"user",
":",
"User",
",",
"state",
":",
"State",
"=",
"None",
")",
":",
"if",
"state",
"is",
"None",
":",
"state",
"=",
"user",
".",
"profile",
".",
"state",
"for",
"config",
"in",
"self",
".",
"filt... | Update the Group memberships for the given users state
:param user: User to update for
:param state: State to update user for
:return: | [
"Update",
"the",
"Group",
"memberships",
"for",
"the",
"given",
"users",
"state",
":",
"param",
"user",
":",
"User",
"to",
"update",
"for",
":",
"param",
"state",
":",
"State",
"to",
"update",
"user",
"for",
":",
"return",
":"
] | python | train | 43.4375 |
klen/makesite | makesite/main.py | https://github.com/klen/makesite/blob/f6f77a43a04a256189e8fffbeac1ffd63f35a10c/makesite/main.py#L316-L334 | def console():
" Enter point "
autocomplete()
config = settings.MakesiteParser()
config.read([
settings.BASECONFIG, settings.HOMECONFIG,
op.join(settings.MAKESITE_HOME or '', settings.CFGNAME),
op.join(op.curdir, settings.CFGNAME),
])
argv = []
alias = dict(config.ite... | [
"def",
"console",
"(",
")",
":",
"autocomplete",
"(",
")",
"config",
"=",
"settings",
".",
"MakesiteParser",
"(",
")",
"config",
".",
"read",
"(",
"[",
"settings",
".",
"BASECONFIG",
",",
"settings",
".",
"HOMECONFIG",
",",
"op",
".",
"join",
"(",
"set... | Enter point | [
"Enter",
"point"
] | python | train | 26 |
PmagPy/PmagPy | SPD/lib/lib_arai_plot_statistics.py | https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L88-L130 | def get_SCAT_box(slope, x_mean, y_mean, beta_threshold = .1):
"""
takes in data and returns information about SCAT box:
the largest possible x_value, the largest possible y_value,
and functions for the two bounding lines of the box
"""
# if beta_threshold is -999, that means null
if beta_thr... | [
"def",
"get_SCAT_box",
"(",
"slope",
",",
"x_mean",
",",
"y_mean",
",",
"beta_threshold",
"=",
".1",
")",
":",
"# if beta_threshold is -999, that means null",
"if",
"beta_threshold",
"==",
"-",
"999",
":",
"beta_threshold",
"=",
".1",
"slope_err_threshold",
"=",
"... | takes in data and returns information about SCAT box:
the largest possible x_value, the largest possible y_value,
and functions for the two bounding lines of the box | [
"takes",
"in",
"data",
"and",
"returns",
"information",
"about",
"SCAT",
"box",
":",
"the",
"largest",
"possible",
"x_value",
"the",
"largest",
"possible",
"y_value",
"and",
"functions",
"for",
"the",
"two",
"bounding",
"lines",
"of",
"the",
"box"
] | python | train | 45.488372 |
trailofbits/manticore | manticore/native/cpu/x86.py | https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L5353-L5357 | def CDQ(cpu):
"""
EDX:EAX = sign-extend of EAX
"""
cpu.EDX = Operators.EXTRACT(Operators.SEXTEND(cpu.EAX, 32, 64), 32, 32) | [
"def",
"CDQ",
"(",
"cpu",
")",
":",
"cpu",
".",
"EDX",
"=",
"Operators",
".",
"EXTRACT",
"(",
"Operators",
".",
"SEXTEND",
"(",
"cpu",
".",
"EAX",
",",
"32",
",",
"64",
")",
",",
"32",
",",
"32",
")"
] | EDX:EAX = sign-extend of EAX | [
"EDX",
":",
"EAX",
"=",
"sign",
"-",
"extend",
"of",
"EAX"
] | python | valid | 30 |
nlsdfnbch/Pysher | pysher/connection.py | https://github.com/nlsdfnbch/Pysher/blob/8bec81616be2b6c9a9c0e2774b42890426a73745/pysher/connection.py#L73-L81 | def bind(self, event_name, callback, *args, **kwargs):
"""Bind an event to a callback
:param event_name: The name of the event to bind to.
:type event_name: str
:param callback: The callback to notify of this event.
"""
self.event_callbacks[event_name].append((callback,... | [
"def",
"bind",
"(",
"self",
",",
"event_name",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"event_callbacks",
"[",
"event_name",
"]",
".",
"append",
"(",
"(",
"callback",
",",
"args",
",",
"kwargs",
")",
")"
] | Bind an event to a callback
:param event_name: The name of the event to bind to.
:type event_name: str
:param callback: The callback to notify of this event. | [
"Bind",
"an",
"event",
"to",
"a",
"callback"
] | python | train | 36.333333 |
CamDavidsonPilon/lifetimes | lifetimes/plotting.py | https://github.com/CamDavidsonPilon/lifetimes/blob/f926308bc03c17c1d12fead729de43885cf13321/lifetimes/plotting.py#L329-L389 | def plot_history_alive(model, t, transactions, datetime_col, freq="D", start_date=None, ax=None, **kwargs):
"""
Draw a graph showing the probability of being alive for a customer in time.
Parameters
----------
model: lifetimes model
A fitted lifetimes model.
t: int
the number of... | [
"def",
"plot_history_alive",
"(",
"model",
",",
"t",
",",
"transactions",
",",
"datetime_col",
",",
"freq",
"=",
"\"D\"",
",",
"start_date",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"matplotlib",
"import",
"pyplot",... | Draw a graph showing the probability of being alive for a customer in time.
Parameters
----------
model: lifetimes model
A fitted lifetimes model.
t: int
the number of time units since the birth we want to draw the p_alive
transactions: pandas DataFrame
DataFrame containing ... | [
"Draw",
"a",
"graph",
"showing",
"the",
"probability",
"of",
"being",
"alive",
"for",
"a",
"customer",
"in",
"time",
"."
] | python | train | 33.278689 |
perrygeo/python-rasterstats | src/rasterstats/cli.py | https://github.com/perrygeo/python-rasterstats/blob/910455cd7c9c21eadf464927db72b38ef62b7dfb/src/rasterstats/cli.py#L29-L74 | def zonalstats(features, raster, all_touched, band, categorical,
indent, info, nodata, prefix, stats, sequence, use_rs):
'''zonalstats generates summary statistics of geospatial raster datasets
based on vector features.
The input arguments to zonalstats should be valid GeoJSON Features. (see... | [
"def",
"zonalstats",
"(",
"features",
",",
"raster",
",",
"all_touched",
",",
"band",
",",
"categorical",
",",
"indent",
",",
"info",
",",
"nodata",
",",
"prefix",
",",
"stats",
",",
"sequence",
",",
"use_rs",
")",
":",
"if",
"info",
":",
"logging",
".... | zonalstats generates summary statistics of geospatial raster datasets
based on vector features.
The input arguments to zonalstats should be valid GeoJSON Features. (see cligj)
The output GeoJSON will be mostly unchanged but have additional properties per feature
describing the summary statistics (min,... | [
"zonalstats",
"generates",
"summary",
"statistics",
"of",
"geospatial",
"raster",
"datasets",
"based",
"on",
"vector",
"features",
"."
] | python | train | 31.695652 |
bitesofcode/projexui | projexui/widgets/xpopupwidget.py | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xpopupwidget.py#L1031-L1041 | def setCurrentMode( self, mode ):
"""
Sets the current mode for this dialog to the inputed mode.
:param mode | <XPopupWidget.Mode>
"""
if ( self._currentMode == mode ):
return
self._currentMode = mode
self.updateModeSet... | [
"def",
"setCurrentMode",
"(",
"self",
",",
"mode",
")",
":",
"if",
"(",
"self",
".",
"_currentMode",
"==",
"mode",
")",
":",
"return",
"self",
".",
"_currentMode",
"=",
"mode",
"self",
".",
"updateModeSettings",
"(",
")"
] | Sets the current mode for this dialog to the inputed mode.
:param mode | <XPopupWidget.Mode> | [
"Sets",
"the",
"current",
"mode",
"for",
"this",
"dialog",
"to",
"the",
"inputed",
"mode",
".",
":",
"param",
"mode",
"|",
"<XPopupWidget",
".",
"Mode",
">"
] | python | train | 28.818182 |
gccxml/pygccxml | pygccxml/declarations/type_traits.py | https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/type_traits.py#L433-L452 | def remove_volatile(type_):
"""removes volatile from the type definition
If type is not volatile type, it will be returned as is
"""
nake_type = remove_alias(type_)
if not is_volatile(nake_type):
return type_
else:
if isinstance(nake_type, cpptypes.array_t):
is_c = i... | [
"def",
"remove_volatile",
"(",
"type_",
")",
":",
"nake_type",
"=",
"remove_alias",
"(",
"type_",
")",
"if",
"not",
"is_volatile",
"(",
"nake_type",
")",
":",
"return",
"type_",
"else",
":",
"if",
"isinstance",
"(",
"nake_type",
",",
"cpptypes",
".",
"arra... | removes volatile from the type definition
If type is not volatile type, it will be returned as is | [
"removes",
"volatile",
"from",
"the",
"type",
"definition"
] | python | train | 33.7 |
mitsei/dlkit | dlkit/json_/assessment/managers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/managers.py#L1186-L1205 | def get_assessment_notification_session(self, assessment_receiver):
"""Gets the notification session for notifications pertaining to assessment changes.
arg: assessment_receiver
(osid.assessment.AssessmentReceiver): the assessment
receiver interface
return: (o... | [
"def",
"get_assessment_notification_session",
"(",
"self",
",",
"assessment_receiver",
")",
":",
"if",
"not",
"self",
".",
"supports_assessment_notification",
"(",
")",
":",
"raise",
"errors",
".",
"Unimplemented",
"(",
")",
"# pylint: disable=no-member",
"return",
"s... | Gets the notification session for notifications pertaining to assessment changes.
arg: assessment_receiver
(osid.assessment.AssessmentReceiver): the assessment
receiver interface
return: (osid.assessment.AssessmentNotificationSession) - an
``Assessment... | [
"Gets",
"the",
"notification",
"session",
"for",
"notifications",
"pertaining",
"to",
"assessment",
"changes",
"."
] | python | train | 50.25 |
openstack/quark | quark/api/extensions/routes.py | https://github.com/openstack/quark/blob/1112e6a66917d3e98e44cb7b33b107fd5a74bb2e/quark/api/extensions/routes.py#L100-L105 | def get_resources(cls):
"""Returns Ext Resources."""
controller = RoutesController(directory.get_plugin())
return [extensions.ResourceExtension(
Routes.get_alias(),
controller)] | [
"def",
"get_resources",
"(",
"cls",
")",
":",
"controller",
"=",
"RoutesController",
"(",
"directory",
".",
"get_plugin",
"(",
")",
")",
"return",
"[",
"extensions",
".",
"ResourceExtension",
"(",
"Routes",
".",
"get_alias",
"(",
")",
",",
"controller",
")",... | Returns Ext Resources. | [
"Returns",
"Ext",
"Resources",
"."
] | python | valid | 36.666667 |
belbio/bel | bel/nanopub/nanopubstore.py | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubstore.py#L23-L50 | def update_nanopubstore_start_dt(url: str, start_dt: str):
"""Add nanopubstore start_dt to belapi.state_mgmt collection
Args:
url: url of nanopubstore
start_dt: datetime of last query against nanopubstore for new ID's
"""
hostname = urllib.parse.urlsplit(url)[1]
start_dates_doc = ... | [
"def",
"update_nanopubstore_start_dt",
"(",
"url",
":",
"str",
",",
"start_dt",
":",
"str",
")",
":",
"hostname",
"=",
"urllib",
".",
"parse",
".",
"urlsplit",
"(",
"url",
")",
"[",
"1",
"]",
"start_dates_doc",
"=",
"state_mgmt",
".",
"get",
"(",
"start_... | Add nanopubstore start_dt to belapi.state_mgmt collection
Args:
url: url of nanopubstore
start_dt: datetime of last query against nanopubstore for new ID's | [
"Add",
"nanopubstore",
"start_dt",
"to",
"belapi",
".",
"state_mgmt",
"collection"
] | python | train | 35.071429 |
luismsgomes/stringology | src/stringology/lcs.py | https://github.com/luismsgomes/stringology/blob/c627dc5a0d4c6af10946040a6463d5495d39d960/src/stringology/lcs.py#L3-L24 | def llcs(s1, s2):
'''length of the longest common sequence
This implementation takes O(len(s1) * len(s2)) time and
O(min(len(s1), len(s2))) space.
Use only with short strings.
>>> llcs('a.b.cd','!a!b!c!!!d!')
4
'''
m, n = len(s1), len(s2)
if m < n: # ensure n <= m, to use O(min(n... | [
"def",
"llcs",
"(",
"s1",
",",
"s2",
")",
":",
"m",
",",
"n",
"=",
"len",
"(",
"s1",
")",
",",
"len",
"(",
"s2",
")",
"if",
"m",
"<",
"n",
":",
"# ensure n <= m, to use O(min(n,m)) space",
"m",
",",
"n",
"=",
"n",
",",
"m",
"s1",
",",
"s2",
"... | length of the longest common sequence
This implementation takes O(len(s1) * len(s2)) time and
O(min(len(s1), len(s2))) space.
Use only with short strings.
>>> llcs('a.b.cd','!a!b!c!!!d!')
4 | [
"length",
"of",
"the",
"longest",
"common",
"sequence"
] | python | train | 25.045455 |
pallets/werkzeug | src/werkzeug/debug/__init__.py | https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/debug/__init__.py#L333-L335 | def execute_command(self, request, command, frame):
"""Execute a command in a console."""
return Response(frame.console.eval(command), mimetype="text/html") | [
"def",
"execute_command",
"(",
"self",
",",
"request",
",",
"command",
",",
"frame",
")",
":",
"return",
"Response",
"(",
"frame",
".",
"console",
".",
"eval",
"(",
"command",
")",
",",
"mimetype",
"=",
"\"text/html\"",
")"
] | Execute a command in a console. | [
"Execute",
"a",
"command",
"in",
"a",
"console",
"."
] | python | train | 56.666667 |
nesaro/pydsl | pydsl/tree.py | https://github.com/nesaro/pydsl/blob/00b4fffd72036b80335e1a44a888fac57917ab41/pydsl/tree.py#L95-L112 | def valid_sequences(self):
"""Returns list"""
valid_sets = [[x] for x in self.possible_items if x['left'] == 0]
change = True
niter = 200
while change and niter > 0:
change = False
niter -=1
for possible in sorted(self.possible_items, key=lambd... | [
"def",
"valid_sequences",
"(",
"self",
")",
":",
"valid_sets",
"=",
"[",
"[",
"x",
"]",
"for",
"x",
"in",
"self",
".",
"possible_items",
"if",
"x",
"[",
"'left'",
"]",
"==",
"0",
"]",
"change",
"=",
"True",
"niter",
"=",
"200",
"while",
"change",
"... | Returns list | [
"Returns",
"list"
] | python | train | 49.722222 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/ostool.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/ostool.py#L132-L153 | def get_maya_location(self, ):
""" Return the installation path to maya
:returns: path to maya
:rtype: str
:raises: errors.SoftwareNotFoundError
"""
import _winreg
# query winreg entry
# the last flag is needed, if we want to test with 32 bit python!
... | [
"def",
"get_maya_location",
"(",
"self",
",",
")",
":",
"import",
"_winreg",
"# query winreg entry",
"# the last flag is needed, if we want to test with 32 bit python!",
"# Because Maya is an 64 bit key!",
"for",
"ver",
"in",
"MAYA_VERSIONS",
":",
"try",
":",
"key",
"=",
"_... | Return the installation path to maya
:returns: path to maya
:rtype: str
:raises: errors.SoftwareNotFoundError | [
"Return",
"the",
"installation",
"path",
"to",
"maya"
] | python | train | 43.454545 |
noahbenson/neuropythy | neuropythy/graphics/core.py | https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/graphics/core.py#L259-L276 | def color_overlap(color1, *args):
'''
color_overlap(color1, color2...) yields the rgba value associated with overlaying color2 on top
of color1 followed by any additional colors (overlaid left to right). This respects alpha
values when calculating the results.
Note that colors may be lists of co... | [
"def",
"color_overlap",
"(",
"color1",
",",
"*",
"args",
")",
":",
"args",
"=",
"list",
"(",
"args",
")",
"args",
".",
"insert",
"(",
"0",
",",
"color1",
")",
"rgba",
"=",
"np",
".",
"asarray",
"(",
"[",
"0.5",
",",
"0.5",
",",
"0.5",
",",
"0",... | color_overlap(color1, color2...) yields the rgba value associated with overlaying color2 on top
of color1 followed by any additional colors (overlaid left to right). This respects alpha
values when calculating the results.
Note that colors may be lists of colors, in which case a matrix of RGBA values is... | [
"color_overlap",
"(",
"color1",
"color2",
"...",
")",
"yields",
"the",
"rgba",
"value",
"associated",
"with",
"overlaying",
"color2",
"on",
"top",
"of",
"color1",
"followed",
"by",
"any",
"additional",
"colors",
"(",
"overlaid",
"left",
"to",
"right",
")",
"... | python | train | 41.666667 |
inasafe/inasafe | safe/common/utilities.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/common/utilities.py#L91-L103 | def safe_dir(sub_dir=None):
"""Absolute path from safe package directory.
:param sub_dir: Sub directory relative to safe package directory.
:type sub_dir: str
:return: The Absolute path.
:rtype: str
"""
safe_relative_path = os.path.join(
os.path.dirname(__file__), '../')
return... | [
"def",
"safe_dir",
"(",
"sub_dir",
"=",
"None",
")",
":",
"safe_relative_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'../'",
")",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
... | Absolute path from safe package directory.
:param sub_dir: Sub directory relative to safe package directory.
:type sub_dir: str
:return: The Absolute path.
:rtype: str | [
"Absolute",
"path",
"from",
"safe",
"package",
"directory",
"."
] | python | train | 28.923077 |
maximkulkin/hypothesis-regex | hypothesis_regex.py | https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L170-L329 | def _strategy(codes, context):
"""
Convert SRE regex parse tree to strategy that generates strings matching that
regex represented by that parse tree.
`codes` is either a list of SRE regex elements representations or a particular
element representation. Each element is a tuple of element code (as s... | [
"def",
"_strategy",
"(",
"codes",
",",
"context",
")",
":",
"if",
"not",
"isinstance",
"(",
"codes",
",",
"tuple",
")",
":",
"# List of codes",
"strategies",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"codes",
")",
":",
"if",
"cod... | Convert SRE regex parse tree to strategy that generates strings matching that
regex represented by that parse tree.
`codes` is either a list of SRE regex elements representations or a particular
element representation. Each element is a tuple of element code (as string) and
parameters. E.g. regex 'ab[0... | [
"Convert",
"SRE",
"regex",
"parse",
"tree",
"to",
"strategy",
"that",
"generates",
"strings",
"matching",
"that",
"regex",
"represented",
"by",
"that",
"parse",
"tree",
"."
] | python | train | 36.225 |
googleapis/google-cloud-python | firestore/google/cloud/firestore_v1beta1/collection.py | https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/firestore/google/cloud/firestore_v1beta1/collection.py#L209-L225 | def select(self, field_paths):
"""Create a "select" query with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.select` for
more information on this method.
Args:
field_paths (Iterable[str, ...]): An iterable of field paths
(``.`... | [
"def",
"select",
"(",
"self",
",",
"field_paths",
")",
":",
"query",
"=",
"query_mod",
".",
"Query",
"(",
"self",
")",
"return",
"query",
".",
"select",
"(",
"field_paths",
")"
] | Create a "select" query with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.select` for
more information on this method.
Args:
field_paths (Iterable[str, ...]): An iterable of field paths
(``.``-delimited list of field names) to use as... | [
"Create",
"a",
"select",
"query",
"with",
"this",
"collection",
"as",
"parent",
"."
] | python | train | 34.764706 |
materialsproject/pymatgen | pymatgen/io/abinit/nodes.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/nodes.py#L170-L190 | def apply_getters(self, task):
"""
This function is called when we specify the task dependencies with the syntax:
deps={node: "@property"}
In this case the task has to the get `property` from `node` before starting the calculation.
At present, the following properties are ... | [
"def",
"apply_getters",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"self",
".",
"getters",
":",
"return",
"for",
"getter",
"in",
"self",
".",
"getters",
":",
"if",
"getter",
"==",
"\"@structure\"",
":",
"task",
".",
"history",
".",
"info",
"(",
... | This function is called when we specify the task dependencies with the syntax:
deps={node: "@property"}
In this case the task has to the get `property` from `node` before starting the calculation.
At present, the following properties are supported:
- @structure | [
"This",
"function",
"is",
"called",
"when",
"we",
"specify",
"the",
"task",
"dependencies",
"with",
"the",
"syntax",
":"
] | python | train | 34.857143 |
wakatime/wakatime | wakatime/packages/pygments/lexers/__init__.py | https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/__init__.py#L288-L309 | def guess_lexer(_text, **options):
"""Guess a lexer by strong distinctions in the text (eg, shebang)."""
# try to get a vim modeline first
ft = get_filetype_from_buffer(_text)
if ft is not None:
try:
return get_lexer_by_name(ft, **options)
except ClassNotFound:
... | [
"def",
"guess_lexer",
"(",
"_text",
",",
"*",
"*",
"options",
")",
":",
"# try to get a vim modeline first",
"ft",
"=",
"get_filetype_from_buffer",
"(",
"_text",
")",
"if",
"ft",
"is",
"not",
"None",
":",
"try",
":",
"return",
"get_lexer_by_name",
"(",
"ft",
... | Guess a lexer by strong distinctions in the text (eg, shebang). | [
"Guess",
"a",
"lexer",
"by",
"strong",
"distinctions",
"in",
"the",
"text",
"(",
"eg",
"shebang",
")",
"."
] | python | train | 31.409091 |
ev3dev/ev3dev-lang-python | ev3dev2/led.py | https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/led.py#L389-L400 | def reset(self):
"""
Put all LEDs back to their default color
"""
if not self.leds:
return
self.animate_stop()
for group in self.led_groups:
self.set_color(group, LED_DEFAULT_COLOR) | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"leds",
":",
"return",
"self",
".",
"animate_stop",
"(",
")",
"for",
"group",
"in",
"self",
".",
"led_groups",
":",
"self",
".",
"set_color",
"(",
"group",
",",
"LED_DEFAULT_COLOR",
")"
] | Put all LEDs back to their default color | [
"Put",
"all",
"LEDs",
"back",
"to",
"their",
"default",
"color"
] | python | train | 20.416667 |
RiotGames/cloud-inquisitor | plugins/public/cinq-collector-aws/cinq_collector_aws/region.py | https://github.com/RiotGames/cloud-inquisitor/blob/181dc2566ca59fc855f695b7fcc2c3b934e6ee9f/plugins/public/cinq-collector-aws/cinq_collector_aws/region.py#L307-L374 | def update_snapshots(self):
"""Update list of EBS Snapshots for the account / region
Returns:
`None`
"""
self.log.debug('Updating EBSSnapshots for {}/{}'.format(self.account.account_name, self.region))
ec2 = self.session.resource('ec2', region_name=self.region)
... | [
"def",
"update_snapshots",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Updating EBSSnapshots for {}/{}'",
".",
"format",
"(",
"self",
".",
"account",
".",
"account_name",
",",
"self",
".",
"region",
")",
")",
"ec2",
"=",
"self",
".",
... | Update list of EBS Snapshots for the account / region
Returns:
`None` | [
"Update",
"list",
"of",
"EBS",
"Snapshots",
"for",
"the",
"account",
"/",
"region"
] | python | train | 39.573529 |
mseclab/PyJFuzz | gramfuzz/gramfuzz/fields.py | https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/gramfuzz/gramfuzz/fields.py#L726-L753 | def build(self, pre=None, shortest=False):
"""Build the ``Ref`` instance by fetching the rule from
the GramFuzzer instance and building it
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should... | [
"def",
"build",
"(",
"self",
",",
"pre",
"=",
"None",
",",
"shortest",
"=",
"False",
")",
":",
"global",
"REF_LEVEL",
"REF_LEVEL",
"+=",
"1",
"try",
":",
"if",
"pre",
"is",
"None",
":",
"pre",
"=",
"[",
"]",
"#print(\"{:04d} - {} - {}:{}\".format(REF_LEVEL... | Build the ``Ref`` instance by fetching the rule from
the GramFuzzer instance and building it
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. | [
"Build",
"the",
"Ref",
"instance",
"by",
"fetching",
"the",
"rule",
"from",
"the",
"GramFuzzer",
"instance",
"and",
"building",
"it"
] | python | test | 31.321429 |
ggravlingen/pytradfri | pytradfri/api/aiocoap_api.py | https://github.com/ggravlingen/pytradfri/blob/63750fa8fb27158c013d24865cdaa7fb82b3ab53/pytradfri/api/aiocoap_api.py#L187-L204 | async def generate_psk(self, security_key):
"""Generate and set a psk from the security key."""
if not self._psk:
PatchedDTLSSecurityStore.IDENTITY = 'Client_identity'.encode(
'utf-8')
PatchedDTLSSecurityStore.KEY = security_key.encode('utf-8')
comman... | [
"async",
"def",
"generate_psk",
"(",
"self",
",",
"security_key",
")",
":",
"if",
"not",
"self",
".",
"_psk",
":",
"PatchedDTLSSecurityStore",
".",
"IDENTITY",
"=",
"'Client_identity'",
".",
"encode",
"(",
"'utf-8'",
")",
"PatchedDTLSSecurityStore",
".",
"KEY",
... | Generate and set a psk from the security key. | [
"Generate",
"and",
"set",
"a",
"psk",
"from",
"the",
"security",
"key",
"."
] | python | train | 42 |
aio-libs/aioredis | aioredis/connection.py | https://github.com/aio-libs/aioredis/blob/e8c33e39558d4cc91cf70dde490d8b330c97dc2e/aioredis/connection.py#L424-L430 | def closed(self):
"""True if connection is closed."""
closed = self._closing or self._closed
if not closed and self._reader and self._reader.at_eof():
self._closing = closed = True
self._loop.call_soon(self._do_close, None)
return closed | [
"def",
"closed",
"(",
"self",
")",
":",
"closed",
"=",
"self",
".",
"_closing",
"or",
"self",
".",
"_closed",
"if",
"not",
"closed",
"and",
"self",
".",
"_reader",
"and",
"self",
".",
"_reader",
".",
"at_eof",
"(",
")",
":",
"self",
".",
"_closing",
... | True if connection is closed. | [
"True",
"if",
"connection",
"is",
"closed",
"."
] | python | train | 41 |
chrislit/abydos | abydos/distance/_manhattan.py | https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_manhattan.py#L159-L192 | def dist_manhattan(src, tar, qval=2, alphabet=None):
"""Return the normalized Manhattan distance between two strings.
This is a wrapper for :py:meth:`Manhattan.dist`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target strin... | [
"def",
"dist_manhattan",
"(",
"src",
",",
"tar",
",",
"qval",
"=",
"2",
",",
"alphabet",
"=",
"None",
")",
":",
"return",
"Manhattan",
"(",
")",
".",
"dist",
"(",
"src",
",",
"tar",
",",
"qval",
",",
"alphabet",
")"
] | Return the normalized Manhattan distance between two strings.
This is a wrapper for :py:meth:`Manhattan.dist`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : int
... | [
"Return",
"the",
"normalized",
"Manhattan",
"distance",
"between",
"two",
"strings",
"."
] | python | valid | 25.970588 |
refinery29/chassis | chassis/util/tree.py | https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/util/tree.py#L95-L99 | def add_head(self, head):
""" Add head Node """
if not isinstance(head, DependencyNode):
raise TypeError('"head" must be a DependencyNode')
self._heads.append(head) | [
"def",
"add_head",
"(",
"self",
",",
"head",
")",
":",
"if",
"not",
"isinstance",
"(",
"head",
",",
"DependencyNode",
")",
":",
"raise",
"TypeError",
"(",
"'\"head\" must be a DependencyNode'",
")",
"self",
".",
"_heads",
".",
"append",
"(",
"head",
")"
] | Add head Node | [
"Add",
"head",
"Node"
] | python | train | 39.2 |
dls-controls/pymalcolm | malcolm/core/controller.py | https://github.com/dls-controls/pymalcolm/blob/80ea667e4da26365a6cebc0249f52fdc744bd983/malcolm/core/controller.py#L215-L233 | def _handle_post(self, request):
# type: (Post) -> CallbackResponses
"""Called with the lock taken"""
method_name = request.path[1]
method = self._block[method_name]
assert isinstance(method, MethodModel), \
"Cannot Post to %s which is a %s" % (method.path, type(meth... | [
"def",
"_handle_post",
"(",
"self",
",",
"request",
")",
":",
"# type: (Post) -> CallbackResponses",
"method_name",
"=",
"request",
".",
"path",
"[",
"1",
"]",
"method",
"=",
"self",
".",
"_block",
"[",
"method_name",
"]",
"assert",
"isinstance",
"(",
"method"... | Called with the lock taken | [
"Called",
"with",
"the",
"lock",
"taken"
] | python | train | 35.473684 |
useblocks/groundwork | groundwork/patterns/gw_documents_pattern.py | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/patterns/gw_documents_pattern.py#L66-L75 | def register(self, name, content, description=None):
"""
Register a new document.
:param content: Content of this document. Jinja and rst are supported.
:type content: str
:param name: Unique name of the document for documentation purposes.
:param description: Short desc... | [
"def",
"register",
"(",
"self",
",",
"name",
",",
"content",
",",
"description",
"=",
"None",
")",
":",
"return",
"self",
".",
"__app",
".",
"documents",
".",
"register",
"(",
"name",
",",
"content",
",",
"self",
".",
"_plugin",
",",
"description",
")"... | Register a new document.
:param content: Content of this document. Jinja and rst are supported.
:type content: str
:param name: Unique name of the document for documentation purposes.
:param description: Short description of this document | [
"Register",
"a",
"new",
"document",
"."
] | python | train | 43.4 |
django-auth-ldap/django-auth-ldap | django_auth_ldap/backend.py | https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L919-L942 | def is_member_of(self, group_dn):
"""
Returns true if our user is a member of the given group.
"""
is_member = None
# Normalize the DN
group_dn = group_dn.lower()
# If we have self._group_dns, we'll use it. Otherwise, we'll try to
# avoid the cost of loa... | [
"def",
"is_member_of",
"(",
"self",
",",
"group_dn",
")",
":",
"is_member",
"=",
"None",
"# Normalize the DN",
"group_dn",
"=",
"group_dn",
".",
"lower",
"(",
")",
"# If we have self._group_dns, we'll use it. Otherwise, we'll try to",
"# avoid the cost of loading it.",
"if"... | Returns true if our user is a member of the given group. | [
"Returns",
"true",
"if",
"our",
"user",
"is",
"a",
"member",
"of",
"the",
"given",
"group",
"."
] | python | train | 29.125 |
Alignak-monitoring/alignak | alignak/dependencynode.py | https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/dependencynode.py#L417-L445 | def eval_cor_pattern(self, pattern, hosts, services, hostgroups, servicegroups, running=False):
"""Parse and build recursively a tree of DependencyNode from pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type h... | [
"def",
"eval_cor_pattern",
"(",
"self",
",",
"pattern",
",",
"hosts",
",",
"services",
",",
"hostgroups",
",",
"servicegroups",
",",
"running",
"=",
"False",
")",
":",
"pattern",
"=",
"pattern",
".",
"strip",
"(",
")",
"complex_node",
"=",
"False",
"# Look... | Parse and build recursively a tree of DependencyNode from pattern
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.Host
:param services: services list, used to find a specific service
... | [
"Parse",
"and",
"build",
"recursively",
"a",
"tree",
"of",
"DependencyNode",
"from",
"pattern"
] | python | train | 46.275862 |
caseyjlaw/rtpipe | rtpipe/cli.py | https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/cli.py#L72-L97 | def mergeall(filename, snrmin, snrmax, bdfdir):
""" Merge cands/noise files over all scans
Tries to find scans from filename, but will fall back to finding relevant files if it does not exist.
"""
filename = os.path.abspath(filename)
bignumber = 500
if os.path.exists(filename):
scans ... | [
"def",
"mergeall",
"(",
"filename",
",",
"snrmin",
",",
"snrmax",
",",
"bdfdir",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
"bignumber",
"=",
"500",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")"... | Merge cands/noise files over all scans
Tries to find scans from filename, but will fall back to finding relevant files if it does not exist. | [
"Merge",
"cands",
"/",
"noise",
"files",
"over",
"all",
"scans"
] | python | train | 43.538462 |
inasafe/inasafe | safe/gui/tools/help/definitions_help.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/help/definitions_help.py#L1459-L1470 | def _make_defaults_exposure_table():
"""Build headers for a table related to exposure classes.
:return: A table with headers.
:rtype: m.Table
"""
table = m.Table(style_class='table table-condensed table-striped')
row = m.Row()
row.add(m.Cell(tr('Name'), header=True))
row.add(m.Cell(tr('... | [
"def",
"_make_defaults_exposure_table",
"(",
")",
":",
"table",
"=",
"m",
".",
"Table",
"(",
"style_class",
"=",
"'table table-condensed table-striped'",
")",
"row",
"=",
"m",
".",
"Row",
"(",
")",
"row",
".",
"add",
"(",
"m",
".",
"Cell",
"(",
"tr",
"("... | Build headers for a table related to exposure classes.
:return: A table with headers.
:rtype: m.Table | [
"Build",
"headers",
"for",
"a",
"table",
"related",
"to",
"exposure",
"classes",
"."
] | python | train | 31.333333 |
pyviz/holoviews | holoviews/ipython/magics.py | https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/ipython/magics.py#L209-L215 | def option_completer(cls, k,v):
"Tab completion hook for the %%opts cell magic."
line = v.text_until_cursor
completions = cls.setup_completer()
compositor_defs = {el.group:el.output_type.__name__
for el in Compositor.definitions if el.group}
return cls.... | [
"def",
"option_completer",
"(",
"cls",
",",
"k",
",",
"v",
")",
":",
"line",
"=",
"v",
".",
"text_until_cursor",
"completions",
"=",
"cls",
".",
"setup_completer",
"(",
")",
"compositor_defs",
"=",
"{",
"el",
".",
"group",
":",
"el",
".",
"output_type",
... | Tab completion hook for the %%opts cell magic. | [
"Tab",
"completion",
"hook",
"for",
"the",
"%%opts",
"cell",
"magic",
"."
] | python | train | 52 |
mitsei/dlkit | dlkit/handcar/relationship/sessions.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/relationship/sessions.py#L1941-L1967 | def get_families_by_genus_type(self, family_genus_type=None):
"""Gets a ``FamilyList`` corresponding to the given family genus ``Type`` which
does not include families of genus types derived from the specified ``Type``.
In plenary mode, the returned list contains all known families
... | [
"def",
"get_families_by_genus_type",
"(",
"self",
",",
"family_genus_type",
"=",
"None",
")",
":",
"if",
"family_genus_type",
"is",
"None",
":",
"raise",
"NullArgument",
"(",
")",
"url_path",
"=",
"'/handcar/services/relationship/families'",
"families_of_type",
"=",
"... | Gets a ``FamilyList`` corresponding to the given family genus ``Type`` which
does not include families of genus types derived from the specified ``Type``.
In plenary mode, the returned list contains all known families
or an error results. Otherwise, the returned list may contain
onl... | [
"Gets",
"a",
"FamilyList",
"corresponding",
"to",
"the",
"given",
"family",
"genus",
"Type",
"which",
"does",
"not",
"include",
"families",
"of",
"genus",
"types",
"derived",
"from",
"the",
"specified",
"Type",
"."
] | python | train | 49.592593 |
noirbizarre/flask-fs | flask_fs/views.py | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/views.py#L12-L17 | def get_file(fs, filename):
'''Serve files for storages with direct file access'''
storage = by_name(fs)
if storage is None:
abort(404)
return storage.serve(filename) | [
"def",
"get_file",
"(",
"fs",
",",
"filename",
")",
":",
"storage",
"=",
"by_name",
"(",
"fs",
")",
"if",
"storage",
"is",
"None",
":",
"abort",
"(",
"404",
")",
"return",
"storage",
".",
"serve",
"(",
"filename",
")"
] | Serve files for storages with direct file access | [
"Serve",
"files",
"for",
"storages",
"with",
"direct",
"file",
"access"
] | python | train | 30.833333 |
google/grr | grr/core/grr_response_core/lib/rdfvalues/structs.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/rdfvalues/structs.py#L111-L127 | def VarintEncode(value):
"""Convert an integer to a varint and write it using the write function."""
result = b""
if value < 0:
raise ValueError("Varint can not encode a negative number.")
bits = value & 0x7f
value >>= 7
while value:
result += HIGH_CHR_MAP[bits]
bits = value & 0x7f
value >... | [
"def",
"VarintEncode",
"(",
"value",
")",
":",
"result",
"=",
"b\"\"",
"if",
"value",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Varint can not encode a negative number.\"",
")",
"bits",
"=",
"value",
"&",
"0x7f",
"value",
">>=",
"7",
"while",
"value",
":... | Convert an integer to a varint and write it using the write function. | [
"Convert",
"an",
"integer",
"to",
"a",
"varint",
"and",
"write",
"it",
"using",
"the",
"write",
"function",
"."
] | python | train | 20.705882 |
nkmathew/yasi-sexp-indenter | yasi.py | https://github.com/nkmathew/yasi-sexp-indenter/blob/6ec2a4675e79606c555bcb67494a0ba994b05805/yasi.py#L178-L197 | def backup_source_file(fname, options=None):
""" backup_source_file(fname : str)
>>> backup_source_file('~/Desktop/lisp/test.lisp')
Create a backup copy of the source file.
"""
opts = parse_options(options)
backup_dir = opts.backup_dir
assert os.path.exists(fname), \
("\n--%s-- War... | [
"def",
"backup_source_file",
"(",
"fname",
",",
"options",
"=",
"None",
")",
":",
"opts",
"=",
"parse_options",
"(",
"options",
")",
"backup_dir",
"=",
"opts",
".",
"backup_dir",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
",",
"(",
... | backup_source_file(fname : str)
>>> backup_source_file('~/Desktop/lisp/test.lisp')
Create a backup copy of the source file. | [
"backup_source_file",
"(",
"fname",
":",
"str",
")"
] | python | train | 43.85 |
artefactual-labs/mets-reader-writer | metsrw/validate.py | https://github.com/artefactual-labs/mets-reader-writer/blob/d95939cabdfdc25cb1bf67df0c84bd0d6e6a73ff/metsrw/validate.py#L130-L139 | def xsd_error_log_string(xsd_error_log):
"""Return a human-readable string representation of the error log
returned by lxml's XMLSchema validator.
"""
ret = []
for error in xsd_error_log:
ret.append(
"ERROR ON LINE {}: {}".format(error.line, error.message.encode("utf-8"))
... | [
"def",
"xsd_error_log_string",
"(",
"xsd_error_log",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"error",
"in",
"xsd_error_log",
":",
"ret",
".",
"append",
"(",
"\"ERROR ON LINE {}: {}\"",
".",
"format",
"(",
"error",
".",
"line",
",",
"error",
".",
"message",
... | Return a human-readable string representation of the error log
returned by lxml's XMLSchema validator. | [
"Return",
"a",
"human",
"-",
"readable",
"string",
"representation",
"of",
"the",
"error",
"log",
"returned",
"by",
"lxml",
"s",
"XMLSchema",
"validator",
"."
] | python | train | 33.9 |
PredixDev/predixpy | predix/security/acs.py | https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L288-L296 | def _get_policy_set_uri(self, guid=None):
"""
Returns the full path that uniquely identifies
the subject endpoint.
"""
uri = self.uri + '/v1/policy-set'
if guid:
uri += '/' + urllib.quote_plus(guid)
return uri | [
"def",
"_get_policy_set_uri",
"(",
"self",
",",
"guid",
"=",
"None",
")",
":",
"uri",
"=",
"self",
".",
"uri",
"+",
"'/v1/policy-set'",
"if",
"guid",
":",
"uri",
"+=",
"'/'",
"+",
"urllib",
".",
"quote_plus",
"(",
"guid",
")",
"return",
"uri"
] | Returns the full path that uniquely identifies
the subject endpoint. | [
"Returns",
"the",
"full",
"path",
"that",
"uniquely",
"identifies",
"the",
"subject",
"endpoint",
"."
] | python | train | 29.888889 |
pre-commit/pre-commit-hooks | pre_commit_hooks/check_docstring_first.py | https://github.com/pre-commit/pre-commit-hooks/blob/6d7906e131976a1ce14ab583badb734727c5da3e/pre_commit_hooks/check_docstring_first.py#L26-L62 | def check_docstring_first(src, filename='<unknown>'):
# type: (bytes, str) -> int
"""Returns nonzero if the source has what looks like a docstring that is
not at the beginning of the source.
A string will be considered a docstring if it is a STRING token with a
col offset of 0.
"""
found_do... | [
"def",
"check_docstring_first",
"(",
"src",
",",
"filename",
"=",
"'<unknown>'",
")",
":",
"# type: (bytes, str) -> int",
"found_docstring_line",
"=",
"None",
"found_code_line",
"=",
"None",
"tok_gen",
"=",
"tokenize_tokenize",
"(",
"io",
".",
"BytesIO",
"(",
"src",... | Returns nonzero if the source has what looks like a docstring that is
not at the beginning of the source.
A string will be considered a docstring if it is a STRING token with a
col offset of 0. | [
"Returns",
"nonzero",
"if",
"the",
"source",
"has",
"what",
"looks",
"like",
"a",
"docstring",
"that",
"is",
"not",
"at",
"the",
"beginning",
"of",
"the",
"source",
"."
] | python | train | 36.378378 |
gwpy/gwpy | gwpy/segments/flag.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/segments/flag.py#L667-L710 | def populate(self, source=DEFAULT_SEGMENT_SERVER, segments=None,
pad=True, **kwargs):
"""Query the segment database for this flag's active segments.
This method assumes all of the metadata for each flag have been
filled. Minimally, the following attributes must be filled
... | [
"def",
"populate",
"(",
"self",
",",
"source",
"=",
"DEFAULT_SEGMENT_SERVER",
",",
"segments",
"=",
"None",
",",
"pad",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"tmp",
"=",
"DataQualityDict",
"(",
")",
"tmp",
"[",
"self",
".",
"name",
"]",
"="... | Query the segment database for this flag's active segments.
This method assumes all of the metadata for each flag have been
filled. Minimally, the following attributes must be filled
.. autosummary::
~DataQualityFlag.name
~DataQualityFlag.known
Segments will be ... | [
"Query",
"the",
"segment",
"database",
"for",
"this",
"flag",
"s",
"active",
"segments",
"."
] | python | train | 34.136364 |
awslabs/aws-sam-cli | samcli/local/lambdafn/zip.py | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/lambdafn/zip.py#L23-L51 | def unzip(zip_file_path, output_dir, permission=None):
"""
Unzip the given file into the given directory while preserving file permissions in the process.
Parameters
----------
zip_file_path : str
Path to the zip file
output_dir : str
Path to the directory where the it should b... | [
"def",
"unzip",
"(",
"zip_file_path",
",",
"output_dir",
",",
"permission",
"=",
"None",
")",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"zip_file_path",
",",
"'r'",
")",
"as",
"zip_ref",
":",
"# For each item in the zip file, extract the file and set permissions if... | Unzip the given file into the given directory while preserving file permissions in the process.
Parameters
----------
zip_file_path : str
Path to the zip file
output_dir : str
Path to the directory where the it should be unzipped to
permission : octal int
Permission to set | [
"Unzip",
"the",
"given",
"file",
"into",
"the",
"given",
"directory",
"while",
"preserving",
"file",
"permissions",
"in",
"the",
"process",
"."
] | python | train | 30.241379 |
inveniosoftware-attic/invenio-comments | invenio_comments/api.py | https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/api.py#L2373-L2414 | def toggle_comment_visibility(uid, comid, collapse, recid):
"""
Toggle the visibility of the given comment (collapse) for the
given user. Return the new visibility
:param uid: the user id for which the change applies
:param comid: the comment id to close/open
:param collapse: if the comment is... | [
"def",
"toggle_comment_visibility",
"(",
"uid",
",",
"comid",
",",
"collapse",
",",
"recid",
")",
":",
"# We rely on the client to tell if comment should be collapsed or",
"# developed, to ensure consistency between our internal state and",
"# client state. Even if not strictly necessar... | Toggle the visibility of the given comment (collapse) for the
given user. Return the new visibility
:param uid: the user id for which the change applies
:param comid: the comment id to close/open
:param collapse: if the comment is to be closed (1) or opened (0)
:param recid: the record id to which... | [
"Toggle",
"the",
"visibility",
"of",
"the",
"given",
"comment",
"(",
"collapse",
")",
"for",
"the",
"given",
"user",
".",
"Return",
"the",
"new",
"visibility"
] | python | train | 48.214286 |
dcos/shakedown | shakedown/dcos/task.py | https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/task.py#L107-L115 | def task_property_present_predicate(service, task, prop):
""" True if the json_element passed is present for the task specified.
"""
try:
response = get_service_task(service, task)
except Exception as e:
pass
return (response is not None) and (prop in response) | [
"def",
"task_property_present_predicate",
"(",
"service",
",",
"task",
",",
"prop",
")",
":",
"try",
":",
"response",
"=",
"get_service_task",
"(",
"service",
",",
"task",
")",
"except",
"Exception",
"as",
"e",
":",
"pass",
"return",
"(",
"response",
"is",
... | True if the json_element passed is present for the task specified. | [
"True",
"if",
"the",
"json_element",
"passed",
"is",
"present",
"for",
"the",
"task",
"specified",
"."
] | python | train | 32.222222 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L3823-L3833 | def set_start(self,time,pad = None):
"""
Set the start time of the datafind query.
@param time: GPS start time of query.
"""
if pad:
self.add_var_opt('gps-start-time', int(time)-int(pad))
else:
self.add_var_opt('gps-start-time', int(time))
self.__start = time
self.__set_outpu... | [
"def",
"set_start",
"(",
"self",
",",
"time",
",",
"pad",
"=",
"None",
")",
":",
"if",
"pad",
":",
"self",
".",
"add_var_opt",
"(",
"'gps-start-time'",
",",
"int",
"(",
"time",
")",
"-",
"int",
"(",
"pad",
")",
")",
"else",
":",
"self",
".",
"add... | Set the start time of the datafind query.
@param time: GPS start time of query. | [
"Set",
"the",
"start",
"time",
"of",
"the",
"datafind",
"query",
"."
] | python | train | 28.454545 |
NoneGG/aredis | aredis/pipeline.py | https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pipeline.py#L633-L643 | def block_pipeline_command(func):
"""
Prints error because some pipelined commands should be blocked when running in cluster-mode
"""
def inner(*args, **kwargs):
raise RedisClusterException(
"ERROR: Calling pipelined function {0} is blocked when running redis in cluster mode...".for... | [
"def",
"block_pipeline_command",
"(",
"func",
")",
":",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"RedisClusterException",
"(",
"\"ERROR: Calling pipelined function {0} is blocked when running redis in cluster mode...\"",
".",
"format",... | Prints error because some pipelined commands should be blocked when running in cluster-mode | [
"Prints",
"error",
"because",
"some",
"pipelined",
"commands",
"should",
"be",
"blocked",
"when",
"running",
"in",
"cluster",
"-",
"mode"
] | python | train | 33.090909 |
jim-easterbrook/pywws | src/pywws/device_pyusb.py | https://github.com/jim-easterbrook/pywws/blob/4e4d74cee5a3ac5bf42286feaa251cd2ffcaf02c/src/pywws/device_pyusb.py#L135-L155 | def write_data(self, buf):
"""Send data to the device.
If the write fails for any reason, an :obj:`IOError` exception
is raised.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool
"""
result = self.devh.c... | [
"def",
"write_data",
"(",
"self",
",",
"buf",
")",
":",
"result",
"=",
"self",
".",
"devh",
".",
"controlMsg",
"(",
"usb",
".",
"ENDPOINT_OUT",
"+",
"usb",
".",
"TYPE_CLASS",
"+",
"usb",
".",
"RECIP_INTERFACE",
",",
"usb",
".",
"REQ_SET_CONFIGURATION",
"... | Send data to the device.
If the write fails for any reason, an :obj:`IOError` exception
is raised.
:param buf: the data to send.
:type buf: list(int)
:return: success status.
:rtype: bool | [
"Send",
"data",
"to",
"the",
"device",
"."
] | python | train | 27.428571 |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/interactiveshell.py#L1900-L1936 | def init_completer(self):
"""Initialize the completion machinery.
This creates completion machinery that can be used by client code,
either interactively in-process (typically triggered by the readline
library), programatically (such as in test suites) or out-of-prcess
(typicall... | [
"def",
"init_completer",
"(",
"self",
")",
":",
"from",
"IPython",
".",
"core",
".",
"completer",
"import",
"IPCompleter",
"from",
"IPython",
".",
"core",
".",
"completerlib",
"import",
"(",
"module_completer",
",",
"magic_run_completer",
",",
"cd_completer",
",... | Initialize the completion machinery.
This creates completion machinery that can be used by client code,
either interactively in-process (typically triggered by the readline
library), programatically (such as in test suites) or out-of-prcess
(typically over the network by remote frontend... | [
"Initialize",
"the",
"completion",
"machinery",
"."
] | python | test | 51.621622 |
BD2KGenomics/toil-scripts | src/toil_scripts/rnaseq_unc/rnaseq_unc_pipeline.py | https://github.com/BD2KGenomics/toil-scripts/blob/f878d863defcdccaabb7fe06f991451b7a198fb7/src/toil_scripts/rnaseq_unc/rnaseq_unc_pipeline.py#L607-L625 | def rseq_qc(job, job_vars):
"""
QC module: contains QC metrics and information about the BAM post alignment
job_vars: tuple Tuple of dictionaries: input_args and ids
"""
input_args, ids = job_vars
work_dir = job.fileStore.getLocalTempDir()
uuid = input_args['uuid']
sudo = input_args... | [
"def",
"rseq_qc",
"(",
"job",
",",
"job_vars",
")",
":",
"input_args",
",",
"ids",
"=",
"job_vars",
"work_dir",
"=",
"job",
".",
"fileStore",
".",
"getLocalTempDir",
"(",
")",
"uuid",
"=",
"input_args",
"[",
"'uuid'",
"]",
"sudo",
"=",
"input_args",
"[",... | QC module: contains QC metrics and information about the BAM post alignment
job_vars: tuple Tuple of dictionaries: input_args and ids | [
"QC",
"module",
":",
"contains",
"QC",
"metrics",
"and",
"information",
"about",
"the",
"BAM",
"post",
"alignment"
] | python | train | 44.736842 |
suds-community/suds | suds/servicedefinition.py | https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/servicedefinition.py#L107-L128 | def getprefixes(self):
"""Add prefixes for each namespace referenced by parameter types."""
namespaces = []
for l in (self.params, self.types):
for t,r in l:
ns = r.namespace()
if ns[1] is None: continue
if ns[1] in namespaces: continue... | [
"def",
"getprefixes",
"(",
"self",
")",
":",
"namespaces",
"=",
"[",
"]",
"for",
"l",
"in",
"(",
"self",
".",
"params",
",",
"self",
".",
"types",
")",
":",
"for",
"t",
",",
"r",
"in",
"l",
":",
"ns",
"=",
"r",
".",
"namespace",
"(",
")",
"if... | Add prefixes for each namespace referenced by parameter types. | [
"Add",
"prefixes",
"for",
"each",
"namespace",
"referenced",
"by",
"parameter",
"types",
"."
] | python | train | 36.136364 |
pydata/xarray | xarray/core/variable.py | https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/variable.py#L515-L541 | def _validate_indexers(self, key):
""" Make sanity checks """
for dim, k in zip(self.dims, key):
if isinstance(k, BASIC_INDEXING_TYPES):
pass
else:
if not isinstance(k, Variable):
k = np.asarray(k)
if k.ndim ... | [
"def",
"_validate_indexers",
"(",
"self",
",",
"key",
")",
":",
"for",
"dim",
",",
"k",
"in",
"zip",
"(",
"self",
".",
"dims",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"k",
",",
"BASIC_INDEXING_TYPES",
")",
":",
"pass",
"else",
":",
"if",
"no... | Make sanity checks | [
"Make",
"sanity",
"checks"
] | python | train | 52.777778 |
goose3/goose3 | goose3/outputformatters.py | https://github.com/goose3/goose3/blob/e6994b1b1826af2720a091d1bff5ca15594f558d/goose3/outputformatters.py#L104-L108 | def make_list_elms_pretty(self):
""" make any list element read like a list
"""
for elm in self.parser.getElementsByTag(self.top_node, tag='li'):
elm.text = r'• {}'.format(elm.text) | [
"def",
"make_list_elms_pretty",
"(",
"self",
")",
":",
"for",
"elm",
"in",
"self",
".",
"parser",
".",
"getElementsByTag",
"(",
"self",
".",
"top_node",
",",
"tag",
"=",
"'li'",
")",
":",
"elm",
".",
"text",
"=",
"r'• {}'.f",
"o",
"rmat(e",
"l",
"m.t",... | make any list element read like a list | [
"make",
"any",
"list",
"element",
"read",
"like",
"a",
"list"
] | python | valid | 42.6 |
Karaage-Cluster/karaage | karaage/datastores/ldap.py | https://github.com/Karaage-Cluster/karaage/blob/2f4c8b4e2d728b3fcbb151160c49000f1c04f5c9/karaage/datastores/ldap.py#L174-L181 | def add_account_to_group(self, account, group):
""" Add account to group. """
lgroup: OpenldapGroup = self._get_group(group.name)
person: OpenldapAccount = self._get_account(account.username)
changes = changeset(lgroup, {})
changes = lgroup.add_member(changes, person)
sa... | [
"def",
"add_account_to_group",
"(",
"self",
",",
"account",
",",
"group",
")",
":",
"lgroup",
":",
"OpenldapGroup",
"=",
"self",
".",
"_get_group",
"(",
"group",
".",
"name",
")",
"person",
":",
"OpenldapAccount",
"=",
"self",
".",
"_get_account",
"(",
"ac... | Add account to group. | [
"Add",
"account",
"to",
"group",
"."
] | python | train | 43.625 |
materialsproject/pymatgen | pymatgen/io/vasp/outputs.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/outputs.py#L576-L582 | def converged_ionic(self):
"""
Checks that ionic step convergence has been reached, i.e. that vasp
exited before reaching the max ionic steps for a relaxation run
"""
nsw = self.parameters.get("NSW", 0)
return nsw <= 1 or len(self.ionic_steps) < nsw | [
"def",
"converged_ionic",
"(",
"self",
")",
":",
"nsw",
"=",
"self",
".",
"parameters",
".",
"get",
"(",
"\"NSW\"",
",",
"0",
")",
"return",
"nsw",
"<=",
"1",
"or",
"len",
"(",
"self",
".",
"ionic_steps",
")",
"<",
"nsw"
] | Checks that ionic step convergence has been reached, i.e. that vasp
exited before reaching the max ionic steps for a relaxation run | [
"Checks",
"that",
"ionic",
"step",
"convergence",
"has",
"been",
"reached",
"i",
".",
"e",
".",
"that",
"vasp",
"exited",
"before",
"reaching",
"the",
"max",
"ionic",
"steps",
"for",
"a",
"relaxation",
"run"
] | python | train | 41.571429 |
django-admin-tools/django-admin-tools | admin_tools/utils.py | https://github.com/django-admin-tools/django-admin-tools/blob/ba6f46f51ebd84fcf84f2f79ec9487f45452d79b/admin_tools/utils.py#L71-L120 | def filter_models(request, models, exclude):
"""
Returns (model, perm,) for all models that match models/exclude patterns
and are visible by current user.
"""
items = get_avail_models(request)
included = []
def full_name(model):
return '%s.%s' % (model.__module__, model.__name__)
... | [
"def",
"filter_models",
"(",
"request",
",",
"models",
",",
"exclude",
")",
":",
"items",
"=",
"get_avail_models",
"(",
"request",
")",
"included",
"=",
"[",
"]",
"def",
"full_name",
"(",
"model",
")",
":",
"return",
"'%s.%s'",
"%",
"(",
"model",
".",
... | Returns (model, perm,) for all models that match models/exclude patterns
and are visible by current user. | [
"Returns",
"(",
"model",
"perm",
")",
"for",
"all",
"models",
"that",
"match",
"models",
"/",
"exclude",
"patterns",
"and",
"are",
"visible",
"by",
"current",
"user",
"."
] | python | train | 35.96 |
taddeus/wspy | frame.py | https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/frame.py#L70-L110 | def pack(self):
"""
Pack the frame into a string according to the following scheme:
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) ... | [
"def",
"pack",
"(",
"self",
")",
":",
"header",
"=",
"struct",
".",
"pack",
"(",
"'!B'",
",",
"(",
"self",
".",
"final",
"<<",
"7",
")",
"|",
"(",
"self",
".",
"rsv1",
"<<",
"6",
")",
"|",
"(",
"self",
".",
"rsv2",
"<<",
"5",
")",
"|",
"(",... | Pack the frame into a string according to the following scheme:
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| ... | [
"Pack",
"the",
"frame",
"into",
"a",
"string",
"according",
"to",
"the",
"following",
"scheme",
":"
] | python | train | 51.390244 |
ph4r05/monero-serialize | monero_serialize/xmrrpc.py | https://github.com/ph4r05/monero-serialize/blob/cebb3ba2aaf2e9211b1dcc6db2bab02946d06e42/monero_serialize/xmrrpc.py#L231-L248 | async def dump_varint(writer, val):
"""
Binary dump of the variable size integer
:param writer:
:param val:
:return:
"""
if val <= 63:
return await dump_varint_t(writer, PortableRawSizeMark.BYTE, val)
elif val <= 16383:
return await dump_varint_t(writer, PortableRawSizeM... | [
"async",
"def",
"dump_varint",
"(",
"writer",
",",
"val",
")",
":",
"if",
"val",
"<=",
"63",
":",
"return",
"await",
"dump_varint_t",
"(",
"writer",
",",
"PortableRawSizeMark",
".",
"BYTE",
",",
"val",
")",
"elif",
"val",
"<=",
"16383",
":",
"return",
... | Binary dump of the variable size integer
:param writer:
:param val:
:return: | [
"Binary",
"dump",
"of",
"the",
"variable",
"size",
"integer"
] | python | train | 32.611111 |
saltstack/salt | salt/cloud/clouds/proxmox.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/proxmox.py#L232-L245 | def _check_ip_available(ip_addr):
'''
Proxmox VMs refuse to start when the IP is already being used.
This function can be used to prevent VMs being created with duplicate
IP's or to generate a warning.
'''
for vm_name, vm_details in six.iteritems(get_resources_vms(includeConfig=True)):
v... | [
"def",
"_check_ip_available",
"(",
"ip_addr",
")",
":",
"for",
"vm_name",
",",
"vm_details",
"in",
"six",
".",
"iteritems",
"(",
"get_resources_vms",
"(",
"includeConfig",
"=",
"True",
")",
")",
":",
"vm_config",
"=",
"vm_details",
"[",
"'config'",
"]",
"if"... | Proxmox VMs refuse to start when the IP is already being used.
This function can be used to prevent VMs being created with duplicate
IP's or to generate a warning. | [
"Proxmox",
"VMs",
"refuse",
"to",
"start",
"when",
"the",
"IP",
"is",
"already",
"being",
"used",
".",
"This",
"function",
"can",
"be",
"used",
"to",
"prevent",
"VMs",
"being",
"created",
"with",
"duplicate",
"IP",
"s",
"or",
"to",
"generate",
"a",
"warn... | python | train | 42.071429 |
OpenMath/py-openmath | openmath/convert_pickle.py | https://github.com/OpenMath/py-openmath/blob/4906aa9ccf606f533675c28823772e07c30fd220/openmath/convert_pickle.py#L286-L307 | def load_python_global(module, name):
"""
Evaluate an OpenMath symbol describing a global Python object
EXAMPLES::
>>> from openmath.convert_pickle import to_python
>>> from openmath.convert_pickle import load_python_global
>>> load_python_global('math', 'sin')
<built-in f... | [
"def",
"load_python_global",
"(",
"module",
",",
"name",
")",
":",
"# The builtin module has been renamed in python3",
"if",
"module",
"==",
"'__builtin__'",
"and",
"six",
".",
"PY3",
":",
"module",
"=",
"'builtins'",
"module",
"=",
"importlib",
".",
"import_module"... | Evaluate an OpenMath symbol describing a global Python object
EXAMPLES::
>>> from openmath.convert_pickle import to_python
>>> from openmath.convert_pickle import load_python_global
>>> load_python_global('math', 'sin')
<built-in function sin>
>>> from openmath import ope... | [
"Evaluate",
"an",
"OpenMath",
"symbol",
"describing",
"a",
"global",
"Python",
"object"
] | python | test | 32.227273 |
dancsalo/TensorBase | tensorbase/base.py | https://github.com/dancsalo/TensorBase/blob/3d42a326452bd03427034916ff2fb90730020204/tensorbase/base.py#L218-L230 | def load_config_yaml(self, flags, config_dict):
""" Load config dict and yaml dict and then override both with flags dict. """
if config_dict is None:
print('Config File not specified. Using only input flags.')
return flags
try:
config_yaml_dict = self.cfg_fro... | [
"def",
"load_config_yaml",
"(",
"self",
",",
"flags",
",",
"config_dict",
")",
":",
"if",
"config_dict",
"is",
"None",
":",
"print",
"(",
"'Config File not specified. Using only input flags.'",
")",
"return",
"flags",
"try",
":",
"config_yaml_dict",
"=",
"self",
"... | Load config dict and yaml dict and then override both with flags dict. | [
"Load",
"config",
"dict",
"and",
"yaml",
"dict",
"and",
"then",
"override",
"both",
"with",
"flags",
"dict",
"."
] | python | train | 52.076923 |
bluedazzle/wechat_sender | wechat_sender/objects.py | https://github.com/bluedazzle/wechat_sender/blob/21d861735509153d6b34408157911c25a5d7018b/wechat_sender/objects.py#L105-L120 | def render_message(self):
"""
渲染消息
:return: 渲染后的消息
"""
message = None
if self.title:
message = '标题:{0}'.format(self.title)
if self.message_time:
message = '{0}\n时间:{1}'.format(message, self.time)
if message:
message = '... | [
"def",
"render_message",
"(",
"self",
")",
":",
"message",
"=",
"None",
"if",
"self",
".",
"title",
":",
"message",
"=",
"'标题:{0}'.forma",
"t",
"(self.",
"t",
"itle",
")",
"",
"",
"if",
"self",
".",
"message_time",
":",
"message",
"=",
"'{0}\\n时间:{1}'.fo... | 渲染消息
:return: 渲染后的消息 | [
"渲染消息"
] | python | train | 26.1875 |
SolutionsCloud/apidoc | apidoc/object/source_dto.py | https://github.com/SolutionsCloud/apidoc/blob/1ee25d886a5bea11dc744c2f3d0abb0b55d942e1/apidoc/object/source_dto.py#L273-L289 | def factory(cls, object_source):
"""Return a proper object
"""
if object_source.type is ObjectRaw.Types.object:
return ObjectObject(object_source)
elif object_source.type not in ObjectRaw.Types or object_source.type is ObjectRaw.Types.type:
return ObjectType(objec... | [
"def",
"factory",
"(",
"cls",
",",
"object_source",
")",
":",
"if",
"object_source",
".",
"type",
"is",
"ObjectRaw",
".",
"Types",
".",
"object",
":",
"return",
"ObjectObject",
"(",
"object_source",
")",
"elif",
"object_source",
".",
"type",
"not",
"in",
"... | Return a proper object | [
"Return",
"a",
"proper",
"object"
] | python | train | 46.235294 |
saltstack/salt | salt/modules/smf_service.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smf_service.py#L38-L51 | def _get_enabled_disabled(enabled_prop="true"):
'''
DRY: Get all service FMRIs and their enabled property
'''
ret = set()
cmd = '/usr/bin/svcprop -c -p general/enabled "*"'
lines = __salt__['cmd.run_stdout'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split(... | [
"def",
"_get_enabled_disabled",
"(",
"enabled_prop",
"=",
"\"true\"",
")",
":",
"ret",
"=",
"set",
"(",
")",
"cmd",
"=",
"'/usr/bin/svcprop -c -p general/enabled \"*\"'",
"lines",
"=",
"__salt__",
"[",
"'cmd.run_stdout'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",... | DRY: Get all service FMRIs and their enabled property | [
"DRY",
":",
"Get",
"all",
"service",
"FMRIs",
"and",
"their",
"enabled",
"property"
] | python | train | 33.285714 |
tradenity/python-sdk | tradenity/resources/cancel_operation.py | https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/cancel_operation.py#L645-L666 | def replace_cancel_operation_by_id(cls, cancel_operation_id, cancel_operation, **kwargs):
"""Replace CancelOperation
Replace all attributes of CancelOperation
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>... | [
"def",
"replace_cancel_operation_by_id",
"(",
"cls",
",",
"cancel_operation_id",
",",
"cancel_operation",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"ret... | Replace CancelOperation
Replace all attributes of CancelOperation
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_cancel_operation_by_id(cancel_operation_id, cancel_operation, async=True)
... | [
"Replace",
"CancelOperation"
] | python | train | 52.090909 |
nickpandolfi/Cyther | cyther/searcher.py | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/searcher.py#L75-L95 | def breadth(dirs):
"""
Crawl through directories like os.walk, but use a 'breadth first' approach
(os.walk uses 'depth first')
"""
while dirs:
next_dirs = []
print("Dirs: '{}'".format(dirs))
for d in dirs:
next_dirs = []
try:
for name i... | [
"def",
"breadth",
"(",
"dirs",
")",
":",
"while",
"dirs",
":",
"next_dirs",
"=",
"[",
"]",
"print",
"(",
"\"Dirs: '{}'\"",
".",
"format",
"(",
"dirs",
")",
")",
"for",
"d",
"in",
"dirs",
":",
"next_dirs",
"=",
"[",
"]",
"try",
":",
"for",
"name",
... | Crawl through directories like os.walk, but use a 'breadth first' approach
(os.walk uses 'depth first') | [
"Crawl",
"through",
"directories",
"like",
"os",
".",
"walk",
"but",
"use",
"a",
"breadth",
"first",
"approach",
"(",
"os",
".",
"walk",
"uses",
"depth",
"first",
")"
] | python | train | 29.761905 |
gwastro/pycbc | pycbc/rate.py | https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/rate.py#L18-L32 | def normalize_pdf(mu, pofmu):
"""
Takes a function pofmu defined at rate sample values mu and
normalizes it to be a suitable pdf. Both mu and pofmu must be
arrays or lists of the same length.
"""
if min(pofmu) < 0:
raise ValueError("Probabilities cannot be negative, don't ask me to "
... | [
"def",
"normalize_pdf",
"(",
"mu",
",",
"pofmu",
")",
":",
"if",
"min",
"(",
"pofmu",
")",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Probabilities cannot be negative, don't ask me to \"",
"\"normalize a function with negative values!\"",
")",
"if",
"min",
"(",
"... | Takes a function pofmu defined at rate sample values mu and
normalizes it to be a suitable pdf. Both mu and pofmu must be
arrays or lists of the same length. | [
"Takes",
"a",
"function",
"pofmu",
"defined",
"at",
"rate",
"sample",
"values",
"mu",
"and",
"normalizes",
"it",
"to",
"be",
"a",
"suitable",
"pdf",
".",
"Both",
"mu",
"and",
"pofmu",
"must",
"be",
"arrays",
"or",
"lists",
"of",
"the",
"same",
"length",
... | python | train | 40.2 |
UCL-INGI/INGInious | inginious/frontend/pages/course_admin/task_edit_file.py | https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit_file.py#L170-L188 | def action_create(self, courseid, taskid, path):
""" Delete a file or a directory """
# the path is given by the user. Let's normalize it
path = path.strip()
if not path.startswith("/"):
path = "/" + path
want_directory = path.endswith("/")
wanted_path = sel... | [
"def",
"action_create",
"(",
"self",
",",
"courseid",
",",
"taskid",
",",
"path",
")",
":",
"# the path is given by the user. Let's normalize it",
"path",
"=",
"path",
".",
"strip",
"(",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"p... | Delete a file or a directory | [
"Delete",
"a",
"file",
"or",
"a",
"directory"
] | python | train | 38 |
TylerGubala/bpy-build | setup.py | https://github.com/TylerGubala/bpy-build/blob/667d41526a346cfa271e26c5d675689c7ab1a254/setup.py#L120-L125 | def versions(self) -> List(BlenderVersion):
"""
The versions associated with Blender
"""
return [BlenderVersion(tag) for tag in self.git_repo.tags] + [BlenderVersion(BLENDER_VERSION_MASTER)] | [
"def",
"versions",
"(",
"self",
")",
"->",
"List",
"(",
"BlenderVersion",
")",
":",
"return",
"[",
"BlenderVersion",
"(",
"tag",
")",
"for",
"tag",
"in",
"self",
".",
"git_repo",
".",
"tags",
"]",
"+",
"[",
"BlenderVersion",
"(",
"BLENDER_VERSION_MASTER",
... | The versions associated with Blender | [
"The",
"versions",
"associated",
"with",
"Blender"
] | python | train | 36.333333 |
IDSIA/sacred | sacred/config/utils.py | https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/utils.py#L13-L65 | def assert_is_valid_key(key):
"""
Raise KeyError if a given config key violates any requirements.
The requirements are the following and can be individually deactivated
in ``sacred.SETTINGS.CONFIG_KEYS``:
* ENFORCE_MONGO_COMPATIBLE (default: True):
make sure the keys don't contain a '.' o... | [
"def",
"assert_is_valid_key",
"(",
"key",
")",
":",
"if",
"SETTINGS",
".",
"CONFIG",
".",
"ENFORCE_KEYS_MONGO_COMPATIBLE",
"and",
"(",
"isinstance",
"(",
"key",
",",
"basestring",
")",
"and",
"(",
"'.'",
"in",
"key",
"or",
"key",
"[",
"0",
"]",
"==",
"'$... | Raise KeyError if a given config key violates any requirements.
The requirements are the following and can be individually deactivated
in ``sacred.SETTINGS.CONFIG_KEYS``:
* ENFORCE_MONGO_COMPATIBLE (default: True):
make sure the keys don't contain a '.' or start with a '$'
* ENFORCE_JSONPIC... | [
"Raise",
"KeyError",
"if",
"a",
"given",
"config",
"key",
"violates",
"any",
"requirements",
"."
] | python | train | 41.90566 |
jjjake/giganews | giganews/utils.py | https://github.com/jjjake/giganews/blob/8cfb26de6c10c482a8da348d438f0ce19e477573/giganews/utils.py#L107-L129 | def get_utc_iso_date(date_str):
"""Convert date str into a iso-formatted UTC date str, i.e.:
yyyymmddhhmmss
:type date_str: str
:param date_str: date string to be parsed.
:rtype: str
:returns: iso-formatted UTC date str.
"""
try:
utc_tuple = dateutil.parser.parse(date_str).utc... | [
"def",
"get_utc_iso_date",
"(",
"date_str",
")",
":",
"try",
":",
"utc_tuple",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"date_str",
")",
".",
"utctimetuple",
"(",
")",
"except",
"ValueError",
":",
"try",
":",
"date_str",
"=",
"' '",
".",
"join"... | Convert date str into a iso-formatted UTC date str, i.e.:
yyyymmddhhmmss
:type date_str: str
:param date_str: date string to be parsed.
:rtype: str
:returns: iso-formatted UTC date str. | [
"Convert",
"date",
"str",
"into",
"a",
"iso",
"-",
"formatted",
"UTC",
"date",
"str",
"i",
".",
"e",
".",
":",
"yyyymmddhhmmss"
] | python | train | 35.695652 |
sirfoga/pyhal | hal/internet/utils.py | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/utils.py#L15-L26 | def add_params_to_url(url, params):
"""Adds params to url
:param url: Url
:param params: Params to add
:return: original url with new params
"""
url_parts = list(urlparse.urlparse(url)) # get url parts
query = dict(urlparse.parse_qsl(url_parts[4])) # get url query
query.update(params)... | [
"def",
"add_params_to_url",
"(",
"url",
",",
"params",
")",
":",
"url_parts",
"=",
"list",
"(",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
")",
"# get url parts",
"query",
"=",
"dict",
"(",
"urlparse",
".",
"parse_qsl",
"(",
"url_parts",
"[",
"4",
"]"... | Adds params to url
:param url: Url
:param params: Params to add
:return: original url with new params | [
"Adds",
"params",
"to",
"url"
] | python | train | 33.75 |
jgm/pandocfilters | pandocfilters.py | https://github.com/jgm/pandocfilters/blob/0d6b4f9be9d8e54b18b8a97e6120dd85ece53de5/pandocfilters.py#L21-L39 | def get_filename4code(module, content, ext=None):
"""Generate filename based on content
The function ensures that the (temporary) directory exists, so that the
file can be written.
Example:
filename = get_filename4code("myfilter", code)
"""
imagedir = module + "-images"
fn = hashli... | [
"def",
"get_filename4code",
"(",
"module",
",",
"content",
",",
"ext",
"=",
"None",
")",
":",
"imagedir",
"=",
"module",
"+",
"\"-images\"",
"fn",
"=",
"hashlib",
".",
"sha1",
"(",
"content",
".",
"encode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
... | Generate filename based on content
The function ensures that the (temporary) directory exists, so that the
file can be written.
Example:
filename = get_filename4code("myfilter", code) | [
"Generate",
"filename",
"based",
"on",
"content"
] | python | train | 30.157895 |
qiniu/python-sdk | qiniu/services/storage/bucket.py | https://github.com/qiniu/python-sdk/blob/a69fbef4e3e6ea1ebe09f4610a5b18bb2c17de59/qiniu/services/storage/bucket.py#L228-L245 | def change_status(self, bucket, key, status, cond):
"""修改文件的状态
修改文件的存储类型为可用或禁用:
Args:
bucket: 待操作资源所在空间
key: 待操作资源文件名
storage_type: 待操作资源存储类型,0为启用,1为禁用
"""
resource = entry(bucket, key)
if cond and isinstance(cond... | [
"def",
"change_status",
"(",
"self",
",",
"bucket",
",",
"key",
",",
"status",
",",
"cond",
")",
":",
"resource",
"=",
"entry",
"(",
"bucket",
",",
"key",
")",
"if",
"cond",
"and",
"isinstance",
"(",
"cond",
",",
"dict",
")",
":",
"condstr",
"=",
"... | 修改文件的状态
修改文件的存储类型为可用或禁用:
Args:
bucket: 待操作资源所在空间
key: 待操作资源文件名
storage_type: 待操作资源存储类型,0为启用,1为禁用 | [
"修改文件的状态"
] | python | train | 36.777778 |
wandb/client | wandb/file_pusher.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/file_pusher.py#L103-L110 | def rename_file(self, old_save_name, new_save_name, new_path):
"""This only updates the name and path we use to track the file's size
and upload progress. Doesn't rename it on the back end or make us
upload from anywhere else.
"""
if old_save_name in self._files:
del ... | [
"def",
"rename_file",
"(",
"self",
",",
"old_save_name",
",",
"new_save_name",
",",
"new_path",
")",
":",
"if",
"old_save_name",
"in",
"self",
".",
"_files",
":",
"del",
"self",
".",
"_files",
"[",
"old_save_name",
"]",
"self",
".",
"update_file",
"(",
"ne... | This only updates the name and path we use to track the file's size
and upload progress. Doesn't rename it on the back end or make us
upload from anywhere else. | [
"This",
"only",
"updates",
"the",
"name",
"and",
"path",
"we",
"use",
"to",
"track",
"the",
"file",
"s",
"size",
"and",
"upload",
"progress",
".",
"Doesn",
"t",
"rename",
"it",
"on",
"the",
"back",
"end",
"or",
"make",
"us",
"upload",
"from",
"anywhere... | python | train | 48.625 |
widdowquinn/pyani | pyani/anib.py | https://github.com/widdowquinn/pyani/blob/2b24ec971401e04024bba896e4011984fe3f53f0/pyani/anib.py#L134-L147 | def get_fraglength_dict(fastafiles):
"""Returns dictionary of sequence fragment lengths, keyed by query name.
- fastafiles - list of FASTA input whole sequence files
Loops over input files and, for each, produces a dictionary with fragment
lengths, keyed by sequence ID. These are returned as a diction... | [
"def",
"get_fraglength_dict",
"(",
"fastafiles",
")",
":",
"fraglength_dict",
"=",
"{",
"}",
"for",
"filename",
"in",
"fastafiles",
":",
"qname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
")",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"\"-fra... | Returns dictionary of sequence fragment lengths, keyed by query name.
- fastafiles - list of FASTA input whole sequence files
Loops over input files and, for each, produces a dictionary with fragment
lengths, keyed by sequence ID. These are returned as a dictionary with
the keys being query IDs derive... | [
"Returns",
"dictionary",
"of",
"sequence",
"fragment",
"lengths",
"keyed",
"by",
"query",
"name",
"."
] | python | train | 42.214286 |
Rapptz/discord.py | discord/gateway.py | https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/gateway.py#L321-L333 | async def resume(self):
"""Sends the RESUME packet."""
payload = {
'op': self.RESUME,
'd': {
'seq': self.sequence,
'session_id': self.session_id,
'token': self.token
}
}
await self.send_as_json(payload)
... | [
"async",
"def",
"resume",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'op'",
":",
"self",
".",
"RESUME",
",",
"'d'",
":",
"{",
"'seq'",
":",
"self",
".",
"sequence",
",",
"'session_id'",
":",
"self",
".",
"session_id",
",",
"'token'",
":",
"self",
... | Sends the RESUME packet. | [
"Sends",
"the",
"RESUME",
"packet",
"."
] | python | train | 29.461538 |
django-parler/django-parler | parler/cache.py | https://github.com/django-parler/django-parler/blob/11ae4af5e8faddb74c69c848870122df4006a54e/parler/cache.py#L67-L88 | def get_cached_translation(instance, language_code=None, related_name=None, use_fallback=False):
"""
Fetch an cached translation.
.. versionadded 1.2 Added the ``related_name`` parameter.
"""
if language_code is None:
language_code = instance.get_current_language()
translated_model = i... | [
"def",
"get_cached_translation",
"(",
"instance",
",",
"language_code",
"=",
"None",
",",
"related_name",
"=",
"None",
",",
"use_fallback",
"=",
"False",
")",
":",
"if",
"language_code",
"is",
"None",
":",
"language_code",
"=",
"instance",
".",
"get_current_lang... | Fetch an cached translation.
.. versionadded 1.2 Added the ``related_name`` parameter. | [
"Fetch",
"an",
"cached",
"translation",
"."
] | python | train | 32.909091 |
saltstack/salt | salt/pillar/hiera.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/hiera.py#L29-L44 | def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
conf):
'''
Execute hiera and return the data
'''
cmd = 'hiera -c {0}'.format(conf)
for key, val in six.iteritems(__grains__):
if isinstance(val, six.string_types):
cm... | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"# pylint: disable=W0613",
"pillar",
",",
"# pylint: disable=W0613",
"conf",
")",
":",
"cmd",
"=",
"'hiera -c {0}'",
".",
"format",
"(",
"conf",
")",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"_... | Execute hiera and return the data | [
"Execute",
"hiera",
"and",
"return",
"the",
"data"
] | python | train | 34.25 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.