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
gem/oq-engine
openquake/hmtk/plotting/seismicity/catalogue_plots.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hmtk/plotting/seismicity/catalogue_plots.py#L345-L353
def _plot_completeness(ax, comw, start_time, end_time): ''' Adds completeness intervals to a plot ''' comw = np.array(comw) comp = np.column_stack([np.hstack([end_time, comw[:, 0], start_time]), np.hstack([comw[0, 1], comw[:, 1], comw[-1, 1]])]) ax.step(comp[:-1, 0], ...
[ "def", "_plot_completeness", "(", "ax", ",", "comw", ",", "start_time", ",", "end_time", ")", ":", "comw", "=", "np", ".", "array", "(", "comw", ")", "comp", "=", "np", ".", "column_stack", "(", "[", "np", ".", "hstack", "(", "[", "end_time", ",", ...
Adds completeness intervals to a plot
[ "Adds", "completeness", "intervals", "to", "a", "plot" ]
python
train
43.666667
iotile/coretools
iotilebuild/iotile/build/config/site_scons/arm.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/site_scons/arm.py#L419-L469
def ensure_image_is_hex(input_path): """Return a path to a hex version of a firmware image. If the input file is already in hex format then input_path is returned and nothing is done. If it is not in hex format then an SCons action is added to convert it to hex and the target output file path is r...
[ "def", "ensure_image_is_hex", "(", "input_path", ")", ":", "family", "=", "utilities", ".", "get_family", "(", "'module_settings.json'", ")", "target", "=", "family", ".", "platform_independent_target", "(", ")", "build_dir", "=", "target", ".", "build_dirs", "(",...
Return a path to a hex version of a firmware image. If the input file is already in hex format then input_path is returned and nothing is done. If it is not in hex format then an SCons action is added to convert it to hex and the target output file path is returned. A cache is kept so that each f...
[ "Return", "a", "path", "to", "a", "hex", "version", "of", "a", "firmware", "image", "." ]
python
train
35.196078
cmap/cmapPy
cmapPy/pandasGEXpress/parse_gctx.py
https://github.com/cmap/cmapPy/blob/59d833b64fd2c3a494cdf67fe1eb11fc8008bf76/cmapPy/pandasGEXpress/parse_gctx.py#L371-L391
def get_row_metadata(gctx_file_path, convert_neg_666=True): """ Opens .gctx file and returns only row metadata Input: Mandatory: - gctx_file_path (str): full path to gctx file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to num ...
[ "def", "get_row_metadata", "(", "gctx_file_path", ",", "convert_neg_666", "=", "True", ")", ":", "full_path", "=", "os", ".", "path", ".", "expanduser", "(", "gctx_file_path", ")", "# open file", "gctx_file", "=", "h5py", ".", "File", "(", "full_path", ",", ...
Opens .gctx file and returns only row metadata Input: Mandatory: - gctx_file_path (str): full path to gctx file you want to parse. Optional: - convert_neg_666 (bool): whether to convert -666 values to num Output: - row_meta (pandas DataFrame): a DataFrame of all row me...
[ "Opens", ".", "gctx", "file", "and", "returns", "only", "row", "metadata" ]
python
train
31.333333
kristianfoerster/melodist
melodist/precipitation.py
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L90-L357
def disagg_prec_cascade(precip_daily, cascade_options, hourly=True,level=9, shift=0, test=False): """Precipitation disaggregation with cascade model (Olsson, 1998) Parameters ---------- precip_daily : pd.Series daily data ...
[ "def", "disagg_prec_cascade", "(", "precip_daily", ",", "cascade_options", ",", "hourly", "=", "True", ",", "level", "=", "9", ",", "shift", "=", "0", ",", "test", "=", "False", ")", ":", "if", "len", "(", "precip_daily", ")", "<", "2", ":", "raise", ...
Precipitation disaggregation with cascade model (Olsson, 1998) Parameters ---------- precip_daily : pd.Series daily data hourly: Boolean (for an hourly resolution disaggregation) if False, then returns 5-min disaggregated precipitation (disaggregation level depending on the "le...
[ "Precipitation", "disaggregation", "with", "cascade", "model", "(", "Olsson", "1998", ")" ]
python
train
34.679104
tanghaibao/jcvi
jcvi/projects/str.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/str.py#L611-L672
def mendelian_errors(args): """ %prog mendelian_errors STR-Mendelian-errors.csv Plot Mendelian errors as calculated by mendelian(). File `STR-Mendelian-errors.csv` looks like: ,Duos - Mendelian errors,Trios - Mendelian errors SCA36,1.40%,0.60% ULD,0.30%,1.50% BPES,0.00%,1.80% One...
[ "def", "mendelian_errors", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "mendelian_errors", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "p", ".", "set_image_options", "(", "args", ",", "figsize", "=", "\"6x6\"", ")", "if", "len"...
%prog mendelian_errors STR-Mendelian-errors.csv Plot Mendelian errors as calculated by mendelian(). File `STR-Mendelian-errors.csv` looks like: ,Duos - Mendelian errors,Trios - Mendelian errors SCA36,1.40%,0.60% ULD,0.30%,1.50% BPES,0.00%,1.80% One TRED disease per line, followed by duo ...
[ "%prog", "mendelian_errors", "STR", "-", "Mendelian", "-", "errors", ".", "csv" ]
python
train
32.241935
TUNE-Archive/freight_forwarder
freight_forwarder/config.py
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/config.py#L1227-L1272
def _update_scheme(self, scheme, ancestors): """ Updates the current scheme based off special pre-defined keys and retruns a new updated scheme. :param scheme: A :dict:, The scheme defining the validations. :param ancestors: A :OrderedDict: that provides a history of its ancestors. :rty...
[ "def", "_update_scheme", "(", "self", ",", "scheme", ",", "ancestors", ")", ":", "if", "not", "isinstance", "(", "ancestors", ",", "OrderedDict", ")", ":", "raise", "TypeError", "(", "\"ancestors must be an OrderedDict. type: {0} was passed.\"", ".", "format", "(", ...
Updates the current scheme based off special pre-defined keys and retruns a new updated scheme. :param scheme: A :dict:, The scheme defining the validations. :param ancestors: A :OrderedDict: that provides a history of its ancestors. :rtype: A new :dict: with updated scheme values.
[ "Updates", "the", "current", "scheme", "based", "off", "special", "pre", "-", "defined", "keys", "and", "retruns", "a", "new", "updated", "scheme", "." ]
python
train
45.304348
trailofbits/manticore
manticore/native/cpu/x86.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/native/cpu/x86.py#L4055-L4082
def BT(cpu, dest, src): """ Bit Test. Selects the bit in a bit string (specified with the first operand, called the bit base) at the bit-position designated by the bit offset (specified by the second operand) and stores the value of the bit in the CF flag. The bit base operand c...
[ "def", "BT", "(", "cpu", ",", "dest", ",", "src", ")", ":", "if", "dest", ".", "type", "==", "'register'", ":", "cpu", ".", "CF", "=", "(", "(", "dest", ".", "read", "(", ")", ">>", "(", "src", ".", "read", "(", ")", "%", "dest", ".", "size...
Bit Test. Selects the bit in a bit string (specified with the first operand, called the bit base) at the bit-position designated by the bit offset (specified by the second operand) and stores the value of the bit in the CF flag. The bit base operand can be a register or a memory location; the b...
[ "Bit", "Test", "." ]
python
valid
55.857143
qacafe/cdrouter.py
cdrouter/results.py
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/results.py#L682-L687
def unpause(self, id): # pylint: disable=invalid-name,redefined-builtin """Unpause a running result. :param id: Result ID as an int. """ return self.service.post(self.base+str(id)+'/unpause/')
[ "def", "unpause", "(", "self", ",", "id", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "return", "self", ".", "service", ".", "post", "(", "self", ".", "base", "+", "str", "(", "id", ")", "+", "'/unpause/'", ")" ]
Unpause a running result. :param id: Result ID as an int.
[ "Unpause", "a", "running", "result", "." ]
python
train
36.666667
google/grr
grr/core/grr_response_core/lib/utils.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/utils.py#L1099-L1111
def WriteSymlink(self, src_arcname, dst_arcname): """Writes a symlink into the archive.""" info = self._tar_fd.tarinfo() info.tarfile = self._tar_fd info.name = SmartStr(dst_arcname) info.size = 0 info.mtime = time.time() info.type = tarfile.SYMTYPE info.linkname = SmartStr(src_arcname)...
[ "def", "WriteSymlink", "(", "self", ",", "src_arcname", ",", "dst_arcname", ")", ":", "info", "=", "self", ".", "_tar_fd", ".", "tarinfo", "(", ")", "info", ".", "tarfile", "=", "self", ".", "_tar_fd", "info", ".", "name", "=", "SmartStr", "(", "dst_ar...
Writes a symlink into the archive.
[ "Writes", "a", "symlink", "into", "the", "archive", "." ]
python
train
29.461538
Kozea/cairocffi
cairocffi/patterns.py
https://github.com/Kozea/cairocffi/blob/450853add7e32eea20985b6aa5f54d9cb3cd04fe/cairocffi/patterns.py#L111-L142
def set_matrix(self, matrix): """Sets the pattern’s transformation matrix to :obj:`matrix`. This matrix is a transformation from user space to pattern space. When a pattern is first created it always has the identity matrix for its transformation matrix, which means that pattern...
[ "def", "set_matrix", "(", "self", ",", "matrix", ")", ":", "cairo", ".", "cairo_pattern_set_matrix", "(", "self", ".", "_pointer", ",", "matrix", ".", "_pointer", ")", "self", ".", "_check_status", "(", ")" ]
Sets the pattern’s transformation matrix to :obj:`matrix`. This matrix is a transformation from user space to pattern space. When a pattern is first created it always has the identity matrix for its transformation matrix, which means that pattern space is initially identical to user spa...
[ "Sets", "the", "pattern’s", "transformation", "matrix", "to", ":", "obj", ":", "matrix", ".", "This", "matrix", "is", "a", "transformation", "from", "user", "space", "to", "pattern", "space", "." ]
python
train
41.28125
mitsei/dlkit
dlkit/handcar/learning/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/learning/sessions.py#L1049-L1065
def can_access_objective_hierarchy(self): """Tests if this user can perform hierarchy queries. A return of true does not guarantee successful authorization. A return of false indicates that it is known all methods in this session will result in a PermissionDenied. This is intended as a ...
[ "def", "can_access_objective_hierarchy", "(", "self", ")", ":", "url_path", "=", "construct_url", "(", "'authorization'", ",", "bank_id", "=", "self", ".", "_catalog_idstr", ")", "return", "self", ".", "_get_request", "(", "url_path", ")", "[", "'objectiveHierarch...
Tests if this user can perform hierarchy queries. A return of true does not guarantee successful authorization. A return of false indicates that it is known all methods in this session will result in a PermissionDenied. This is intended as a hint to an an application that may not offer ...
[ "Tests", "if", "this", "user", "can", "perform", "hierarchy", "queries", "." ]
python
train
47.411765
buzzfeed/caliendo
caliendo/db/flatfiles.py
https://github.com/buzzfeed/caliendo/blob/1628a10f7782ad67c0422b5cbc9bf4979ac40abc/caliendo/db/flatfiles.py#L82-L97
def select_io( hash ): """ Returns the relevant i/o for a method whose call is characterized by the hash :param hash: The hash for the CallDescriptor :rtype list(tuple( hash, stack, methodname, returnval, args, packet_num )): """ load_cache(True) global CACHE_ res = [] record_used(...
[ "def", "select_io", "(", "hash", ")", ":", "load_cache", "(", "True", ")", "global", "CACHE_", "res", "=", "[", "]", "record_used", "(", "'cache'", ",", "hash", ")", "for", "d", "in", "CACHE_", "[", "'cache'", "]", ".", "get", "(", "hash", ",", "{"...
Returns the relevant i/o for a method whose call is characterized by the hash :param hash: The hash for the CallDescriptor :rtype list(tuple( hash, stack, methodname, returnval, args, packet_num )):
[ "Returns", "the", "relevant", "i", "/", "o", "for", "a", "method", "whose", "call", "is", "characterized", "by", "the", "hash" ]
python
train
32.3125
swharden/SWHLab
swhlab/analysis/glance.py
https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/analysis/glance.py#L37-L102
def processAbf(abfFname,saveAs=False,dpi=100,show=True): """ automatically generate a single representative image for an ABF. If saveAs is given (full path of a jpg of png file), the image will be saved. Otherwise, the image will pop up in a matplotlib window. """ if not type(abfFname) is str or...
[ "def", "processAbf", "(", "abfFname", ",", "saveAs", "=", "False", ",", "dpi", "=", "100", ",", "show", "=", "True", ")", ":", "if", "not", "type", "(", "abfFname", ")", "is", "str", "or", "not", "len", "(", "abfFname", ")", ">", "3", ":", "retur...
automatically generate a single representative image for an ABF. If saveAs is given (full path of a jpg of png file), the image will be saved. Otherwise, the image will pop up in a matplotlib window.
[ "automatically", "generate", "a", "single", "representative", "image", "for", "an", "ABF", ".", "If", "saveAs", "is", "given", "(", "full", "path", "of", "a", "jpg", "of", "png", "file", ")", "the", "image", "will", "be", "saved", ".", "Otherwise", "the"...
python
valid
37.984848
twisted/twistedchecker
check_pyflakes.py
https://github.com/twisted/twistedchecker/blob/80060e1c07cf5d67d747dbec8ec0e5ee913e8929/check_pyflakes.py#L99-L114
def iterSourceCode(paths): """ Iterate over all Python source files in C{paths}. @param paths: A list of paths. Directories will be recursed into and any .py files found will be yielded. Any non-directories will be yielded as-is. """ for path in paths: if os.path.isdir(pat...
[ "def", "iterSourceCode", "(", "paths", ")", ":", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "path", ")", ":", ...
Iterate over all Python source files in C{paths}. @param paths: A list of paths. Directories will be recursed into and any .py files found will be yielded. Any non-directories will be yielded as-is.
[ "Iterate", "over", "all", "Python", "source", "files", "in", "C", "{", "paths", "}", "." ]
python
train
35.125
michael-lazar/rtv
rtv/packages/praw/multiprocess.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/multiprocess.py#L79-L102
def run(): """The entry point from the praw-multiprocess utility.""" parser = OptionParser(version='%prog {0}'.format(__version__)) parser.add_option('-a', '--addr', default='localhost', help=('The address or host to listen on. Specify -a ' '0.0.0.0 to liste...
[ "def", "run", "(", ")", ":", "parser", "=", "OptionParser", "(", "version", "=", "'%prog {0}'", ".", "format", "(", "__version__", ")", ")", "parser", ".", "add_option", "(", "'-a'", ",", "'--addr'", ",", "default", "=", "'localhost'", ",", "help", "=", ...
The entry point from the praw-multiprocess utility.
[ "The", "entry", "point", "from", "the", "praw", "-", "multiprocess", "utility", "." ]
python
train
46.333333
moonlitesolutions/SolrClient
SolrClient/collections.py
https://github.com/moonlitesolutions/SolrClient/blob/19c5280c9f8e97ee104d22ae883c4ccfd7c4f43b/SolrClient/collections.py#L142-L172
def check_status(self, ignore=(), status=None): """ Checks status of each collection and shard to make sure that: a) Cluster state is active b) Number of docs matches across replicas for a given shard. Returns a dict of results for custom alerting. """ self.SH...
[ "def", "check_status", "(", "self", ",", "ignore", "=", "(", ")", ",", "status", "=", "None", ")", ":", "self", ".", "SHARD_CHECKS", "=", "[", "{", "'check_msg'", ":", "'Bad Core Count Check'", ",", "'f'", ":", "self", ".", "_check_shard_count", "}", ","...
Checks status of each collection and shard to make sure that: a) Cluster state is active b) Number of docs matches across replicas for a given shard. Returns a dict of results for custom alerting.
[ "Checks", "status", "of", "each", "collection", "and", "shard", "to", "make", "sure", "that", ":", "a", ")", "Cluster", "state", "is", "active", "b", ")", "Number", "of", "docs", "matches", "across", "replicas", "for", "a", "given", "shard", ".", "Return...
python
train
46.580645
Parsl/parsl
parsl/executors/serialize/serialize.py
https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/executors/serialize/serialize.py#L121-L153
def deserialize_object(buffers, g=None): """Reconstruct an object serialized by serialize_object from data buffers. Parameters ---------- bufs : list of buffers/bytes g : globals to be used when uncanning Returns ------- (newobj, bufs) : unpacked object, and the list of remaining un...
[ "def", "deserialize_object", "(", "buffers", ",", "g", "=", "None", ")", ":", "bufs", "=", "list", "(", "buffers", ")", "pobj", "=", "buffer_to_bytes_py2", "(", "bufs", ".", "pop", "(", "0", ")", ")", "canned", "=", "pickle", ".", "loads", "(", "pobj...
Reconstruct an object serialized by serialize_object from data buffers. Parameters ---------- bufs : list of buffers/bytes g : globals to be used when uncanning Returns ------- (newobj, bufs) : unpacked object, and the list of remaining unused buffers.
[ "Reconstruct", "an", "object", "serialized", "by", "serialize_object", "from", "data", "buffers", "." ]
python
valid
27.363636
graphql-python/graphql-core-next
graphql/error/print_error.py
https://github.com/graphql-python/graphql-core-next/blob/073dce3f002f897d40f9348ffd8f107815160540/graphql/error/print_error.py#L13-L35
def print_error(error: "GraphQLError") -> str: """Print a GraphQLError to a string. The printed string will contain useful location information about the error's position in the source. """ printed_locations: List[str] = [] print_location = printed_locations.append if error.nodes: f...
[ "def", "print_error", "(", "error", ":", "\"GraphQLError\"", ")", "->", "str", ":", "printed_locations", ":", "List", "[", "str", "]", "=", "[", "]", "print_location", "=", "printed_locations", ".", "append", "if", "error", ".", "nodes", ":", "for", "node"...
Print a GraphQLError to a string. The printed string will contain useful location information about the error's position in the source.
[ "Print", "a", "GraphQLError", "to", "a", "string", "." ]
python
train
37.608696
senaite/senaite.core
bika/lims/browser/worksheet/views/referencesamples.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/worksheet/views/referencesamples.py#L204-L213
def make_position_choices(self): """Create choices for available positions """ choices = [] for pos in self.get_available_positions(): choices.append({ "ResultValue": pos, "ResultText": pos, }) return choices
[ "def", "make_position_choices", "(", "self", ")", ":", "choices", "=", "[", "]", "for", "pos", "in", "self", ".", "get_available_positions", "(", ")", ":", "choices", ".", "append", "(", "{", "\"ResultValue\"", ":", "pos", ",", "\"ResultText\"", ":", "pos"...
Create choices for available positions
[ "Create", "choices", "for", "available", "positions" ]
python
train
29.5
kashifrazzaqui/json-streamer
jsonstreamer/jsonstreamer.py
https://github.com/kashifrazzaqui/json-streamer/blob/f87527d57557d11682c12727a1a4eeda9cca3c8f/jsonstreamer/jsonstreamer.py#L147-L156
def on_number(self, ctx, value): ''' Since this is defined both integer and double callbacks are useless ''' value = int(value) if value.isdigit() else float(value) top = self._stack[-1] if top is JSONCompositeType.OBJECT: self.fire(JSONStreamer.VALUE_EVENT, value) el...
[ "def", "on_number", "(", "self", ",", "ctx", ",", "value", ")", ":", "value", "=", "int", "(", "value", ")", "if", "value", ".", "isdigit", "(", ")", "else", "float", "(", "value", ")", "top", "=", "self", ".", "_stack", "[", "-", "1", "]", "if...
Since this is defined both integer and double callbacks are useless
[ "Since", "this", "is", "defined", "both", "integer", "and", "double", "callbacks", "are", "useless" ]
python
train
47.8
inveniosoftware/invenio-access
invenio_access/permissions.py
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/permissions.py#L122-L165
def _load_permissions(self): """Load permissions associated to actions.""" result = _P(needs=set(), excludes=set()) if not self.allow_by_default: result.needs.update(self.explicit_needs) for explicit_need in self.explicit_needs: if explicit_need.method == 'action...
[ "def", "_load_permissions", "(", "self", ")", ":", "result", "=", "_P", "(", "needs", "=", "set", "(", ")", ",", "excludes", "=", "set", "(", ")", ")", "if", "not", "self", ".", "allow_by_default", ":", "result", ".", "needs", ".", "update", "(", "...
Load permissions associated to actions.
[ "Load", "permissions", "associated", "to", "actions", "." ]
python
train
37.681818
chris1610/barnum-proj
barnum/gencc.py
https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gencc.py#L63-L90
def completed_number(prefix, length): """ 'prefix' is the start of the CC number as a string, any number of digits. 'length' is the length of the CC number to generate. Typically 13 or 16 """ ccnumber = prefix # generate digits while len(ccnumber) < (length - 1): digit = random.choic...
[ "def", "completed_number", "(", "prefix", ",", "length", ")", ":", "ccnumber", "=", "prefix", "# generate digits", "while", "len", "(", "ccnumber", ")", "<", "(", "length", "-", "1", ")", ":", "digit", "=", "random", ".", "choice", "(", "[", "'0'", ","...
'prefix' is the start of the CC number as a string, any number of digits. 'length' is the length of the CC number to generate. Typically 13 or 16
[ "prefix", "is", "the", "start", "of", "the", "CC", "number", "as", "a", "string", "any", "number", "of", "digits", ".", "length", "is", "the", "length", "of", "the", "CC", "number", "to", "generate", ".", "Typically", "13", "or", "16" ]
python
train
32.25
cggh/scikit-allel
allel/stats/distance.py
https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/stats/distance.py#L255-L288
def condensed_coords(i, j, n): """Transform square distance matrix coordinates to the corresponding index into a condensed, 1D form of the matrix. Parameters ---------- i : int Row index. j : int Column index. n : int Size of the square matrix (length of first or sec...
[ "def", "condensed_coords", "(", "i", ",", "j", ",", "n", ")", ":", "# guard conditions", "if", "i", "==", "j", "or", "i", ">=", "n", "or", "j", ">=", "n", "or", "i", "<", "0", "or", "j", "<", "0", ":", "raise", "ValueError", "(", "'invalid coordi...
Transform square distance matrix coordinates to the corresponding index into a condensed, 1D form of the matrix. Parameters ---------- i : int Row index. j : int Column index. n : int Size of the square matrix (length of first or second dimension). Returns -----...
[ "Transform", "square", "distance", "matrix", "coordinates", "to", "the", "corresponding", "index", "into", "a", "condensed", "1D", "form", "of", "the", "matrix", "." ]
python
train
22.235294
globality-corp/microcosm-flask
microcosm_flask/conventions/upload.py
https://github.com/globality-corp/microcosm-flask/blob/c2eaf57f03e7d041eea343751a4a90fcc80df418/microcosm_flask/conventions/upload.py#L130-L136
def configure_upload(graph, ns, mappings, exclude_func=None): """ Register Upload endpoints for a resource object. """ convention = UploadConvention(graph, exclude_func) convention.configure(ns, mappings)
[ "def", "configure_upload", "(", "graph", ",", "ns", ",", "mappings", ",", "exclude_func", "=", "None", ")", ":", "convention", "=", "UploadConvention", "(", "graph", ",", "exclude_func", ")", "convention", ".", "configure", "(", "ns", ",", "mappings", ")" ]
Register Upload endpoints for a resource object.
[ "Register", "Upload", "endpoints", "for", "a", "resource", "object", "." ]
python
train
31.285714
ActivisionGameScience/assertpy
assertpy/assertpy.py
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L570-L607
def contains_ignoring_case(self, *items): """Asserts that val is string and contains the given item or items.""" if len(items) == 0: raise ValueError('one or more args must be given') if isinstance(self.val, str_types): if len(items) == 1: if not isinstanc...
[ "def", "contains_ignoring_case", "(", "self", ",", "*", "items", ")", ":", "if", "len", "(", "items", ")", "==", "0", ":", "raise", "ValueError", "(", "'one or more args must be given'", ")", "if", "isinstance", "(", "self", ".", "val", ",", "str_types", "...
Asserts that val is string and contains the given item or items.
[ "Asserts", "that", "val", "is", "string", "and", "contains", "the", "given", "item", "or", "items", "." ]
python
valid
51.052632
msmbuilder/msmbuilder
msmbuilder/cluster/regularspatial.py
https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/cluster/regularspatial.py#L83-L102
def predict(self, X): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters -------...
[ "def", "predict", "(", "self", ",", "X", ")", ":", "labels", ",", "inertia", "=", "libdistance", ".", "assign_nearest", "(", "X", ",", "self", ".", "cluster_centers_", ",", "metric", "=", "self", ".", "metric", ")", "return", "labels" ]
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : array-like, shape...
[ "Predict", "the", "closest", "cluster", "each", "sample", "in", "X", "belongs", "to", "." ]
python
train
33.7
hydpy-dev/hydpy
hydpy/core/sequencetools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1090-L1127
def check_completeness(self): """Raise a |RuntimeError| if the |IOSequence.series| contains at least one |numpy.nan| value, if option |Options.checkseries| is enabled. >>> from hydpy import pub >>> pub.timegrids = '2000-01-01', '2000-01-11', '1d' >>> from hydpy.core.sequ...
[ "def", "check_completeness", "(", "self", ")", ":", "if", "hydpy", ".", "pub", ".", "options", ".", "checkseries", ":", "isnan", "=", "numpy", ".", "isnan", "(", "self", ".", "series", ")", "if", "numpy", ".", "any", "(", "isnan", ")", ":", "nmb", ...
Raise a |RuntimeError| if the |IOSequence.series| contains at least one |numpy.nan| value, if option |Options.checkseries| is enabled. >>> from hydpy import pub >>> pub.timegrids = '2000-01-01', '2000-01-11', '1d' >>> from hydpy.core.sequencetools import IOSequence >>> c...
[ "Raise", "a", "|RuntimeError|", "if", "the", "|IOSequence", ".", "series|", "contains", "at", "least", "one", "|numpy", ".", "nan|", "value", "if", "option", "|Options", ".", "checkseries|", "is", "enabled", "." ]
python
train
37.289474
mixmastamyk/fr
fr/ansi.py
https://github.com/mixmastamyk/fr/blob/f96df8ed7210a033b9e711bbed768d4116213bfb/fr/ansi.py#L128-L134
def cprint(text, fg=grey, bg=blackbg, w=norm, cr=False, encoding='utf8'): ''' Print a string in a specified color style and then return to normal. def cprint(text, fg=white, bg=blackbg, w=norm, cr=True): ''' colorstart(fg, bg, w) out(text) colorend(cr)
[ "def", "cprint", "(", "text", ",", "fg", "=", "grey", ",", "bg", "=", "blackbg", ",", "w", "=", "norm", ",", "cr", "=", "False", ",", "encoding", "=", "'utf8'", ")", ":", "colorstart", "(", "fg", ",", "bg", ",", "w", ")", "out", "(", "text", ...
Print a string in a specified color style and then return to normal. def cprint(text, fg=white, bg=blackbg, w=norm, cr=True):
[ "Print", "a", "string", "in", "a", "specified", "color", "style", "and", "then", "return", "to", "normal", ".", "def", "cprint", "(", "text", "fg", "=", "white", "bg", "=", "blackbg", "w", "=", "norm", "cr", "=", "True", ")", ":" ]
python
train
39.142857
hydroshare/hs_restclient
hs_restclient/__init__.py
https://github.com/hydroshare/hs_restclient/blob/9cd106238b512e01ecd3e33425fe48c13b7f63d5/hs_restclient/__init__.py#L1091-L1103
def createReferenceURL(self, pid, name, ref_url, path="", validate=True): """Create a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be created :param name: Filename for the referenced file ...
[ "def", "createReferenceURL", "(", "self", ",", "pid", ",", "name", ",", "ref_url", ",", "path", "=", "\"\"", ",", "validate", "=", "True", ")", ":", "return", "self", ".", "createReferencedFile", "(", "pid", ",", "path", ",", "name", ",", "ref_url", ",...
Create a Referenced Content File (.url) :param pid: The HydroShare ID of the resource for which the file should be created :param name: Filename for the referenced file :param ref_url: url to be used in the referenced file :...
[ "Create", "a", "Referenced", "Content", "File", "(", ".", "url", ")", ":", "param", "pid", ":", "The", "HydroShare", "ID", "of", "the", "resource", "for", "which", "the", "file", "should", "be", "created", ":", "param", "name", ":", "Filename", "for", ...
python
train
79
readbeyond/aeneas
aeneas/plotter.py
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L237-L252
def text_bounding_box(self, size_pt, text): """ Return the bounding box of the given text at the given font size. :param int size_pt: the font size in points :param string text: the text :rtype: tuple (width, height) """ if size_pt == 12: mul...
[ "def", "text_bounding_box", "(", "self", ",", "size_pt", ",", "text", ")", ":", "if", "size_pt", "==", "12", ":", "mult", "=", "{", "\"h\"", ":", "9", ",", "\"w_digit\"", ":", "5", ",", "\"w_space\"", ":", "2", "}", "elif", "size_pt", "==", "18", "...
Return the bounding box of the given text at the given font size. :param int size_pt: the font size in points :param string text: the text :rtype: tuple (width, height)
[ "Return", "the", "bounding", "box", "of", "the", "given", "text", "at", "the", "given", "font", "size", "." ]
python
train
34.75
agile-geoscience/striplog
striplog/legend.py
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/legend.py#L771-L790
def get_width(self, c, default=0, match_only=None): """ Get the display width of a component. Wraps `getattr()`. Development note: Cannot define this as a `partial()` because I want to maintain the order of arguments in `getattr()`. Args: c (component): The componen...
[ "def", "get_width", "(", "self", ",", "c", ",", "default", "=", "0", ",", "match_only", "=", "None", ")", ":", "return", "self", ".", "getattr", "(", "c", "=", "c", ",", "attr", "=", "'width'", ",", "default", "=", "default", ",", "match_only", "="...
Get the display width of a component. Wraps `getattr()`. Development note: Cannot define this as a `partial()` because I want to maintain the order of arguments in `getattr()`. Args: c (component): The component to look up. default (float): The width to return in the ev...
[ "Get", "the", "display", "width", "of", "a", "component", ".", "Wraps", "getattr", "()", "." ]
python
test
39.35
chrisjrn/registrasion
registrasion/controllers/cart.py
https://github.com/chrisjrn/registrasion/blob/461d5846c6f9f3b7099322a94f5d9911564448e4/registrasion/controllers/cart.py#L52-L67
def for_user(cls, user): ''' Returns the user's current cart, or creates a new cart if there isn't one ready yet. ''' try: existing = commerce.Cart.objects.get( user=user, status=commerce.Cart.STATUS_ACTIVE, ) except ObjectDoesNotE...
[ "def", "for_user", "(", "cls", ",", "user", ")", ":", "try", ":", "existing", "=", "commerce", ".", "Cart", ".", "objects", ".", "get", "(", "user", "=", "user", ",", "status", "=", "commerce", ".", "Cart", ".", "STATUS_ACTIVE", ",", ")", "except", ...
Returns the user's current cart, or creates a new cart if there isn't one ready yet.
[ "Returns", "the", "user", "s", "current", "cart", "or", "creates", "a", "new", "cart", "if", "there", "isn", "t", "one", "ready", "yet", "." ]
python
test
33.875
adamcharnock/swiftwind
swiftwind/housemates/forms.py
https://github.com/adamcharnock/swiftwind/blob/72c715800841c3b2feabded3f3b65b76388b4cea/swiftwind/housemates/forms.py#L28-L44
def clean_account(self): """Ensure this is an income account""" account = self.cleaned_data['account'] if not account: return if account.type != Account.TYPES.income: raise ValidationError('Account must be an income account') try: account.hou...
[ "def", "clean_account", "(", "self", ")", ":", "account", "=", "self", ".", "cleaned_data", "[", "'account'", "]", "if", "not", "account", ":", "return", "if", "account", ".", "type", "!=", "Account", ".", "TYPES", ".", "income", ":", "raise", "Validatio...
Ensure this is an income account
[ "Ensure", "this", "is", "an", "income", "account" ]
python
train
27.823529
nerdvegas/rez
src/rezgui/models/ContextModel.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/models/ContextModel.py#L113-L134
def get_lock_requests(self): """Take the current context, and the current patch locks, and determine the effective requests that will be added to the main request. Returns: A dict of (PatchLock, [Requirement]) tuples. Each requirement will be a weak package reference. If...
[ "def", "get_lock_requests", "(", "self", ")", ":", "d", "=", "defaultdict", "(", "list", ")", "if", "self", ".", "_context", ":", "for", "variant", "in", "self", ".", "_context", ".", "resolved_packages", ":", "name", "=", "variant", ".", "name", "versio...
Take the current context, and the current patch locks, and determine the effective requests that will be added to the main request. Returns: A dict of (PatchLock, [Requirement]) tuples. Each requirement will be a weak package reference. If there is no current context, an empty ...
[ "Take", "the", "current", "context", "and", "the", "current", "patch", "locks", "and", "determine", "the", "effective", "requests", "that", "will", "be", "added", "to", "the", "main", "request", "." ]
python
train
39.909091
angr/angr
angr/analyses/girlscout.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/analyses/girlscout.py#L600-L691
def _determinebase_address(self): """ The basic idea is simple: start from a specific point, try to construct functions as much as we can, and maintain a function distribution graph and a call graph simultaneously. Repeat searching until we come to the end that there is no new fu...
[ "def", "_determinebase_address", "(", "self", ")", ":", "traced_address", "=", "set", "(", ")", "self", ".", "functions", "=", "set", "(", ")", "self", ".", "call_map", "=", "networkx", ".", "DiGraph", "(", ")", "self", ".", "cfg", "=", "networkx", "."...
The basic idea is simple: start from a specific point, try to construct functions as much as we can, and maintain a function distribution graph and a call graph simultaneously. Repeat searching until we come to the end that there is no new function to be found. A function should start wi...
[ "The", "basic", "idea", "is", "simple", ":", "start", "from", "a", "specific", "point", "try", "to", "construct", "functions", "as", "much", "as", "we", "can", "and", "maintain", "a", "function", "distribution", "graph", "and", "a", "call", "graph", "simul...
python
train
48.913043
cloud9ers/gurumate
environment/lib/python2.7/site-packages/nose/selector.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/selector.py#L107-L135
def wantFile(self, file): """Is the file a wanted test file? The file must be a python source file and match testMatch or include, and not match exclude. Files that match ignore are *never* wanted, regardless of plugin, testMatch, include or exclude settings. """ # never...
[ "def", "wantFile", "(", "self", ",", "file", ")", ":", "# never, ever load files that match anything in ignore", "# (.* _* and *setup*.py by default)", "base", "=", "op_basename", "(", "file", ")", "ignore_matches", "=", "[", "ignore_this", "for", "ignore_this", "in", "...
Is the file a wanted test file? The file must be a python source file and match testMatch or include, and not match exclude. Files that match ignore are *never* wanted, regardless of plugin, testMatch, include or exclude settings.
[ "Is", "the", "file", "a", "wanted", "test", "file?" ]
python
test
42.068966
Syndace/python-doubleratchet
doubleratchet/kdfchains/kdfchain.py
https://github.com/Syndace/python-doubleratchet/blob/d4497af73044e0084efa3e447276ee9d6a6eb66a/doubleratchet/kdfchains/kdfchain.py#L49-L66
def next(self, data): """ Derive a new set of internal and output data from given input data and the data stored internally. Use the key derivation function to derive new data. The kdf gets supplied with the current key and the data passed to this method. :param data: A...
[ "def", "next", "(", "self", ",", "data", ")", ":", "self", ".", "__length", "+=", "1", "result", "=", "self", ".", "__kdf", ".", "calculate", "(", "self", ".", "__key", ",", "data", ",", "64", ")", "self", ".", "__key", "=", "result", "[", ":", ...
Derive a new set of internal and output data from given input data and the data stored internally. Use the key derivation function to derive new data. The kdf gets supplied with the current key and the data passed to this method. :param data: A bytes-like object encoding the data to pa...
[ "Derive", "a", "new", "set", "of", "internal", "and", "output", "data", "from", "given", "input", "data", "and", "the", "data", "stored", "internally", "." ]
python
valid
34.444444
hubo1016/vlcp
vlcp/service/sdn/vxlanvtep.py
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/service/sdn/vxlanvtep.py#L300-L426
async def action_handler(self): """ Call vtep controller in sequence, merge mutiple calls if possible When a bind relationship is updated, we always send all logical ports to a logicalswitch, to make sure it recovers from some failed updates (so called idempotency). When multipl...
[ "async", "def", "action_handler", "(", "self", ")", ":", "bind_event", "=", "VtepControllerCall", ".", "createMatcher", "(", "self", ".", "_conn", ")", "event_queue", "=", "[", "]", "timeout_flag", "=", "[", "False", "]", "async", "def", "handle_action", "("...
Call vtep controller in sequence, merge mutiple calls if possible When a bind relationship is updated, we always send all logical ports to a logicalswitch, to make sure it recovers from some failed updates (so called idempotency). When multiple calls are pending, we only need to send th...
[ "Call", "vtep", "controller", "in", "sequence", "merge", "mutiple", "calls", "if", "possible", "When", "a", "bind", "relationship", "is", "updated", "we", "always", "send", "all", "logical", "ports", "to", "a", "logicalswitch", "to", "make", "sure", "it", "r...
python
train
48.125984
sbarham/dsrt
dsrt/models/Decoder.py
https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/dsrt/models/Decoder.py#L34-L81
def build(self): """ The decoder computational graph consists of three components: (1) the input node `decoder_input` (2) the embedding node `decoder_embed` (3) the recurrent (RNN) part `decoder_rnn` (4) the output of th...
[ "def", "build", "(", "self", ")", ":", "# Grab hyperparameters from self.config:", "hidden_dim", "=", "self", ".", "config", "[", "'encoding-layer-width'", "]", "recurrent_unit", "=", "self", ".", "config", "[", "'recurrent-unit-type'", "]", "bidirectional", "=", "F...
The decoder computational graph consists of three components: (1) the input node `decoder_input` (2) the embedding node `decoder_embed` (3) the recurrent (RNN) part `decoder_rnn` (4) the output of the decoder RNN `decoder_output`...
[ "The", "decoder", "computational", "graph", "consists", "of", "three", "components", ":", "(", "1", ")", "the", "input", "node", "decoder_input", "(", "2", ")", "the", "embedding", "node", "decoder_embed", "(", "3", ")", "the", "recurrent", "(", "RNN", ")"...
python
train
49.333333
DataONEorg/d1_python
lib_client/src/d1_client/cnclient.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/cnclient.py#L1092-L1104
def updateNodeCapabilities(self, nodeId, node, vendorSpecific=None): """See Also: updateNodeCapabilitiesResponse() Args: nodeId: node: vendorSpecific: Returns: """ response = self.updateNodeCapabilitiesResponse(nodeId, node, vendorSpecific) ...
[ "def", "updateNodeCapabilities", "(", "self", ",", "nodeId", ",", "node", ",", "vendorSpecific", "=", "None", ")", ":", "response", "=", "self", ".", "updateNodeCapabilitiesResponse", "(", "nodeId", ",", "node", ",", "vendorSpecific", ")", "return", "self", "....
See Also: updateNodeCapabilitiesResponse() Args: nodeId: node: vendorSpecific: Returns:
[ "See", "Also", ":", "updateNodeCapabilitiesResponse", "()" ]
python
train
27.230769
PGower/PyCanvas
pycanvas/apis/notification_preferences.py
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/notification_preferences.py#L165-L192
def update_preference_type(self, type, address, notification, notification_preferences_frequency): """ Update a preference. Change the preference for a single notification for a single communication channel """ path = {} data = {} params = {} #...
[ "def", "update_preference_type", "(", "self", ",", "type", ",", "address", ",", "notification", ",", "notification_preferences_frequency", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - type\r", "\"\"\"ID\"\...
Update a preference. Change the preference for a single notification for a single communication channel
[ "Update", "a", "preference", ".", "Change", "the", "preference", "for", "a", "single", "notification", "for", "a", "single", "communication", "channel" ]
python
train
42.785714
mapbox/mapbox-cli-py
mapboxcli/scripts/geocoding.py
https://github.com/mapbox/mapbox-cli-py/blob/b75544a2f83a4fda79d78b5673058e16e64a4f6d/mapboxcli/scripts/geocoding.py#L78-L147
def geocoding(ctx, query, forward, include_headers, lat, lon, place_type, output, dataset, country, bbox, features, limit): """This command returns places matching an address (forward mode) or places matching coordinates (reverse mode). In forward (the default) mode the query argument shall b...
[ "def", "geocoding", "(", "ctx", ",", "query", ",", "forward", ",", "include_headers", ",", "lat", ",", "lon", ",", "place_type", ",", "output", ",", "dataset", ",", "country", ",", "bbox", ",", "features", ",", "limit", ")", ":", "access_token", "=", "...
This command returns places matching an address (forward mode) or places matching coordinates (reverse mode). In forward (the default) mode the query argument shall be an address such as '1600 pennsylvania ave nw'. $ mapbox geocoding '1600 pennsylvania ave nw' In reverse mode the query argument...
[ "This", "command", "returns", "places", "matching", "an", "address", "(", "forward", "mode", ")", "or", "places", "matching", "coordinates", "(", "reverse", "mode", ")", "." ]
python
train
38.114286
pyroscope/pyrocore
src/pyrocore/scripts/base.py
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/scripts/base.py#L61-L76
def setup(cls, cron_cfg="cron"): """ Set up the runtime environment. """ random.seed() logging_cfg = cls.LOGGING_CFG if "%s" in logging_cfg: logging_cfg = logging_cfg % (cron_cfg if "--cron" in sys.argv[1:] else "scripts",) logging_cfg = os.path.expanduser(log...
[ "def", "setup", "(", "cls", ",", "cron_cfg", "=", "\"cron\"", ")", ":", "random", ".", "seed", "(", ")", "logging_cfg", "=", "cls", ".", "LOGGING_CFG", "if", "\"%s\"", "in", "logging_cfg", ":", "logging_cfg", "=", "logging_cfg", "%", "(", "cron_cfg", "if...
Set up the runtime environment.
[ "Set", "up", "the", "runtime", "environment", "." ]
python
train
38.125
10gen/mongo-orchestration
mongo_orchestration/sharded_clusters.py
https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/sharded_clusters.py#L275-L298
def router_add(self, params): """add new router (mongos) into existing configuration""" if self.uses_rs_configdb: # Replica set configdb. rs_id = self._configsvrs[0] config_members = ReplicaSets().members(rs_id) configdb = '%s/%s' % ( rs_id...
[ "def", "router_add", "(", "self", ",", "params", ")", ":", "if", "self", ".", "uses_rs_configdb", ":", "# Replica set configdb.", "rs_id", "=", "self", ".", "_configsvrs", "[", "0", "]", "config_members", "=", "ReplicaSets", "(", ")", ".", "members", "(", ...
add new router (mongos) into existing configuration
[ "add", "new", "router", "(", "mongos", ")", "into", "existing", "configuration" ]
python
train
43.75
gijzelaerr/python-snap7
snap7/server.py
https://github.com/gijzelaerr/python-snap7/blob/a6db134c7a3a2ef187b9eca04669221d6fc634c3/snap7/server.py#L63-L69
def create(self): """ create the server. """ logger.info("creating server") self.library.Srv_Create.restype = snap7.snap7types.S7Object self.pointer = snap7.snap7types.S7Object(self.library.Srv_Create())
[ "def", "create", "(", "self", ")", ":", "logger", ".", "info", "(", "\"creating server\"", ")", "self", ".", "library", ".", "Srv_Create", ".", "restype", "=", "snap7", ".", "snap7types", ".", "S7Object", "self", ".", "pointer", "=", "snap7", ".", "snap7...
create the server.
[ "create", "the", "server", "." ]
python
train
35
bitesofcode/projexui
projexui/widgets/xorbtreewidget/xorbtreewidget.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbtreewidget.py#L616-L624
def autoExpand(self, level=None): """ Returns whether or not to expand for the inputed level. :param level | <int> || None :return <bool> """ return self._autoExpand.get(level, self._autoExpand.get(None, False))
[ "def", "autoExpand", "(", "self", ",", "level", "=", "None", ")", ":", "return", "self", ".", "_autoExpand", ".", "get", "(", "level", ",", "self", ".", "_autoExpand", ".", "get", "(", "None", ",", "False", ")", ")" ]
Returns whether or not to expand for the inputed level. :param level | <int> || None :return <bool>
[ "Returns", "whether", "or", "not", "to", "expand", "for", "the", "inputed", "level", ".", ":", "param", "level", "|", "<int", ">", "||", "None", ":", "return", "<bool", ">" ]
python
train
31.777778
serhatbolsu/robotframework-appiumlibrary
AppiumLibrary/keywords/_element.py
https://github.com/serhatbolsu/robotframework-appiumlibrary/blob/91c808cf0602af6be8135ac529fa488fded04a85/AppiumLibrary/keywords/_element.py#L52-L62
def click_text(self, text, exact_match=False): """Click text identified by ``text``. By default tries to click first text involves given ``text``, if you would like to click exactly matching text, then set ``exact_match`` to `True`. If there are multiple use of ``text`` and you ...
[ "def", "click_text", "(", "self", ",", "text", ",", "exact_match", "=", "False", ")", ":", "self", ".", "_element_find_by_text", "(", "text", ",", "exact_match", ")", ".", "click", "(", ")" ]
Click text identified by ``text``. By default tries to click first text involves given ``text``, if you would like to click exactly matching text, then set ``exact_match`` to `True`. If there are multiple use of ``text`` and you do not want first one, use `locator` with `Get Web...
[ "Click", "text", "identified", "by", "text", ".", "By", "default", "tries", "to", "click", "first", "text", "involves", "given", "text", "if", "you", "would", "like", "to", "click", "exactly", "matching", "text", "then", "set", "exact_match", "to", "True", ...
python
train
42.272727
F5Networks/f5-common-python
f5/bigip/tm/gtm/topology.py
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/gtm/topology.py#L149-L153
def exists(self, **kwargs): """Providing a partition is not necessary on topology; causes errors""" kwargs.pop('partition', None) kwargs['transform_name'] = True return self._exists(**kwargs)
[ "def", "exists", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "pop", "(", "'partition'", ",", "None", ")", "kwargs", "[", "'transform_name'", "]", "=", "True", "return", "self", ".", "_exists", "(", "*", "*", "kwargs", ")" ]
Providing a partition is not necessary on topology; causes errors
[ "Providing", "a", "partition", "is", "not", "necessary", "on", "topology", ";", "causes", "errors" ]
python
train
43.8
PSPC-SPAC-buyandsell/von_anchor
von_anchor/wallet/manager.py
https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/wallet/manager.py#L297-L336
async def reset(self, von_wallet: Wallet, seed: str = None) -> Wallet: """ Close and delete (open) VON anchor wallet and then create, open, and return replacement on current link secret. Note that this operation effectively destroys private keys for keyed data structures such as...
[ "async", "def", "reset", "(", "self", ",", "von_wallet", ":", "Wallet", ",", "seed", ":", "str", "=", "None", ")", "->", "Wallet", ":", "LOGGER", ".", "debug", "(", "'WalletManager.reset >>> von_wallet %s'", ",", "von_wallet", ")", "if", "not", "von_wallet",...
Close and delete (open) VON anchor wallet and then create, open, and return replacement on current link secret. Note that this operation effectively destroys private keys for keyed data structures such as credential offers or credential definitions. Raise WalletState if the wallet is c...
[ "Close", "and", "delete", "(", "open", ")", "VON", "anchor", "wallet", "and", "then", "create", "open", "and", "return", "replacement", "on", "current", "link", "secret", "." ]
python
train
38.5
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L53-L64
def get_model_details(self, model_name): """Get details of the specified model from CloudML Service. Args: model_name: the name of the model. It can be a model full name ("projects/[project_id]/models/[model_name]") or just [model_name]. Returns: a dictionary of the model details. """...
[ "def", "get_model_details", "(", "self", ",", "model_name", ")", ":", "full_name", "=", "model_name", "if", "not", "model_name", ".", "startswith", "(", "'projects/'", ")", ":", "full_name", "=", "(", "'projects/%s/models/%s'", "%", "(", "self", ".", "_project...
Get details of the specified model from CloudML Service. Args: model_name: the name of the model. It can be a model full name ("projects/[project_id]/models/[model_name]") or just [model_name]. Returns: a dictionary of the model details.
[ "Get", "details", "of", "the", "specified", "model", "from", "CloudML", "Service", "." ]
python
train
44.25
grampajoe/pymosh
pymosh/avi.py
https://github.com/grampajoe/pymosh/blob/2a17a0271fda939528edc31572940d3b676f8a47/pymosh/avi.py#L83-L87
def rebuild(self): """Rebuild RIFF tree and index from streams.""" movi = self.riff.find('LIST', 'movi') movi.chunks = self.combine_streams() self.rebuild_index()
[ "def", "rebuild", "(", "self", ")", ":", "movi", "=", "self", ".", "riff", ".", "find", "(", "'LIST'", ",", "'movi'", ")", "movi", ".", "chunks", "=", "self", ".", "combine_streams", "(", ")", "self", ".", "rebuild_index", "(", ")" ]
Rebuild RIFF tree and index from streams.
[ "Rebuild", "RIFF", "tree", "and", "index", "from", "streams", "." ]
python
train
38
brechtm/rinohtype
src/rinoh/backend/pdf/xobject/purepng.py
https://github.com/brechtm/rinohtype/blob/40a63c4e5ad7550f62b6860f1812cb67cafb9dc7/src/rinoh/backend/pdf/xobject/purepng.py#L2893-L2922
def asRGB(self): """ Return image as RGB pixels. RGB colour images are passed through unchanged; greyscales are expanded into RGB triplets (there is a small speed overhead for doing this). An alpha channel in the source image will raise an exception. The retur...
[ "def", "asRGB", "(", "self", ")", ":", "width", ",", "height", ",", "pixels", ",", "meta", "=", "self", ".", "asDirect", "(", ")", "if", "meta", "[", "'alpha'", "]", ":", "raise", "Error", "(", "\"will not convert image with alpha channel to RGB\"", ")", "...
Return image as RGB pixels. RGB colour images are passed through unchanged; greyscales are expanded into RGB triplets (there is a small speed overhead for doing this). An alpha channel in the source image will raise an exception. The return values are as for the :meth:`read` ...
[ "Return", "image", "as", "RGB", "pixels", "." ]
python
train
36.466667
carpedm20/fbchat
fbchat/_client.py
https://github.com/carpedm20/fbchat/blob/f480d68b5773473e6daba7f66075ee30e8d737a8/fbchat/_client.py#L2307-L2317
def markAsSpam(self, thread_id=None): """ Mark a thread as spam and delete it :param thread_id: User/Group ID to mark as spam. See :ref:`intro_threads` :return: Whether the request was successful :raises: FBchatException if request failed """ thread_id, thread_ty...
[ "def", "markAsSpam", "(", "self", ",", "thread_id", "=", "None", ")", ":", "thread_id", ",", "thread_type", "=", "self", ".", "_getThread", "(", "thread_id", ",", "None", ")", "r", "=", "self", ".", "_post", "(", "self", ".", "req_url", ".", "MARK_SPAM...
Mark a thread as spam and delete it :param thread_id: User/Group ID to mark as spam. See :ref:`intro_threads` :return: Whether the request was successful :raises: FBchatException if request failed
[ "Mark", "a", "thread", "as", "spam", "and", "delete", "it" ]
python
train
39.363636
crossbario/txaio
txaio/aio.py
https://github.com/crossbario/txaio/blob/29c77ff1210cabd4cc03f16f34672612e7eef704/txaio/aio.py#L495-L505
def create_failure(self, exception=None): """ This returns an object implementing IFailedFuture. If exception is None (the default) we MUST be called within an "except" block (such that sys.exc_info() returns useful information). """ if exception: ret...
[ "def", "create_failure", "(", "self", ",", "exception", "=", "None", ")", ":", "if", "exception", ":", "return", "FailedFuture", "(", "type", "(", "exception", ")", ",", "exception", ",", "None", ")", "return", "FailedFuture", "(", "*", "sys", ".", "exc_...
This returns an object implementing IFailedFuture. If exception is None (the default) we MUST be called within an "except" block (such that sys.exc_info() returns useful information).
[ "This", "returns", "an", "object", "implementing", "IFailedFuture", "." ]
python
train
36.818182
StackStorm/pybind
pybind/nos/v6_0_2f/support/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/nos/v6_0_2f/support/__init__.py#L97-L118
def _set_autoupload_param(self, v, load=False): """ Setter method for autoupload_param, mapped from YANG variable /support/autoupload_param (container) If this variable is read-only (config: false) in the source YANG file, then _set_autoupload_param is considered as a private method. Backends lookin...
[ "def", "_set_autoupload_param", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
Setter method for autoupload_param, mapped from YANG variable /support/autoupload_param (container) If this variable is read-only (config: false) in the source YANG file, then _set_autoupload_param is considered as a private method. Backends looking to populate this variable should do so via calling thi...
[ "Setter", "method", "for", "autoupload_param", "mapped", "from", "YANG", "variable", "/", "support", "/", "autoupload_param", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source",...
python
train
90.727273
pycontribs/jira
jira/client.py
https://github.com/pycontribs/jira/blob/397db5d78441ed6a680a9b7db4c62030ade1fd8a/jira/client.py#L552-L565
def _check_update_(self): """Check if the current version of the library is outdated.""" try: data = requests.get("https://pypi.python.org/pypi/jira/json", timeout=2.001).json() released_version = data['info']['version'] if parse_version(released_version) > parse_ver...
[ "def", "_check_update_", "(", "self", ")", ":", "try", ":", "data", "=", "requests", ".", "get", "(", "\"https://pypi.python.org/pypi/jira/json\"", ",", "timeout", "=", "2.001", ")", ".", "json", "(", ")", "released_version", "=", "data", "[", "'info'", "]",...
Check if the current version of the library is outdated.
[ "Check", "if", "the", "current", "version", "of", "the", "library", "is", "outdated", "." ]
python
train
48.714286
helixyte/everest
everest/views/base.py
https://github.com/helixyte/everest/blob/70c9b93c3061db5cb62428349d18b8fb8566411b/everest/views/base.py#L244-L262
def _get_result(self, resource): """ Converts the given resource to a result to be returned from the view. Unless a custom renderer is employed, this will involve creating a representer and using it to convert the resource to a string. :param resource: Resource to convert. ...
[ "def", "_get_result", "(", "self", ",", "resource", ")", ":", "if", "self", ".", "_convert_response", ":", "self", ".", "_update_response_body", "(", "resource", ")", "result", "=", "self", ".", "request", ".", "response", "else", ":", "result", "=", "dict...
Converts the given resource to a result to be returned from the view. Unless a custom renderer is employed, this will involve creating a representer and using it to convert the resource to a string. :param resource: Resource to convert. :type resource: Object implementing :cla...
[ "Converts", "the", "given", "resource", "to", "a", "result", "to", "be", "returned", "from", "the", "view", ".", "Unless", "a", "custom", "renderer", "is", "employed", "this", "will", "involve", "creating", "a", "representer", "and", "using", "it", "to", "...
python
train
42.210526
tradenity/python-sdk
tradenity/resources/measurement_settings.py
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/measurement_settings.py#L55-L69
def weight_unit(self, weight_unit): """Sets the weight_unit of this MeasurementSettings. :param weight_unit: The weight_unit of this MeasurementSettings. :type: str """ allowed_values = ["pound", "kilogram"] # noqa: E501 if weight_unit is not None and weight_unit not i...
[ "def", "weight_unit", "(", "self", ",", "weight_unit", ")", ":", "allowed_values", "=", "[", "\"pound\"", ",", "\"kilogram\"", "]", "# noqa: E501", "if", "weight_unit", "is", "not", "None", "and", "weight_unit", "not", "in", "allowed_values", ":", "raise", "Va...
Sets the weight_unit of this MeasurementSettings. :param weight_unit: The weight_unit of this MeasurementSettings. :type: str
[ "Sets", "the", "weight_unit", "of", "this", "MeasurementSettings", "." ]
python
train
36.733333
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L25105-L25124
def notify3_d_event(self, type_p, data): """Notifies framebuffer about 3D backend event. in type_p of type int event type. Currently only VBOX3D_NOTIFY_EVENT_TYPE_VISIBLE_3DDATA is supported. in data of type str event-specific data, depends on the supplied event type ...
[ "def", "notify3_d_event", "(", "self", ",", "type_p", ",", "data", ")", ":", "if", "not", "isinstance", "(", "type_p", ",", "baseinteger", ")", ":", "raise", "TypeError", "(", "\"type_p can only be an instance of type baseinteger\"", ")", "if", "not", "isinstance"...
Notifies framebuffer about 3D backend event. in type_p of type int event type. Currently only VBOX3D_NOTIFY_EVENT_TYPE_VISIBLE_3DDATA is supported. in data of type str event-specific data, depends on the supplied event type
[ "Notifies", "framebuffer", "about", "3D", "backend", "event", "." ]
python
train
40.75
wandb/client
wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py
https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/key_binding/bindings/named_commands.py#L95-L104
def backward_word(event): """ Move back to the start of the current or previous word. Words are composed of letters and digits. """ buff = event.current_buffer pos = buff.document.find_previous_word_beginning(count=event.arg) if pos: buff.cursor_position += pos
[ "def", "backward_word", "(", "event", ")", ":", "buff", "=", "event", ".", "current_buffer", "pos", "=", "buff", ".", "document", ".", "find_previous_word_beginning", "(", "count", "=", "event", ".", "arg", ")", "if", "pos", ":", "buff", ".", "cursor_posit...
Move back to the start of the current or previous word. Words are composed of letters and digits.
[ "Move", "back", "to", "the", "start", "of", "the", "current", "or", "previous", "word", ".", "Words", "are", "composed", "of", "letters", "and", "digits", "." ]
python
train
28.9
data61/clkhash
clkhash/bloomfilter.py
https://github.com/data61/clkhash/blob/ec6398d6708a063de83f7c3d6286587bff8e7121/clkhash/bloomfilter.py#L332-L348
def stream_bloom_filters(dataset, # type: Iterable[Sequence[Text]] keys, # type: Sequence[Sequence[bytes]] schema # type: Schema ): # type: (...) -> Iterable[Tuple[bitarray, Text, int]] """ Compute composite Bloom filters (CLKs) ...
[ "def", "stream_bloom_filters", "(", "dataset", ",", "# type: Iterable[Sequence[Text]]", "keys", ",", "# type: Sequence[Sequence[bytes]]", "schema", "# type: Schema", ")", ":", "# type: (...) -> Iterable[Tuple[bitarray, Text, int]]", "tokenizers", "=", "[", "tokenizer", ".", "ge...
Compute composite Bloom filters (CLKs) for every record in an iterable dataset. :param dataset: An iterable of indexable records. :param schema: An instantiated Schema instance :param keys: A tuple of two lists of secret keys used in the HMAC. :return: Generator yielding bloom f...
[ "Compute", "composite", "Bloom", "filters", "(", "CLKs", ")", "for", "every", "record", "in", "an", "iterable", "dataset", "." ]
python
train
48
aleju/imgaug
imgaug/augmentables/polys.py
https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/polys.py#L780-L803
def to_line_string(self, closed=True): """ Convert this polygon's `exterior` to a ``LineString`` instance. Parameters ---------- closed : bool, optional Whether to close the line string, i.e. to add the first point of the `exterior` also as the last point...
[ "def", "to_line_string", "(", "self", ",", "closed", "=", "True", ")", ":", "from", "imgaug", ".", "augmentables", ".", "lines", "import", "LineString", "if", "not", "closed", "or", "len", "(", "self", ".", "exterior", ")", "<=", "1", ":", "return", "L...
Convert this polygon's `exterior` to a ``LineString`` instance. Parameters ---------- closed : bool, optional Whether to close the line string, i.e. to add the first point of the `exterior` also as the last point at the end of the line string. This has no eff...
[ "Convert", "this", "polygon", "s", "exterior", "to", "a", "LineString", "instance", "." ]
python
valid
36.208333
hubo1016/vlcp
vlcp/service/sdn/dhcpserver.py
https://github.com/hubo1016/vlcp/blob/239055229ec93a99cc7e15208075724ccf543bd1/vlcp/service/sdn/dhcpserver.py#L57-L266
async def _dhcp_handler(self): """ Mini DHCP server, respond DHCP packets from OpenFlow """ conn = self._connection ofdef = self._connection.openflowdef l3 = self._parent._gettableindex('l3input', self._connection.protocol.vhost) dhcp_packet_matcher = OpenflowAsyn...
[ "async", "def", "_dhcp_handler", "(", "self", ")", ":", "conn", "=", "self", ".", "_connection", "ofdef", "=", "self", ".", "_connection", ".", "openflowdef", "l3", "=", "self", ".", "_parent", ".", "_gettableindex", "(", "'l3input'", ",", "self", ".", "...
Mini DHCP server, respond DHCP packets from OpenFlow
[ "Mini", "DHCP", "server", "respond", "DHCP", "packets", "from", "OpenFlow" ]
python
train
63.833333
MaterialsDataInfrastructureConsortium/CommonMetadata
matmeta/payload_metaclass.py
https://github.com/MaterialsDataInfrastructureConsortium/CommonMetadata/blob/282d67fdd20f8535c108a7651348633aabdfa82b/matmeta/payload_metaclass.py#L58-L87
def _validate_inputs(actual_inputs, required_inputs, keypath=None): """ Validate inputs. Raise exception if something is missing. args: actual_inputs: the object/dictionary passed to a subclass of PublishablePayload required_inputs: the object/dictionary containing key...
[ "def", "_validate_inputs", "(", "actual_inputs", ",", "required_inputs", ",", "keypath", "=", "None", ")", ":", "actual_keys", "=", "set", "(", "actual_inputs", ".", "keys", "(", ")", ")", "required_keys", "=", "set", "(", "required_inputs", ".", "keys", "("...
Validate inputs. Raise exception if something is missing. args: actual_inputs: the object/dictionary passed to a subclass of PublishablePayload required_inputs: the object/dictionary containing keys (and subkeys) for required fields. (See get_common_payload_templat...
[ "Validate", "inputs", ".", "Raise", "exception", "if", "something", "is", "missing", ".", "args", ":", "actual_inputs", ":", "the", "object", "/", "dictionary", "passed", "to", "a", "subclass", "of", "PublishablePayload", "required_inputs", ":", "the", "object",...
python
train
45.8
edx/opaque-keys
opaque_keys/edx/locator.py
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L1122-L1126
def for_version(self, version_guid): """ Return a UsageLocator for the same block in a different version of the library. """ return self.replace(library_key=self.library_key.for_version(version_guid))
[ "def", "for_version", "(", "self", ",", "version_guid", ")", ":", "return", "self", ".", "replace", "(", "library_key", "=", "self", ".", "library_key", ".", "for_version", "(", "version_guid", ")", ")" ]
Return a UsageLocator for the same block in a different version of the library.
[ "Return", "a", "UsageLocator", "for", "the", "same", "block", "in", "a", "different", "version", "of", "the", "library", "." ]
python
train
45.6
soravux/scoop
scoop/_control.py
https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_control.py#L98-L105
def init_debug(): """Initialise debug_stats and QueueLength (this is not a reset)""" global debug_stats global QueueLength if debug_stats is None: list_defaultdict = partial(defaultdict, list) debug_stats = defaultdict(list_defaultdict) QueueLength = []
[ "def", "init_debug", "(", ")", ":", "global", "debug_stats", "global", "QueueLength", "if", "debug_stats", "is", "None", ":", "list_defaultdict", "=", "partial", "(", "defaultdict", ",", "list", ")", "debug_stats", "=", "defaultdict", "(", "list_defaultdict", ")...
Initialise debug_stats and QueueLength (this is not a reset)
[ "Initialise", "debug_stats", "and", "QueueLength", "(", "this", "is", "not", "a", "reset", ")" ]
python
train
35.75
ajbosco/dag-factory
dagfactory/dagfactory.py
https://github.com/ajbosco/dag-factory/blob/cc7cfe74e62f82859fe38d527e95311a2805723b/dagfactory/dagfactory.py#L30-L40
def _load_config(config_filepath: str) -> Dict[str, Any]: """ Loads YAML config file to dictionary :returns: dict from YAML config file """ try: config: Dict[str, Any] = yaml.load(stream=open(config_filepath, "r")) except Exception as e: raise Exc...
[ "def", "_load_config", "(", "config_filepath", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "try", ":", "config", ":", "Dict", "[", "str", ",", "Any", "]", "=", "yaml", ".", "load", "(", "stream", "=", "open", "(", "config_filep...
Loads YAML config file to dictionary :returns: dict from YAML config file
[ "Loads", "YAML", "config", "file", "to", "dictionary" ]
python
train
34.909091
dangunter/smoqe
smoqe/query.py
https://github.com/dangunter/smoqe/blob/70aa8ec1e9df875b9d21c71cbded95c595fe2aad/smoqe/query.py#L684-L698
def add_clause(self, clause): """Add a new clause to the existing query. :param clause: The clause to add :type clause: MongoClause :return: None """ if clause.query_loc == MongoClause.LOC_MAIN: self._main.append(clause) elif clause.query_loc == Mongo...
[ "def", "add_clause", "(", "self", ",", "clause", ")", ":", "if", "clause", ".", "query_loc", "==", "MongoClause", ".", "LOC_MAIN", ":", "self", ".", "_main", ".", "append", "(", "clause", ")", "elif", "clause", ".", "query_loc", "==", "MongoClause", ".",...
Add a new clause to the existing query. :param clause: The clause to add :type clause: MongoClause :return: None
[ "Add", "a", "new", "clause", "to", "the", "existing", "query", "." ]
python
train
36.933333
vmalyi/adb_android
adb_android/adb_android.py
https://github.com/vmalyi/adb_android/blob/de53dc54f27b14dc8c2ae64b136a60a59e1a1cb1/adb_android/adb_android.py#L178-L202
def _exec_command(adb_cmd): """ Format adb command and execute it in shell :param adb_cmd: list adb command to execute :return: string '0' and shell command output if successful, otherwise raise CalledProcessError exception and return error code """ t = tempfile.TemporaryFile() final_adb...
[ "def", "_exec_command", "(", "adb_cmd", ")", ":", "t", "=", "tempfile", ".", "TemporaryFile", "(", ")", "final_adb_cmd", "=", "[", "]", "for", "e", "in", "adb_cmd", ":", "if", "e", "!=", "''", ":", "# avoid items with empty string...", "final_adb_cmd", ".", ...
Format adb command and execute it in shell :param adb_cmd: list adb command to execute :return: string '0' and shell command output if successful, otherwise raise CalledProcessError exception and return error code
[ "Format", "adb", "command", "and", "execute", "it", "in", "shell", ":", "param", "adb_cmd", ":", "list", "adb", "command", "to", "execute", ":", "return", ":", "string", "0", "and", "shell", "command", "output", "if", "successful", "otherwise", "raise", "C...
python
train
32.24
angr/angr
angr/state_plugins/heap/heap_base.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/heap/heap_base.py#L99-L108
def _realloc(self, ptr, size): """ Handler for any libc `realloc` SimProcedure call. If the heap has faithful support for `realloc`, it ought to be implemented in a `realloc` function (as opposed to the `_realloc` function). :param ptr: the location in memory to be reallocated :...
[ "def", "_realloc", "(", "self", ",", "ptr", ",", "size", ")", ":", "raise", "NotImplementedError", "(", "\"%s not implemented for %s\"", "%", "(", "self", ".", "_realloc", ".", "__func__", ".", "__name__", ",", "self", ".", "__class__", ".", "__name__", ")",...
Handler for any libc `realloc` SimProcedure call. If the heap has faithful support for `realloc`, it ought to be implemented in a `realloc` function (as opposed to the `_realloc` function). :param ptr: the location in memory to be reallocated :param size: the new size desired for the allocation
[ "Handler", "for", "any", "libc", "realloc", "SimProcedure", "call", ".", "If", "the", "heap", "has", "faithful", "support", "for", "realloc", "it", "ought", "to", "be", "implemented", "in", "a", "realloc", "function", "(", "as", "opposed", "to", "the", "_r...
python
train
56.3
LLNL/certipy
certipy/certipy.py
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L393-L412
def remove_record(self, common_name): """Delete the record associated with this common name""" bundle = self.get_files(common_name) num_signees = len(Counter(bundle.record['signees'])) if bundle.is_ca() and num_signees > 0: raise CertificateAuthorityInUseError( ...
[ "def", "remove_record", "(", "self", ",", "common_name", ")", ":", "bundle", "=", "self", ".", "get_files", "(", "common_name", ")", "num_signees", "=", "len", "(", "Counter", "(", "bundle", ".", "record", "[", "'signees'", "]", ")", ")", "if", "bundle",...
Delete the record associated with this common name
[ "Delete", "the", "record", "associated", "with", "this", "common", "name" ]
python
train
38.7
a1ezzz/wasp-general
wasp_general/task/thread.py
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/thread.py#L421-L427
def thread_stopped(self): """ :meth:`.WThreadTask._polling_iteration` implementation """ if self.__current_task is not None: task = self.__task_chain[self.__current_task] task.stop() self.__current_task = None
[ "def", "thread_stopped", "(", "self", ")", ":", "if", "self", ".", "__current_task", "is", "not", "None", ":", "task", "=", "self", ".", "__task_chain", "[", "self", ".", "__current_task", "]", "task", ".", "stop", "(", ")", "self", ".", "__current_task"...
:meth:`.WThreadTask._polling_iteration` implementation
[ ":", "meth", ":", ".", "WThreadTask", ".", "_polling_iteration", "implementation" ]
python
train
31.142857
census-instrumentation/opencensus-python
contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-httplib/opencensus/ext/httplib/trace.py#L58-L92
def wrap_httplib_request(request_func): """Wrap the httplib request function to trace. Create a new span and update and close the span in the response later. """ def call(self, method, url, body, headers, *args, **kwargs): _tracer = execution_context.get_opencensus_tracer() blacklist_ho...
[ "def", "wrap_httplib_request", "(", "request_func", ")", ":", "def", "call", "(", "self", ",", "method", ",", "url", ",", "body", ",", "headers", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_tracer", "=", "execution_context", ".", "get_opencens...
Wrap the httplib request function to trace. Create a new span and update and close the span in the response later.
[ "Wrap", "the", "httplib", "request", "function", "to", "trace", ".", "Create", "a", "new", "span", "and", "update", "and", "close", "the", "span", "in", "the", "response", "later", "." ]
python
train
42
nerdvegas/rez
src/rez/utils/filesystem.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L126-L154
def get_existing_path(path, topmost_path=None): """Get the longest parent path in `path` that exists. If `path` exists, it is returned. Args: path (str): Path to test topmost_path (str): Do not test this path or above Returns: str: Existing path, or None if no path was found. ...
[ "def", "get_existing_path", "(", "path", ",", "topmost_path", "=", "None", ")", ":", "prev_path", "=", "None", "if", "topmost_path", ":", "topmost_path", "=", "os", ".", "path", ".", "normpath", "(", "topmost_path", ")", "while", "True", ":", "if", "os", ...
Get the longest parent path in `path` that exists. If `path` exists, it is returned. Args: path (str): Path to test topmost_path (str): Do not test this path or above Returns: str: Existing path, or None if no path was found.
[ "Get", "the", "longest", "parent", "path", "in", "path", "that", "exists", "." ]
python
train
23.482759
saltstack/salt
salt/output/json_out.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/json_out.py#L56-L92
def output(data, **kwargs): # pylint: disable=unused-argument ''' Print the output data in JSON ''' try: if 'output_indent' not in __opts__: return salt.utils.json.dumps(data, default=repr, indent=4) indent = __opts__.get('output_indent') sort_keys = False ...
[ "def", "output", "(", "data", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "try", ":", "if", "'output_indent'", "not", "in", "__opts__", ":", "return", "salt", ".", "utils", ".", "json", ".", "dumps", "(", "data", ",", "default",...
Print the output data in JSON
[ "Print", "the", "output", "data", "in", "JSON" ]
python
train
29.432432
tensorflow/skflow
scripts/docs/docs.py
https://github.com/tensorflow/skflow/blob/f8da498a1abb7562f57dfc7010941578103061b6/scripts/docs/docs.py#L225-L246
def get_class_members(self, cls_name, cls): """Returns the list of class members to document in `cls`. This function filters the class member to ONLY return those defined by the class. It drops the inherited ones. Args: cls_name: Qualified name of `cls`. cls: An inspect object of type 'cl...
[ "def", "get_class_members", "(", "self", ",", "cls_name", ",", "cls", ")", ":", "for", "name", ",", "member", "in", "inspect", ".", "getmembers", "(", "cls", ")", ":", "# Only show methods and properties presently. In Python 3,", "# methods register as isfunction.", ...
Returns the list of class members to document in `cls`. This function filters the class member to ONLY return those defined by the class. It drops the inherited ones. Args: cls_name: Qualified name of `cls`. cls: An inspect object of type 'class'. Yields: name, member tuples.
[ "Returns", "the", "list", "of", "class", "members", "to", "document", "in", "cls", "." ]
python
train
37.5
apple/turicreate
deps/src/libxml2-2.9.1/python/libxml2.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L6856-L6865
def RelaxNGSetSchema(self, schema): """Use RelaxNG to validate the document as it is processed. Activation is only possible before the first Read(). if @schema is None, then RelaxNG validation is desactivated. @ The @schema should not be freed until the reader is dealloc...
[ "def", "RelaxNGSetSchema", "(", "self", ",", "schema", ")", ":", "if", "schema", "is", "None", ":", "schema__o", "=", "None", "else", ":", "schema__o", "=", "schema", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlTextReaderRelaxNGSetSchema", "(", "self", "...
Use RelaxNG to validate the document as it is processed. Activation is only possible before the first Read(). if @schema is None, then RelaxNG validation is desactivated. @ The @schema should not be freed until the reader is deallocated or its use has been deactivated.
[ "Use", "RelaxNG", "to", "validate", "the", "document", "as", "it", "is", "processed", ".", "Activation", "is", "only", "possible", "before", "the", "first", "Read", "()", ".", "if" ]
python
train
52.6
d0ugal/python-rfxcom
rfxcom/protocol/temperature.py
https://github.com/d0ugal/python-rfxcom/blob/2eb87f85e5f5a04d00f32f25e0f010edfefbde0d/rfxcom/protocol/temperature.py#L49-L96
def parse(self, data): """Parse a 9 bytes packet in the Temperature format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x2EB2", 'packet_length': 8, ...
[ "def", "parse", "(", "self", ",", "data", ")", ":", "self", ".", "validate_packet", "(", "data", ")", "id_", "=", "self", ".", "dump_hex", "(", "data", "[", "4", ":", "6", "]", ")", "# channel = data[5] TBC", "temperature", "=", "(", "(", "data", "["...
Parse a 9 bytes packet in the Temperature format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x2EB2", 'packet_length': 8, 'packet_type': 80, ...
[ "Parse", "a", "9", "bytes", "packet", "in", "the", "Temperature", "format", "and", "return", "a", "dictionary", "containing", "the", "data", "extracted", ".", "An", "example", "of", "a", "return", "value", "would", "be", ":" ]
python
train
28.645833
ToucanToco/toucan-data-sdk
toucan_data_sdk/utils/postprocess/text.py
https://github.com/ToucanToco/toucan-data-sdk/blob/c3ca874e1b64f4bdcc2edda750a72d45d1561d8a/toucan_data_sdk/utils/postprocess/text.py#L516-L541
def repeat( df, column: str, *, times: int, new_column: str = None ): """ Duplicate each string in `column` by indicated number of time See [pandas doc]( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.repeat.html) for more information...
[ "def", "repeat", "(", "df", ",", "column", ":", "str", ",", "*", ",", "times", ":", "int", ",", "new_column", ":", "str", "=", "None", ")", ":", "new_column", "=", "new_column", "or", "column", "df", ".", "loc", "[", ":", ",", "new_column", "]", ...
Duplicate each string in `column` by indicated number of time See [pandas doc]( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.repeat.html) for more information --- ### Parameters *mandatory :* - `column` (*str*): the column - `times` (*int*): times to repeat...
[ "Duplicate", "each", "string", "in", "column", "by", "indicated", "number", "of", "time", "See", "[", "pandas", "doc", "]", "(", "https", ":", "//", "pandas", ".", "pydata", ".", "org", "/", "pandas", "-", "docs", "/", "stable", "/", "reference", "/", ...
python
test
25
rigetti/pyquil
pyquil/quil.py
https://github.com/rigetti/pyquil/blob/ec98e453084b0037d69d8c3245f6822a5422593d/pyquil/quil.py#L347-L376
def while_do(self, classical_reg, q_program): """ While a classical register at index classical_reg is 1, loop q_program Equivalent to the following construction: .. code:: WHILE [c]: instr... => LABEL @START JUMP-UNLE...
[ "def", "while_do", "(", "self", ",", "classical_reg", ",", "q_program", ")", ":", "label_start", "=", "LabelPlaceholder", "(", "\"START\"", ")", "label_end", "=", "LabelPlaceholder", "(", "\"END\"", ")", "self", ".", "inst", "(", "JumpTarget", "(", "label_star...
While a classical register at index classical_reg is 1, loop q_program Equivalent to the following construction: .. code:: WHILE [c]: instr... => LABEL @START JUMP-UNLESS @END [c] instr... JUMP @START ...
[ "While", "a", "classical", "register", "at", "index", "classical_reg", "is", "1", "loop", "q_program" ]
python
train
31.4
SpriteLink/NIPAP
nipap/nipap/backend.py
https://github.com/SpriteLink/NIPAP/blob/f96069f11ab952d80b13cab06e0528f2d24b3de9/nipap/nipap/backend.py#L1120-L1126
def _db_install(self, db_name): """ Install nipap database schema """ self._logger.info("Installing NIPAP database schemas into db") self._execute(db_schema.ip_net % (db_name)) self._execute(db_schema.functions) self._execute(db_schema.triggers)
[ "def", "_db_install", "(", "self", ",", "db_name", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Installing NIPAP database schemas into db\"", ")", "self", ".", "_execute", "(", "db_schema", ".", "ip_net", "%", "(", "db_name", ")", ")", "self", ".",...
Install nipap database schema
[ "Install", "nipap", "database", "schema" ]
python
train
41
hydpy-dev/hydpy
hydpy/models/dam/dam_model.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/dam/dam_model.py#L61-L65
def pic_loggedrequiredremoterelease_v2(self): """Update the receiver link sequence.""" log = self.sequences.logs.fastaccess rec = self.sequences.receivers.fastaccess log.loggedrequiredremoterelease[0] = rec.s[0]
[ "def", "pic_loggedrequiredremoterelease_v2", "(", "self", ")", ":", "log", "=", "self", ".", "sequences", ".", "logs", ".", "fastaccess", "rec", "=", "self", ".", "sequences", ".", "receivers", ".", "fastaccess", "log", ".", "loggedrequiredremoterelease", "[", ...
Update the receiver link sequence.
[ "Update", "the", "receiver", "link", "sequence", "." ]
python
train
44.6
rkargon/pixelsorter
pixelsorter/sort.py
https://github.com/rkargon/pixelsorter/blob/0775d1e487fbcb023e411e1818ba3290b0e8665e/pixelsorter/sort.py#L305-L317
def apply_tile_to_image(image, size, tile, tile_size, tile_corner): """ Copies a tile with a given offset onto an image :param image: The image the file is to be copied onto (as a list of (R,G,B) tuples) :param size: The size of the image as a tuple (width, height) :param tile: The tile to be copied...
[ "def", "apply_tile_to_image", "(", "image", ",", "size", ",", "tile", ",", "tile_size", ",", "tile_corner", ")", ":", "for", "y", "in", "range", "(", "tile_size", "[", "1", "]", ")", ":", "for", "x", "in", "range", "(", "tile_size", "[", "0", "]", ...
Copies a tile with a given offset onto an image :param image: The image the file is to be copied onto (as a list of (R,G,B) tuples) :param size: The size of the image as a tuple (width, height) :param tile: The tile to be copied over (as a list of (R,G,B) tuples) :param tile_size: The size of the tile a...
[ "Copies", "a", "tile", "with", "a", "given", "offset", "onto", "an", "image", ":", "param", "image", ":", "The", "image", "the", "file", "is", "to", "be", "copied", "onto", "(", "as", "a", "list", "of", "(", "R", "G", "B", ")", "tuples", ")", ":"...
python
train
59.769231
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/collectionseditor.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/collectionseditor.py#L991-L999
def dropEvent(self, event): """Allow user to drop supported files""" urls = mimedata2url(event.mimeData()) if urls: event.setDropAction(Qt.CopyAction) event.accept() self.sig_files_dropped.emit(urls) else: event.ignore()
[ "def", "dropEvent", "(", "self", ",", "event", ")", ":", "urls", "=", "mimedata2url", "(", "event", ".", "mimeData", "(", ")", ")", "if", "urls", ":", "event", ".", "setDropAction", "(", "Qt", ".", "CopyAction", ")", "event", ".", "accept", "(", ")",...
Allow user to drop supported files
[ "Allow", "user", "to", "drop", "supported", "files" ]
python
train
33.333333
qacafe/cdrouter.py
cdrouter/highlights.py
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/highlights.py#L57-L67
def get(self, id, seq, line): # pylint: disable=invalid-name,redefined-builtin """Get a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. :return: :class:`highlights.Highlight <hig...
[ "def", "get", "(", "self", ",", "id", ",", "seq", ",", "line", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "HighlightSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "get_id", "(", "self", ".", "_base", "(", "id...
Get a highlight. :param id: Result ID as an int. :param seq: TestResult sequence ID as an int. :param line: Line number in TestResult's logfile as an int. :return: :class:`highlights.Highlight <highlights.Highlight>` object
[ "Get", "a", "highlight", "." ]
python
train
44.909091
stefanfoulis/django-sendsms
sendsms/utils.py
https://github.com/stefanfoulis/django-sendsms/blob/375f469789866853253eceba936ebcff98e83c07/sendsms/utils.py#L8-L32
def load_object(import_path): """ Shamelessly stolen from https://github.com/ojii/django-load Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the likes. Import paths should be: "mypackage.mymodule.MyObject". It then imports the module up until the last dot and tries t...
[ "def", "load_object", "(", "import_path", ")", ":", "if", "'.'", "not", "in", "import_path", ":", "raise", "TypeError", "(", "\"'import_path' argument to 'load_object' must \"", "\"contain at least one dot.\"", ")", "module_name", ",", "object_name", "=", "import_path", ...
Shamelessly stolen from https://github.com/ojii/django-load Loads an object from an 'import_path', like in MIDDLEWARE_CLASSES and the likes. Import paths should be: "mypackage.mymodule.MyObject". It then imports the module up until the last dot and tries to get the attribute after that dot fro...
[ "Shamelessly", "stolen", "from", "https", ":", "//", "github", ".", "com", "/", "ojii", "/", "django", "-", "load", "Loads", "an", "object", "from", "an", "import_path", "like", "in", "MIDDLEWARE_CLASSES", "and", "the", "likes", "." ]
python
train
35.64
matthias-k/cyipopt
doc/source/sphinxext/inheritance_diagram.py
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L251-L284
def run_dot(self, args, name, parts=0, urls={}, graph_options={}, node_options={}, edge_options={}): """ Run graphviz 'dot' over this graph, returning whatever 'dot' writes to stdout. *args* will be passed along as commandline arguments. *name* is the name of th...
[ "def", "run_dot", "(", "self", ",", "args", ",", "name", ",", "parts", "=", "0", ",", "urls", "=", "{", "}", ",", "graph_options", "=", "{", "}", ",", "node_options", "=", "{", "}", ",", "edge_options", "=", "{", "}", ")", ":", "try", ":", "dot...
Run graphviz 'dot' over this graph, returning whatever 'dot' writes to stdout. *args* will be passed along as commandline arguments. *name* is the name of the graph *urls* is a dictionary mapping class names to http urls Raises DotException for any of the many os and ...
[ "Run", "graphviz", "dot", "over", "this", "graph", "returning", "whatever", "dot", "writes", "to", "stdout", "." ]
python
train
39.294118
pricingassistant/mrq
mrq/job.py
https://github.com/pricingassistant/mrq/blob/d0a5a34de9cba38afa94fb7c9e17f9b570b79a50/mrq/job.py#L231-L251
def retry(self, queue=None, delay=None, max_retries=None): """ Marks the current job as needing to be retried. Interrupts it. """ max_retries = max_retries if max_retries is None: max_retries = self.max_retries if self.data.get("retry_count", 0) >= max_retries: ...
[ "def", "retry", "(", "self", ",", "queue", "=", "None", ",", "delay", "=", "None", ",", "max_retries", "=", "None", ")", ":", "max_retries", "=", "max_retries", "if", "max_retries", "is", "None", ":", "max_retries", "=", "self", ".", "max_retries", "if",...
Marks the current job as needing to be retried. Interrupts it.
[ "Marks", "the", "current", "job", "as", "needing", "to", "be", "retried", ".", "Interrupts", "it", "." ]
python
train
31.571429
agschwender/pilbox
pilbox/image.py
https://github.com/agschwender/pilbox/blob/8b1d154436fd1b9f9740925549793561c58d4400/pilbox/image.py#L182-L206
def resize(self, width, height, **kwargs): """Resizes the image to the supplied width/height. Returns the instance. Supports the following optional keyword arguments: mode - The resizing mode to use, see Image.MODES filter - The filter to use: see Image.FILTERS background - The ...
[ "def", "resize", "(", "self", ",", "width", ",", "height", ",", "*", "*", "kwargs", ")", ":", "opts", "=", "Image", ".", "_normalize_options", "(", "kwargs", ")", "size", "=", "self", ".", "_get_size", "(", "width", ",", "height", ")", "if", "opts", ...
Resizes the image to the supplied width/height. Returns the instance. Supports the following optional keyword arguments: mode - The resizing mode to use, see Image.MODES filter - The filter to use: see Image.FILTERS background - The hexadecimal background fill color, RGB or ARGB ...
[ "Resizes", "the", "image", "to", "the", "supplied", "width", "/", "height", ".", "Returns", "the", "instance", ".", "Supports", "the", "following", "optional", "keyword", "arguments", ":" ]
python
train
41.88
HewlettPackard/python-hpOneView
hpOneView/resources/servers/enclosures.py
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/servers/enclosures.py#L106-L119
def update_configuration(self, timeout=-1): """ Reapplies the appliance's configuration on the enclosure. This includes running the same configure steps that were performed as part of the enclosure add. Args: timeout: Timeout in seconds. Wait for task completion by default. ...
[ "def", "update_configuration", "(", "self", ",", "timeout", "=", "-", "1", ")", ":", "uri", "=", "\"{}/configuration\"", ".", "format", "(", "self", ".", "data", "[", "'uri'", "]", ")", "return", "self", ".", "update_with_zero_body", "(", "uri", "=", "ur...
Reapplies the appliance's configuration on the enclosure. This includes running the same configure steps that were performed as part of the enclosure add. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneV...
[ "Reapplies", "the", "appliance", "s", "configuration", "on", "the", "enclosure", ".", "This", "includes", "running", "the", "same", "configure", "steps", "that", "were", "performed", "as", "part", "of", "the", "enclosure", "add", "." ]
python
train
42.5
WebarchivCZ/WA-KAT
src/wa_kat/settings.py
https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/settings.py#L39-L47
def _in_conf_dir(filename): """ Put the `filename` to the configuration directory context / path. """ return os.path.join( os.path.dirname(__file__), "templates/conf", filename )
[ "def", "_in_conf_dir", "(", "filename", ")", ":", "return", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"templates/conf\"", ",", "filename", ")" ]
Put the `filename` to the configuration directory context / path.
[ "Put", "the", "filename", "to", "the", "configuration", "directory", "context", "/", "path", "." ]
python
train
23.777778
BerkeleyAutomation/perception
perception/image.py
https://github.com/BerkeleyAutomation/perception/blob/03d9b37dd6b66896cdfe173905c9413c8c3c5df6/perception/image.py#L2612-L2638
def diff_with_target(self, binary_im): """ Creates a color image to visualize the overlap between two images. Nonzero pixels that match in both images are green. Nonzero pixels of this image that aren't in the other image are yellow Nonzero pixels of the other image that aren't in this i...
[ "def", "diff_with_target", "(", "self", ",", "binary_im", ")", ":", "red", "=", "np", ".", "array", "(", "[", "BINARY_IM_MAX_VAL", ",", "0", ",", "0", "]", ")", "yellow", "=", "np", ".", "array", "(", "[", "BINARY_IM_MAX_VAL", ",", "BINARY_IM_MAX_VAL", ...
Creates a color image to visualize the overlap between two images. Nonzero pixels that match in both images are green. Nonzero pixels of this image that aren't in the other image are yellow Nonzero pixels of the other image that aren't in this image are red Parameters ----------...
[ "Creates", "a", "color", "image", "to", "visualize", "the", "overlap", "between", "two", "images", ".", "Nonzero", "pixels", "that", "match", "in", "both", "images", "are", "green", ".", "Nonzero", "pixels", "of", "this", "image", "that", "aren", "t", "in"...
python
train
47.185185
oksome/Tumulus
tumulus/element.py
https://github.com/oksome/Tumulus/blob/20fca0e251d6f1825c33e61a8d497b62a8cbc0da/tumulus/element.py#L62-L77
def plugins(self, deduplicate=False): ''' Returns a flattened list of all plugins used by page components. ''' plugins = [] for c in self.components: if hasattr(c, 'plugins'): plugins += c.plugins() elif isinstance(c, Lib): ...
[ "def", "plugins", "(", "self", ",", "deduplicate", "=", "False", ")", ":", "plugins", "=", "[", "]", "for", "c", "in", "self", ".", "components", ":", "if", "hasattr", "(", "c", ",", "'plugins'", ")", ":", "plugins", "+=", "c", ".", "plugins", "(",...
Returns a flattened list of all plugins used by page components.
[ "Returns", "a", "flattened", "list", "of", "all", "plugins", "used", "by", "page", "components", "." ]
python
train
32.75
ff0000/scarlet
scarlet/assets/models.py
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/assets/models.py#L85-L98
def reset_crops(self): """ Reset all known crops to the default crop. If settings.ASSET_CELERY is specified then the task will be run async """ if self._can_crop(): if settings.CELERY or settings.USE_CELERY_DECORATOR: # this means that we are...
[ "def", "reset_crops", "(", "self", ")", ":", "if", "self", ".", "_can_crop", "(", ")", ":", "if", "settings", ".", "CELERY", "or", "settings", ".", "USE_CELERY_DECORATOR", ":", "# this means that we are using celery", "tasks", ".", "reset_crops", ".", "apply_asy...
Reset all known crops to the default crop. If settings.ASSET_CELERY is specified then the task will be run async
[ "Reset", "all", "known", "crops", "to", "the", "default", "crop", "." ]
python
train
33.214286
h2non/pook
pook/mock.py
https://github.com/h2non/pook/blob/e64094e41e4d89d98d2d29af7608ef27dc50cf19/pook/mock.py#L188-L202
def header(self, name, value): """ Defines a URL path to match. Only call this method if the URL has no path already defined. Arguments: path (str): URL path value to match. E.g: ``/api/users``. Returns: self: current Mock instance. """ ...
[ "def", "header", "(", "self", ",", "name", ",", "value", ")", ":", "headers", "=", "{", "name", ":", "value", "}", "self", ".", "_request", ".", "headers", "=", "headers", "self", ".", "add_matcher", "(", "matcher", "(", "'HeadersMatcher'", ",", "heade...
Defines a URL path to match. Only call this method if the URL has no path already defined. Arguments: path (str): URL path value to match. E.g: ``/api/users``. Returns: self: current Mock instance.
[ "Defines", "a", "URL", "path", "to", "match", "." ]
python
test
28.666667
nickmckay/LiPD-utilities
Python/lipd/fetch_doi.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/fetch_doi.py#L165-L180
def clean_doi(doi_string): """ Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215) :param str doi_string: Raw DOI string value from input file. Often not properly formatted. :return list: DOI ids. May contain 0, 1, or multiple ids. """ regex = re.compile(r'\b(10[.][0-9]{3,}...
[ "def", "clean_doi", "(", "doi_string", ")", ":", "regex", "=", "re", ".", "compile", "(", "r'\\b(10[.][0-9]{3,}(?:[.][0-9]+)*/(?:(?![\"&\\'<>,])\\S)+)\\b'", ")", "try", ":", "# Returns a list of matching strings", "m", "=", "re", ".", "findall", "(", "regex", ",", "...
Use regex to extract all DOI ids from string (i.e. 10.1029/2005pa001215) :param str doi_string: Raw DOI string value from input file. Often not properly formatted. :return list: DOI ids. May contain 0, 1, or multiple ids.
[ "Use", "regex", "to", "extract", "all", "DOI", "ids", "from", "string", "(", "i", ".", "e", ".", "10", ".", "1029", "/", "2005pa001215", ")" ]
python
train
38.875
ssalentin/plip
plip/modules/preparation.py
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/preparation.py#L906-L945
def find_charged(self, mol): """Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and glutamic acid.""" data = namedtuple('pcharge', 'atoms atoms_orig_idx type center restype resnr reschain') a_set = [] # Iterate through all residue, exclude those in c...
[ "def", "find_charged", "(", "self", ",", "mol", ")", ":", "data", "=", "namedtuple", "(", "'pcharge'", ",", "'atoms atoms_orig_idx type center restype resnr reschain'", ")", "a_set", "=", "[", "]", "# Iterate through all residue, exclude those in chains defined as peptides", ...
Looks for positive charges in arginine, histidine or lysine, for negative in aspartic and glutamic acid.
[ "Looks", "for", "positive", "charges", "in", "arginine", "histidine", "or", "lysine", "for", "negative", "in", "aspartic", "and", "glutamic", "acid", "." ]
python
train
66.55
idlesign/django-sitetree
sitetree/sitetreeapp.py
https://github.com/idlesign/django-sitetree/blob/61de4608e6e415247c75fe8691027d7c4ed0d1e7/sitetree/sitetreeapp.py#L1055-L1070
def get_ancestor_item(self, tree_alias, base_item): """Climbs up the site tree to resolve root item for chosen one. :param str|unicode tree_alias: :param TreeItemBase base_item: :rtype: TreeItemBase """ parent = None if hasattr(base_item, 'parent') and base_item...
[ "def", "get_ancestor_item", "(", "self", ",", "tree_alias", ",", "base_item", ")", ":", "parent", "=", "None", "if", "hasattr", "(", "base_item", ",", "'parent'", ")", "and", "base_item", ".", "parent", "is", "not", "None", ":", "parent", "=", "self", "....
Climbs up the site tree to resolve root item for chosen one. :param str|unicode tree_alias: :param TreeItemBase base_item: :rtype: TreeItemBase
[ "Climbs", "up", "the", "site", "tree", "to", "resolve", "root", "item", "for", "chosen", "one", "." ]
python
test
32.1875
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/node.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/node.py#L525-L570
def node_path(self, node): """Return two lists describing the path from this node to another Parameters ---------- node : instance of Node The other node. Returns ------- p1 : list First path (see below). p2 : list Sec...
[ "def", "node_path", "(", "self", ",", "node", ")", ":", "p1", "=", "self", ".", "parent_chain", "(", ")", "p2", "=", "node", ".", "parent_chain", "(", ")", "cp", "=", "None", "for", "p", "in", "p1", ":", "if", "p", "in", "p2", ":", "cp", "=", ...
Return two lists describing the path from this node to another Parameters ---------- node : instance of Node The other node. Returns ------- p1 : list First path (see below). p2 : list Second path (see below). Notes ...
[ "Return", "two", "lists", "describing", "the", "path", "from", "this", "node", "to", "another" ]
python
train
27.456522
sepandhaghighi/pycm
pycm/pycm_util.py
https://github.com/sepandhaghighi/pycm/blob/cb03258afd6a821d10acba73c965aaac174bedcd/pycm/pycm_util.py#L35-L56
def rounder(input_number, digit=5): """ Round input number and convert to str. :param input_number: input number :type input_number : anything :param digit: scale (the number of digits to the right of the decimal point in a number.) :type digit : int :return: round number as str """ ...
[ "def", "rounder", "(", "input_number", ",", "digit", "=", "5", ")", ":", "if", "isinstance", "(", "input_number", ",", "tuple", ")", ":", "tuple_list", "=", "list", "(", "input_number", ")", "tuple_str", "=", "[", "]", "for", "i", "in", "tuple_list", "...
Round input number and convert to str. :param input_number: input number :type input_number : anything :param digit: scale (the number of digits to the right of the decimal point in a number.) :type digit : int :return: round number as str
[ "Round", "input", "number", "and", "convert", "to", "str", "." ]
python
train
33.409091