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
Accelize/pycosio
pycosio/storage/s3.py
https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L331-L357
def _read_range(self, start, end=0): """ Read a range of bytes in stream. Args: start (int): Start stream position. end (int): End stream position. 0 To not specify end. Returns: bytes: number of bytes read """ # Get o...
[ "def", "_read_range", "(", "self", ",", "start", ",", "end", "=", "0", ")", ":", "# Get object part from S3", "try", ":", "with", "_handle_client_error", "(", ")", ":", "response", "=", "self", ".", "_client", ".", "get_object", "(", "Range", "=", "self", ...
Read a range of bytes in stream. Args: start (int): Start stream position. end (int): End stream position. 0 To not specify end. Returns: bytes: number of bytes read
[ "Read", "a", "range", "of", "bytes", "in", "stream", "." ]
python
train
28.962963
marshmallow-code/webargs
src/webargs/core.py
https://github.com/marshmallow-code/webargs/blob/40cc2d25421d15d9630b1a819f1dcefbbf01ed95/src/webargs/core.py#L97-L130
def get_value(data, name, field, allow_many_nested=False): """Get a value from a dictionary. Handles ``MultiDict`` types when ``multiple=True``. If the value is not found, return `missing`. :param object data: Mapping (e.g. `dict`) or list-like instance to pull the value from. :param str name: ...
[ "def", "get_value", "(", "data", ",", "name", ",", "field", ",", "allow_many_nested", "=", "False", ")", ":", "missing_value", "=", "missing", "if", "allow_many_nested", "and", "isinstance", "(", "field", ",", "ma", ".", "fields", ".", "Nested", ")", "and"...
Get a value from a dictionary. Handles ``MultiDict`` types when ``multiple=True``. If the value is not found, return `missing`. :param object data: Mapping (e.g. `dict`) or list-like instance to pull the value from. :param str name: Name of the key. :param bool multiple: Whether to handle multi...
[ "Get", "a", "value", "from", "a", "dictionary", ".", "Handles", "MultiDict", "types", "when", "multiple", "=", "True", ".", "If", "the", "value", "is", "not", "found", "return", "missing", "." ]
python
train
35.647059
saltstack/salt
salt/utils/cloud.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/cloud.py#L2634-L2677
def cachedir_index_add(minion_id, profile, driver, provider, base=None): ''' Add an entry to the cachedir index. This generally only needs to happen when a new instance is created. This entry should contain: .. code-block:: yaml - minion_id - profile used to create the instance ...
[ "def", "cachedir_index_add", "(", "minion_id", ",", "profile", ",", "driver", ",", "provider", ",", "base", "=", "None", ")", ":", "base", "=", "init_cachedir", "(", "base", ")", "index_file", "=", "os", ".", "path", ".", "join", "(", "base", ",", "'in...
Add an entry to the cachedir index. This generally only needs to happen when a new instance is created. This entry should contain: .. code-block:: yaml - minion_id - profile used to create the instance - provider and driver name The intent of this function is to speed up lookups f...
[ "Add", "an", "entry", "to", "the", "cachedir", "index", ".", "This", "generally", "only", "needs", "to", "happen", "when", "a", "new", "instance", "is", "created", ".", "This", "entry", "should", "contain", ":" ]
python
train
30.522727
draperjames/qtpandas
qtpandas/utils.py
https://github.com/draperjames/qtpandas/blob/64294fb69f1839e53dee5ea453337266bfaf24f4/qtpandas/utils.py#L180-L205
def superReadFile(filepath, **kwargs): """ Uses pandas.read_excel (on excel files) and returns a dataframe of the first sheet (unless sheet is specified in kwargs) Uses superReadText (on .txt,.tsv, or .csv files) and returns a dataframe of the data. One function to read almost all types of data file...
[ "def", "superReadFile", "(", "filepath", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "filepath", ",", "pd", ".", "DataFrame", ")", ":", "return", "filepath", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filepath", ")", "[", "...
Uses pandas.read_excel (on excel files) and returns a dataframe of the first sheet (unless sheet is specified in kwargs) Uses superReadText (on .txt,.tsv, or .csv files) and returns a dataframe of the data. One function to read almost all types of data files.
[ "Uses", "pandas", ".", "read_excel", "(", "on", "excel", "files", ")", "and", "returns", "a", "dataframe", "of", "the", "first", "sheet", "(", "unless", "sheet", "is", "specified", "in", "kwargs", ")", "Uses", "superReadText", "(", "on", ".", "txt", ".",...
python
train
35.269231
awslabs/serverless-application-model
examples/apps/lex-book-trip-python/lambda_function.py
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-book-trip-python/lambda_function.py#L116-L127
def generate_hotel_price(location, nights, room_type): """ Generates a number within a reasonable range that might be expected for a hotel. The price is fixed for a pair of location and roomType. """ room_types = ['queen', 'king', 'deluxe'] cost_of_living = 0 for i in range(len(location)): ...
[ "def", "generate_hotel_price", "(", "location", ",", "nights", ",", "room_type", ")", ":", "room_types", "=", "[", "'queen'", ",", "'king'", ",", "'deluxe'", "]", "cost_of_living", "=", "0", "for", "i", "in", "range", "(", "len", "(", "location", ")", ")...
Generates a number within a reasonable range that might be expected for a hotel. The price is fixed for a pair of location and roomType.
[ "Generates", "a", "number", "within", "a", "reasonable", "range", "that", "might", "be", "expected", "for", "a", "hotel", ".", "The", "price", "is", "fixed", "for", "a", "pair", "of", "location", "and", "roomType", "." ]
python
train
37.833333
PyCQA/pylint
pylint/checkers/classes.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/classes.py#L768-L790
def _check_proper_bases(self, node): """ Detect that a class inherits something which is not a class or a type. """ for base in node.bases: ancestor = safe_infer(base) if ancestor in (astroid.Uninferable, None): continue if isin...
[ "def", "_check_proper_bases", "(", "self", ",", "node", ")", ":", "for", "base", "in", "node", ".", "bases", ":", "ancestor", "=", "safe_infer", "(", "base", ")", "if", "ancestor", "in", "(", "astroid", ".", "Uninferable", ",", "None", ")", ":", "conti...
Detect that a class inherits something which is not a class or a type.
[ "Detect", "that", "a", "class", "inherits", "something", "which", "is", "not", "a", "class", "or", "a", "type", "." ]
python
test
36.173913
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/parallel/controller/scheduler.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/scheduler.py#L572-L605
def dispatch_result(self, raw_msg): """dispatch method for result replies""" try: idents,msg = self.session.feed_identities(raw_msg, copy=False) msg = self.session.unserialize(msg, content=False, copy=False) engine = idents[0] try: idx = se...
[ "def", "dispatch_result", "(", "self", ",", "raw_msg", ")", ":", "try", ":", "idents", ",", "msg", "=", "self", ".", "session", ".", "feed_identities", "(", "raw_msg", ",", "copy", "=", "False", ")", "msg", "=", "self", ".", "session", ".", "unserializ...
dispatch method for result replies
[ "dispatch", "method", "for", "result", "replies" ]
python
test
40.470588
Microsoft/nni
examples/trials/weight_sharing/ga_squad/data.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/trials/weight_sharing/ga_squad/data.py#L137-L146
def shuffle_step(entries, step): ''' Shuffle the step ''' answer = [] for i in range(0, len(entries), step): sub = entries[i:i+step] shuffle(sub) answer += sub return answer
[ "def", "shuffle_step", "(", "entries", ",", "step", ")", ":", "answer", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "entries", ")", ",", "step", ")", ":", "sub", "=", "entries", "[", "i", ":", "i", "+", "step", "]", "...
Shuffle the step
[ "Shuffle", "the", "step" ]
python
train
21.2
saltstack/salt
doc/_ext/saltdomain.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/doc/_ext/saltdomain.py#L52-L72
def parse_lit(self, lines): ''' Parse a string line-by-line delineating comments and code :returns: An tuple of boolean/list-of-string pairs. True designates a comment; False designates code. ''' comment_char = '#' # TODO: move this into a directive option co...
[ "def", "parse_lit", "(", "self", ",", "lines", ")", ":", "comment_char", "=", "'#'", "# TODO: move this into a directive option", "comment", "=", "re", ".", "compile", "(", "r'^\\s*{0}[ \\n]'", ".", "format", "(", "comment_char", ")", ")", "section_test", "=", "...
Parse a string line-by-line delineating comments and code :returns: An tuple of boolean/list-of-string pairs. True designates a comment; False designates code.
[ "Parse", "a", "string", "line", "-", "by", "-", "line", "delineating", "comments", "and", "code" ]
python
train
35.714286
pantsbuild/pants
src/python/pants/util/contextutil.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/util/contextutil.py#L302-L312
def open_tar(path_or_file, *args, **kwargs): """ A with-context for tar files. Passes through positional and kwargs to tarfile.open. If path_or_file is a file, caller must close it separately. """ (path, fileobj) = ((path_or_file, None) if isinstance(path_or_file, string_types) else...
[ "def", "open_tar", "(", "path_or_file", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "(", "path", ",", "fileobj", ")", "=", "(", "(", "path_or_file", ",", "None", ")", "if", "isinstance", "(", "path_or_file", ",", "string_types", ")", "else", ...
A with-context for tar files. Passes through positional and kwargs to tarfile.open. If path_or_file is a file, caller must close it separately.
[ "A", "with", "-", "context", "for", "tar", "files", ".", "Passes", "through", "positional", "and", "kwargs", "to", "tarfile", ".", "open", "." ]
python
train
52.272727
peri-source/peri
peri/opt/optimize.py
https://github.com/peri-source/peri/blob/61beed5deaaf978ab31ed716e8470d86ba639867/peri/opt/optimize.py#L1138-L1169
def get_termination_stats(self, get_cos=True): """ Returns a dict of termination statistics Parameters ---------- get_cos : Bool, optional Whether or not to calcualte the cosine of the residuals with the tangent plane of the model using the cu...
[ "def", "get_termination_stats", "(", "self", ",", "get_cos", "=", "True", ")", ":", "delta_vals", "=", "self", ".", "_last_vals", "-", "self", ".", "param_vals", "delta_err", "=", "self", ".", "_last_error", "-", "self", ".", "error", "frac_err", "=", "del...
Returns a dict of termination statistics Parameters ---------- get_cos : Bool, optional Whether or not to calcualte the cosine of the residuals with the tangent plane of the model using the current J. The calculation may take some time. Defaul...
[ "Returns", "a", "dict", "of", "termination", "statistics" ]
python
valid
42.34375
ebroecker/canmatrix
src/canmatrix/formats/arxml.py
https://github.com/ebroecker/canmatrix/blob/d6150b7a648350f051a11c431e9628308c8d5593/src/canmatrix/formats/arxml.py#L812-L831
def get_element_by_path(tree, path_and_name, namespace): # type: (_Element, str, str) -> typing.Union[_Element, None] """Find sub-element of given path with given short name.""" global xml_element_cache namespace_map = {'A': namespace[1:-1]} base_path, element_name = path_and_name.rsplit('/', 1) ...
[ "def", "get_element_by_path", "(", "tree", ",", "path_and_name", ",", "namespace", ")", ":", "# type: (_Element, str, str) -> typing.Union[_Element, None]", "global", "xml_element_cache", "namespace_map", "=", "{", "'A'", ":", "namespace", "[", "1", ":", "-", "1", "]"...
Find sub-element of given path with given short name.
[ "Find", "sub", "-", "element", "of", "given", "path", "with", "given", "short", "name", "." ]
python
train
43.1
tensorflow/cleverhans
cleverhans/plot/pyplot_image.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/pyplot_image.py#L9-L49
def pair_visual(original, adversarial, figure=None): """ This function displays two images: the original and the adversarial sample :param original: the original input :param adversarial: the input after perturbations have been applied :param figure: if we've already displayed images, use the same plot :ret...
[ "def", "pair_visual", "(", "original", ",", "adversarial", ",", "figure", "=", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "# Squeeze the image to remove single-dimensional entries from array shape", "original", "=", "np", ".", "squeeze", "("...
This function displays two images: the original and the adversarial sample :param original: the original input :param adversarial: the input after perturbations have been applied :param figure: if we've already displayed images, use the same plot :return: the matplot figure to reuse for future samples
[ "This", "function", "displays", "two", "images", ":", "the", "original", "and", "the", "adversarial", "sample", ":", "param", "original", ":", "the", "original", "input", ":", "param", "adversarial", ":", "the", "input", "after", "perturbations", "have", "been...
python
train
32
log2timeline/plaso
plaso/cli/helpers/database_config.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/helpers/database_config.py#L22-L45
def AddArguments(cls, argument_group): """Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|arg...
[ "def", "AddArguments", "(", "cls", ",", "argument_group", ")", ":", "argument_group", ".", "add_argument", "(", "'--user'", ",", "dest", "=", "'username'", ",", "type", "=", "str", ",", "action", "=", "'store'", ",", "default", "=", "cls", ".", "_DEFAULT_U...
Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse grou...
[ "Adds", "command", "line", "arguments", "the", "helper", "supports", "to", "an", "argument", "group", "." ]
python
train
45.541667
astropy/photutils
photutils/psf/epsf_stars.py
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/epsf_stars.py#L388-L402
def all_good_stars(self): """ A list of all `EPSFStar` objects stored in this object that have not been excluded from fitting, including those that comprise linked stars (i.e. `LinkedEPSFStar`), as a flat list. """ stars = [] for star in self.all_stars: ...
[ "def", "all_good_stars", "(", "self", ")", ":", "stars", "=", "[", "]", "for", "star", "in", "self", ".", "all_stars", ":", "if", "star", ".", "_excluded_from_fit", ":", "continue", "else", ":", "stars", ".", "append", "(", "star", ")", "return", "star...
A list of all `EPSFStar` objects stored in this object that have not been excluded from fitting, including those that comprise linked stars (i.e. `LinkedEPSFStar`), as a flat list.
[ "A", "list", "of", "all", "EPSFStar", "objects", "stored", "in", "this", "object", "that", "have", "not", "been", "excluded", "from", "fitting", "including", "those", "that", "comprise", "linked", "stars", "(", "i", ".", "e", ".", "LinkedEPSFStar", ")", "a...
python
train
29.066667
bukun/TorCMS
torcms/modules/info_modules.py
https://github.com/bukun/TorCMS/blob/6567c7fe2604a1d646d4570c017840958630ed2b/torcms/modules/info_modules.py#L185-L197
def render_it(self, kind, num, with_tag=False, glyph=''): ''' render, no user logged in ''' all_cats = MPost.query_recent(num, kind=kind) kwd = { 'with_tag': with_tag, 'router': router_post[kind], 'glyph': glyph } return self.re...
[ "def", "render_it", "(", "self", ",", "kind", ",", "num", ",", "with_tag", "=", "False", ",", "glyph", "=", "''", ")", ":", "all_cats", "=", "MPost", ".", "query_recent", "(", "num", ",", "kind", "=", "kind", ")", "kwd", "=", "{", "'with_tag'", ":"...
render, no user logged in
[ "render", "no", "user", "logged", "in" ]
python
train
34.307692
neherlab/treetime
treetime/gtr_site_specific.py
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr_site_specific.py#L83-L125
def random(cls, L=1, avg_mu=1.0, alphabet='nuc', pi_dirichlet_alpha=1, W_dirichlet_alpha=3.0, mu_gamma_alpha=3.0): """ Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (s...
[ "def", "random", "(", "cls", ",", "L", "=", "1", ",", "avg_mu", "=", "1.0", ",", "alphabet", "=", "'nuc'", ",", "pi_dirichlet_alpha", "=", "1", ",", "W_dirichlet_alpha", "=", "3.0", ",", "mu_gamma_alpha", "=", "3.0", ")", ":", "from", "scipy", ".", "...
Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (should be standard: 'nuc', 'nuc_gap', 'aa', 'aa_gap')
[ "Creates", "a", "random", "GTR", "model" ]
python
test
25.534884
googlefonts/glyphsLib
Lib/glyphsLib/builder/builders.py
https://github.com/googlefonts/glyphsLib/blob/9c12dc70c8d13f08d92b824e6710f6e3bb5037bb/Lib/glyphsLib/builder/builders.py#L277-L419
def _apply_bracket_layers(self): """Extract bracket layers in a GSGlyph into free-standing UFO glyphs with Designspace substitution rules. As of Glyphs.app 2.6, only single axis bracket layers are supported, we assume the axis to be the first axis in the Designspace. Bracket layer ...
[ "def", "_apply_bracket_layers", "(", "self", ")", ":", "if", "not", "self", ".", "_designspace", ".", "axes", ":", "raise", "ValueError", "(", "\"Cannot apply bracket layers unless at least one axis is defined.\"", ")", "bracket_axis", "=", "self", ".", "_designspace", ...
Extract bracket layers in a GSGlyph into free-standing UFO glyphs with Designspace substitution rules. As of Glyphs.app 2.6, only single axis bracket layers are supported, we assume the axis to be the first axis in the Designspace. Bracket layer backgrounds are not round-tripped. ...
[ "Extract", "bracket", "layers", "in", "a", "GSGlyph", "into", "free", "-", "standing", "UFO", "glyphs", "with", "Designspace", "substitution", "rules", "." ]
python
train
48.13986
soimort/you-get
src/you_get/extractors/bokecc.py
https://github.com/soimort/you-get/blob/b746ac01c9f39de94cac2d56f665285b0523b974/src/you_get/extractors/bokecc.py#L17-L39
def download_by_id(self, vid = '', title = None, output_dir='.', merge=True, info_only=False,**kwargs): """self, str->None Keyword arguments: self: self vid: The video ID for BokeCC cloud, something like FE3BB999594978049C33DC5901307461 Calls the prepare...
[ "def", "download_by_id", "(", "self", ",", "vid", "=", "''", ",", "title", "=", "None", ",", "output_dir", "=", "'.'", ",", "merge", "=", "True", ",", "info_only", "=", "False", ",", "*", "*", "kwargs", ")", ":", "assert", "vid", "self", ".", "prep...
self, str->None Keyword arguments: self: self vid: The video ID for BokeCC cloud, something like FE3BB999594978049C33DC5901307461 Calls the prepare() to download the video. If no title is provided, this method shall try to find a proper title ...
[ "self", "str", "-", ">", "None", "Keyword", "arguments", ":", "self", ":", "self", "vid", ":", "The", "video", "ID", "for", "BokeCC", "cloud", "something", "like", "FE3BB999594978049C33DC5901307461", "Calls", "the", "prepare", "()", "to", "download", "the", ...
python
test
32.478261
jssimporter/python-jss
jss/jamf_software_server.py
https://github.com/jssimporter/python-jss/blob/b95185d74e0c0531b0b563f280d4129e21d5fe5d/jss/jamf_software_server.py#L660-L663
def MobileDeviceApplication(self, data=None, subset=None): """{dynamic_docstring}""" return self.factory.get_object(jssobjects.MobileDeviceApplication, data, subset)
[ "def", "MobileDeviceApplication", "(", "self", ",", "data", "=", "None", ",", "subset", "=", "None", ")", ":", "return", "self", ".", "factory", ".", "get_object", "(", "jssobjects", ".", "MobileDeviceApplication", ",", "data", ",", "subset", ")" ]
{dynamic_docstring}
[ "{", "dynamic_docstring", "}" ]
python
train
54.25
domainaware/parsedmarc
parsedmarc/utils.py
https://github.com/domainaware/parsedmarc/blob/ecc9fd434c23d896ccd1f35795ccc047f946ed05/parsedmarc/utils.py#L393-L410
def get_filename_safe_string(string): """ Converts a string to a string that is safe for a filename Args: string (str): A string to make safe for a filename Returns: str: A string safe for a filename """ invalid_filename_chars = ['\\', '/', ':', '"', '*', '?', '|', '\n', ...
[ "def", "get_filename_safe_string", "(", "string", ")", ":", "invalid_filename_chars", "=", "[", "'\\\\'", ",", "'/'", ",", "':'", ",", "'\"'", ",", "'*'", ",", "'?'", ",", "'|'", ",", "'\\n'", ",", "'\\r'", "]", "if", "string", "is", "None", ":", "stri...
Converts a string to a string that is safe for a filename Args: string (str): A string to make safe for a filename Returns: str: A string safe for a filename
[ "Converts", "a", "string", "to", "a", "string", "that", "is", "safe", "for", "a", "filename", "Args", ":", "string", "(", "str", ")", ":", "A", "string", "to", "make", "safe", "for", "a", "filename" ]
python
test
28.388889
BlueBrain/NeuroM
neurom/check/structural_checks.py
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/check/structural_checks.py#L117-L127
def has_valid_soma(data_wrapper): '''Check if a data block has a valid soma Returns: CheckResult with result ''' try: make_soma(data_wrapper.soma_points()) return CheckResult(True) except SomaError: return CheckResult(False)
[ "def", "has_valid_soma", "(", "data_wrapper", ")", ":", "try", ":", "make_soma", "(", "data_wrapper", ".", "soma_points", "(", ")", ")", "return", "CheckResult", "(", "True", ")", "except", "SomaError", ":", "return", "CheckResult", "(", "False", ")" ]
Check if a data block has a valid soma Returns: CheckResult with result
[ "Check", "if", "a", "data", "block", "has", "a", "valid", "soma" ]
python
train
24.272727
roll/interest-py
interest/logger/logger.py
https://github.com/roll/interest-py/blob/e6e1def4f2999222aac2fb1d290ae94250673b89/interest/logger/logger.py#L112-L117
def error(self, message, *args, **kwargs): """Log error event. Compatible with logging.error signature. """ self.system.error(message, *args, **kwargs)
[ "def", "error", "(", "self", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "system", ".", "error", "(", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Log error event. Compatible with logging.error signature.
[ "Log", "error", "event", "." ]
python
train
29.833333
chaoss/grimoirelab-elk
utils/index_mapping.py
https://github.com/chaoss/grimoirelab-elk/blob/64e08b324b36d9f6909bf705145d6451c8d34e65/utils/index_mapping.py#L145-L190
def get_elastic_items(elastic, elastic_scroll_id=None, limit=None): """ Get the items from the index """ scroll_size = limit if not limit: scroll_size = DEFAULT_LIMIT if not elastic: return None url = elastic.index_url max_process_items_pack_time = "5m" # 10 minutes url +...
[ "def", "get_elastic_items", "(", "elastic", ",", "elastic_scroll_id", "=", "None", ",", "limit", "=", "None", ")", ":", "scroll_size", "=", "limit", "if", "not", "limit", ":", "scroll_size", "=", "DEFAULT_LIMIT", "if", "not", "elastic", ":", "return", "None"...
Get the items from the index
[ "Get", "the", "items", "from", "the", "index" ]
python
train
26.413043
orbingol/NURBS-Python
geomdl/operations.py
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L1369-L1388
def find_ctrlpts(obj, u, v=None, **kwargs): """ Finds the control points involved in the evaluation of the curve/surface point defined by the input parameter(s). :param obj: curve or surface :type obj: abstract.Curve or abstract.Surface :param u: parameter (for curve), parameter on the u-direction (for...
[ "def", "find_ctrlpts", "(", "obj", ",", "u", ",", "v", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "obj", ",", "abstract", ".", "Curve", ")", ":", "return", "ops", ".", "find_ctrlpts_curve", "(", "u", ",", "obj", ",", ...
Finds the control points involved in the evaluation of the curve/surface point defined by the input parameter(s). :param obj: curve or surface :type obj: abstract.Curve or abstract.Surface :param u: parameter (for curve), parameter on the u-direction (for surface) :type u: float :param v: parameter...
[ "Finds", "the", "control", "points", "involved", "in", "the", "evaluation", "of", "the", "curve", "/", "surface", "point", "defined", "by", "the", "input", "parameter", "(", "s", ")", "." ]
python
train
48.6
CiscoTestAutomation/yang
ncdiff/src/yang/ncdiff/gnmi.py
https://github.com/CiscoTestAutomation/yang/blob/c70ec5ac5a91f276c4060009203770ece92e76b4/ncdiff/src/yang/ncdiff/gnmi.py#L569-L634
def get_path(self, instance=True, origin='openconfig'): '''get_path High-level api: get_path returns gNMI path object of the config node. Note that gNMI Path can specify list instance but cannot specify leaf-list instance. Parameters ---------- instance : `bool...
[ "def", "get_path", "(", "self", ",", "instance", "=", "True", ",", "origin", "=", "'openconfig'", ")", ":", "def", "get_name", "(", "node", ",", "default_ns", ")", ":", "if", "origin", "==", "'openconfig'", "or", "origin", "==", "''", ":", "return", "g...
get_path High-level api: get_path returns gNMI path object of the config node. Note that gNMI Path can specify list instance but cannot specify leaf-list instance. Parameters ---------- instance : `bool` True if the gNMI Path object refers to only one insta...
[ "get_path" ]
python
train
41.242424
hobson/aima
aima/probability.py
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/probability.py#L421-L433
def likelihood_weighting(X, e, bn, N): """Estimate the probability distribution of variable X given evidence e in BayesNet bn. [Fig. 14.15] >>> seed(1017) >>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T), ... burglary, 10000).show_approx() 'False: 0.702, True: 0.298' ""...
[ "def", "likelihood_weighting", "(", "X", ",", "e", ",", "bn", ",", "N", ")", ":", "W", "=", "dict", "(", "(", "x", ",", "0", ")", "for", "x", "in", "bn", ".", "variable_values", "(", "X", ")", ")", "for", "j", "in", "xrange", "(", "N", ")", ...
Estimate the probability distribution of variable X given evidence e in BayesNet bn. [Fig. 14.15] >>> seed(1017) >>> likelihood_weighting('Burglary', dict(JohnCalls=T, MaryCalls=T), ... burglary, 10000).show_approx() 'False: 0.702, True: 0.298'
[ "Estimate", "the", "probability", "distribution", "of", "variable", "X", "given", "evidence", "e", "in", "BayesNet", "bn", ".", "[", "Fig", ".", "14", ".", "15", "]", ">>>", "seed", "(", "1017", ")", ">>>", "likelihood_weighting", "(", "Burglary", "dict", ...
python
valid
40
Esri/ArcREST
src/arcrest/manageorg/_portals.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_portals.py#L1267-L1334
def users(self, start=1, num=10, sortField="fullName", sortOrder="asc", role=None): """ Lists all the members of the organization. The start and num paging parameters are supported. Inputs: start - The numb...
[ "def", "users", "(", "self", ",", "start", "=", "1", ",", "num", "=", "10", ",", "sortField", "=", "\"fullName\"", ",", "sortOrder", "=", "\"asc\"", ",", "role", "=", "None", ")", ":", "users", "=", "[", "]", "url", "=", "self", ".", "_url", "+",...
Lists all the members of the organization. The start and num paging parameters are supported. Inputs: start - The number of the first entry in the result set response. The index number is 1-based. The default value of start is 1 (that is, the first ...
[ "Lists", "all", "the", "members", "of", "the", "organization", ".", "The", "start", "and", "num", "paging", "parameters", "are", "supported", "." ]
python
train
41.867647
project-rig/rig
rig/machine_control/machine_controller.py
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/machine_controller.py#L754-L761
def _get_vcpu_field_and_address(self, field_name, x, y, p): """Get the field and address for a VCPU struct field.""" vcpu_struct = self.structs[b"vcpu"] field = vcpu_struct[six.b(field_name)] address = (self.read_struct_field("sv", "vcpu_base", x, y) + vcpu_struct.size...
[ "def", "_get_vcpu_field_and_address", "(", "self", ",", "field_name", ",", "x", ",", "y", ",", "p", ")", ":", "vcpu_struct", "=", "self", ".", "structs", "[", "b\"vcpu\"", "]", "field", "=", "vcpu_struct", "[", "six", ".", "b", "(", "field_name", ")", ...
Get the field and address for a VCPU struct field.
[ "Get", "the", "field", "and", "address", "for", "a", "VCPU", "struct", "field", "." ]
python
train
52.5
tanghaibao/jcvi
jcvi/algorithms/tsp.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/algorithms/tsp.py#L50-L98
def print_to_tsplib(self, edges, tspfile, precision=0): """ See TSPlib format: <https://www.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/> NAME: bayg29 TYPE: TSP COMMENT: 29 Cities in Bavaria, geographical distances DIMENSION: 29 EDGE_WEIGHT_TYPE...
[ "def", "print_to_tsplib", "(", "self", ",", "edges", ",", "tspfile", ",", "precision", "=", "0", ")", ":", "fw", "=", "must_open", "(", "tspfile", ",", "\"w\"", ")", "incident", ",", "nodes", "=", "node_to_edge", "(", "edges", ",", "directed", "=", "Fa...
See TSPlib format: <https://www.iwr.uni-heidelberg.de/groups/comopt/software/TSPLIB95/> NAME: bayg29 TYPE: TSP COMMENT: 29 Cities in Bavaria, geographical distances DIMENSION: 29 EDGE_WEIGHT_TYPE: EXPLICIT EDGE_WEIGHT_FORMAT: UPPER_ROW DISPLAY_DATA_TYPE: ...
[ "See", "TSPlib", "format", ":", "<https", ":", "//", "www", ".", "iwr", ".", "uni", "-", "heidelberg", ".", "de", "/", "groups", "/", "comopt", "/", "software", "/", "TSPLIB95", "/", ">" ]
python
train
36.836735
honeynet/beeswarm
beeswarm/drones/client/baits/ftp.py
https://github.com/honeynet/beeswarm/blob/db51ea0bc29f631c3e3b5312b479ac9d5e31079a/beeswarm/drones/client/baits/ftp.py#L206-L217
def _process_list(self, list_line): # -rw-r--r-- 1 ftp ftp 68 May 09 19:37 testftp.txt """ Processes a line of 'ls -l' output, and updates state accordingly. :param list_line: Line to process """ res = list_line.split(' ', 8) if res[0].startswith('-'): ...
[ "def", "_process_list", "(", "self", ",", "list_line", ")", ":", "# -rw-r--r-- 1 ftp ftp 68\t May 09 19:37 testftp.txt", "res", "=", "list_line", ".", "split", "(", "' '", ",", "8", ")", "if", "res", "[", "0", "]", ".", "startswith", "(", "'-'", ")", ":", ...
Processes a line of 'ls -l' output, and updates state accordingly. :param list_line: Line to process
[ "Processes", "a", "line", "of", "ls", "-", "l", "output", "and", "updates", "state", "accordingly", "." ]
python
train
36.75
bwohlberg/sporco
sporco/admm/ccmod.py
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/ccmod.py#L768-L802
def xstep(self): r"""Minimise Augmented Lagrangian with respect to block vector :math:`\mathbf{x} = \left( \begin{array}{ccc} \mathbf{x}_0^T & \mathbf{x}_1^T & \ldots \end{array} \right)^T\;`. """ # This test reflects empirical evidence that two slightly # different impl...
[ "def", "xstep", "(", "self", ")", ":", "# This test reflects empirical evidence that two slightly", "# different implementations are faster for single or", "# multi-channel data. This kludge is intended to be temporary.", "if", "self", ".", "cri", ".", "Cd", ">", "1", ":", "for",...
r"""Minimise Augmented Lagrangian with respect to block vector :math:`\mathbf{x} = \left( \begin{array}{ccc} \mathbf{x}_0^T & \mathbf{x}_1^T & \ldots \end{array} \right)^T\;`.
[ "r", "Minimise", "Augmented", "Lagrangian", "with", "respect", "to", "block", "vector", ":", "math", ":", "\\", "mathbf", "{", "x", "}", "=", "\\", "left", "(", "\\", "begin", "{", "array", "}", "{", "ccc", "}", "\\", "mathbf", "{", "x", "}", "_0^T...
python
train
44.714286
openpermissions/chub
chub/api.py
https://github.com/openpermissions/chub/blob/00762aa17015f4b3010673d1570c708eab3c34ed/chub/api.py#L75-L79
def prepare_request(self, *args, **kw): """ creates a full featured HTTPRequest objects """ self.http_request = self.request_class(self.path, *args, **kw)
[ "def", "prepare_request", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "http_request", "=", "self", ".", "request_class", "(", "self", ".", "path", ",", "*", "args", ",", "*", "*", "kw", ")" ]
creates a full featured HTTPRequest objects
[ "creates", "a", "full", "featured", "HTTPRequest", "objects" ]
python
train
36.4
BerkeleyAutomation/autolab_core
autolab_core/rigid_transformations.py
https://github.com/BerkeleyAutomation/autolab_core/blob/8f3813f6401972868cc5e3981ba1b4382d4418d5/autolab_core/rigid_transformations.py#L812-L840
def rotation_from_axis_and_origin(axis, origin, angle, to_frame='world'): """ Returns a rotation matrix around some arbitrary axis, about the point origin, using Rodrigues Formula Parameters ---------- axis : :obj:`numpy.ndarray` of float 3x1 vector representing whic...
[ "def", "rotation_from_axis_and_origin", "(", "axis", ",", "origin", ",", "angle", ",", "to_frame", "=", "'world'", ")", ":", "axis_hat", "=", "np", ".", "array", "(", "[", "[", "0", ",", "-", "axis", "[", "2", "]", ",", "axis", "[", "1", "]", "]", ...
Returns a rotation matrix around some arbitrary axis, about the point origin, using Rodrigues Formula Parameters ---------- axis : :obj:`numpy.ndarray` of float 3x1 vector representing which axis we should be rotating about origin : :obj:`numpy.ndarray` of float ...
[ "Returns", "a", "rotation", "matrix", "around", "some", "arbitrary", "axis", "about", "the", "point", "origin", "using", "Rodrigues", "Formula" ]
python
train
43.241379
mental32/spotify.py
spotify/models/player.py
https://github.com/mental32/spotify.py/blob/bb296cac7c3dd289908906b7069bd80f43950515/spotify/models/player.py#L213-L224
async def transfer(self, device: SomeDevice, ensure_playback: bool = False): """Transfer playback to a new device and determine if it should start playing. Parameters ---------- device : :obj:`SomeDevice` The device on which playback should be started/transferred. en...
[ "async", "def", "transfer", "(", "self", ",", "device", ":", "SomeDevice", ",", "ensure_playback", ":", "bool", "=", "False", ")", ":", "await", "self", ".", "_user", ".", "http", ".", "transfer_player", "(", "str", "(", "device", ")", ",", "play", "="...
Transfer playback to a new device and determine if it should start playing. Parameters ---------- device : :obj:`SomeDevice` The device on which playback should be started/transferred. ensure_playback : bool if `True` ensure playback happens on new device. ...
[ "Transfer", "playback", "to", "a", "new", "device", "and", "determine", "if", "it", "should", "start", "playing", "." ]
python
test
44.416667
soynatan/django-easy-audit
easyaudit/admin_helpers.py
https://github.com/soynatan/django-easy-audit/blob/03e05bc94beb29fc3e4ff86e313a6fef4b766b4b/easyaudit/admin_helpers.py#L66-L116
def purge_objects(self, request): """ Removes all objects in this table. This action first displays a confirmation page; next, it deletes all objects and redirects back to the change list. """ def truncate_table(model): if settings.TRUNCATE_TABLE_SQL_STATEMEN...
[ "def", "purge_objects", "(", "self", ",", "request", ")", ":", "def", "truncate_table", "(", "model", ")", ":", "if", "settings", ".", "TRUNCATE_TABLE_SQL_STATEMENT", ":", "from", "django", ".", "db", "import", "connection", "sql", "=", "settings", ".", "TRU...
Removes all objects in this table. This action first displays a confirmation page; next, it deletes all objects and redirects back to the change list.
[ "Removes", "all", "objects", "in", "this", "table", ".", "This", "action", "first", "displays", "a", "confirmation", "page", ";", "next", "it", "deletes", "all", "objects", "and", "redirects", "back", "to", "the", "change", "list", "." ]
python
train
40.470588
line/line-bot-sdk-python
linebot/api.py
https://github.com/line/line-bot-sdk-python/blob/1b38bfc2497ff3e3c75be4b50e0f1b7425a07ce0/linebot/api.py#L235-L262
def get_group_member_ids(self, group_id, start=None, timeout=None): """Call get group member IDs API. https://devdocs.line.me/en/#get-group-room-member-ids Gets the user IDs of the members of a group that the bot is in. This includes the user IDs of users who have not added the bot as ...
[ "def", "get_group_member_ids", "(", "self", ",", "group_id", ",", "start", "=", "None", ",", "timeout", "=", "None", ")", ":", "params", "=", "None", "if", "start", "is", "None", "else", "{", "'start'", ":", "start", "}", "response", "=", "self", ".", ...
Call get group member IDs API. https://devdocs.line.me/en/#get-group-room-member-ids Gets the user IDs of the members of a group that the bot is in. This includes the user IDs of users who have not added the bot as a friend or has blocked the bot. :param str group_id: Group ID...
[ "Call", "get", "group", "member", "IDs", "API", "." ]
python
train
39.464286
saltstack/salt
salt/netapi/__init__.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/__init__.py#L178-L191
def wheel(self, fun, **kwargs): ''' Run :ref:`wheel modules <all-salt.wheel>` synchronously Wraps :py:meth:`salt.wheel.WheelClient.master_call`. Note that wheel functions must be called using keyword arguments. Positional arguments are not supported. :return: Returns t...
[ "def", "wheel", "(", "self", ",", "fun", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'fun'", "]", "=", "fun", "wheel", "=", "salt", ".", "wheel", ".", "WheelClient", "(", "self", ".", "opts", ")", "return", "wheel", ".", "cmd_sync", "(", "...
Run :ref:`wheel modules <all-salt.wheel>` synchronously Wraps :py:meth:`salt.wheel.WheelClient.master_call`. Note that wheel functions must be called using keyword arguments. Positional arguments are not supported. :return: Returns the result from the wheel module
[ "Run", ":", "ref", ":", "wheel", "modules", "<all", "-", "salt", ".", "wheel", ">", "synchronously" ]
python
train
33.285714
google/tangent
tangent/ast.py
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/ast.py#L83-L90
def copy_node(node): """Copy a node but keep its annotations intact.""" if not isinstance(node, gast.AST): return [copy_node(n) for n in node] new_node = copy.deepcopy(node) setattr(new_node, anno.ANNOTATION_FIELD, getattr(node, anno.ANNOTATION_FIELD, {}).copy()) return new_node
[ "def", "copy_node", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ",", "gast", ".", "AST", ")", ":", "return", "[", "copy_node", "(", "n", ")", "for", "n", "in", "node", "]", "new_node", "=", "copy", ".", "deepcopy", "(", "node", ...
Copy a node but keep its annotations intact.
[ "Copy", "a", "node", "but", "keep", "its", "annotations", "intact", "." ]
python
train
37
panosl/django-currencies
currencies/management/commands/updatecurrencies.py
https://github.com/panosl/django-currencies/blob/8d4c6c202ad7c4cc06263ab2c1b1f969bbe99acd/currencies/management/commands/updatecurrencies.py#L15-L21
def add_arguments(self, parser): """Add command arguments""" parser.add_argument(self._source_param, **self._source_kwargs) parser.add_argument('--base', '-b', action='store', help= 'Supply the base currency as code or a settings variable name. ' 'The default is...
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "self", ".", "_source_param", ",", "*", "*", "self", ".", "_source_kwargs", ")", "parser", ".", "add_argument", "(", "'--base'", ",", "'-b'", ",", "action", ...
Add command arguments
[ "Add", "command", "arguments" ]
python
train
60.857143
tensorflow/probability
tensorflow_probability/python/stats/sample_stats.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/sample_stats.py#L646-L661
def _make_list_or_1d_tensor(values): """Return a list (preferred) or 1d Tensor from values, if values.ndims < 2.""" values = tf.convert_to_tensor(value=values, name='values') values_ = tf.get_static_value(values) # Static didn't work. if values_ is None: # Cheap way to bring to at least 1d. return va...
[ "def", "_make_list_or_1d_tensor", "(", "values", ")", ":", "values", "=", "tf", ".", "convert_to_tensor", "(", "value", "=", "values", ",", "name", "=", "'values'", ")", "values_", "=", "tf", ".", "get_static_value", "(", "values", ")", "# Static didn't work."...
Return a list (preferred) or 1d Tensor from values, if values.ndims < 2.
[ "Return", "a", "list", "(", "preferred", ")", "or", "1d", "Tensor", "from", "values", "if", "values", ".", "ndims", "<", "2", "." ]
python
test
36
anlutro/diay.py
diay/__init__.py
https://github.com/anlutro/diay.py/blob/78cfd2b53c8dca3dbac468d620eaa0bb7af08275/diay/__init__.py#L173-L187
def call(self, func, *args, **kwargs): """ Call a function, resolving any type-hinted arguments. """ guessed_kwargs = self._guess_kwargs(func) for key, val in guessed_kwargs.items(): kwargs.setdefault(key, val) try: return func(*args, **kwargs) ...
[ "def", "call", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "guessed_kwargs", "=", "self", ".", "_guess_kwargs", "(", "func", ")", "for", "key", ",", "val", "in", "guessed_kwargs", ".", "items", "(", ")", ":", "kwa...
Call a function, resolving any type-hinted arguments.
[ "Call", "a", "function", "resolving", "any", "type", "-", "hinted", "arguments", "." ]
python
train
37.133333
openvax/varcode
varcode/effects/effect_prediction_coding_in_frame.py
https://github.com/openvax/varcode/blob/981633db45ca2b31f76c06894a7360ea5d70a9b8/varcode/effects/effect_prediction_coding_in_frame.py#L110-L267
def predict_in_frame_coding_effect( variant, transcript, trimmed_cdna_ref, trimmed_cdna_alt, sequence_from_start_codon, cds_offset): """Coding effect of an in-frame nucleotide change Parameters ---------- variant : Variant transcript : Transcript ...
[ "def", "predict_in_frame_coding_effect", "(", "variant", ",", "transcript", ",", "trimmed_cdna_ref", ",", "trimmed_cdna_alt", ",", "sequence_from_start_codon", ",", "cds_offset", ")", ":", "ref_codon_start_offset", ",", "ref_codon_end_offset", ",", "mutant_codons", "=", "...
Coding effect of an in-frame nucleotide change Parameters ---------- variant : Variant transcript : Transcript trimmed_cdna_ref : str Reference nucleotides from the coding sequence of the transcript trimmed_cdna_alt : str Nucleotides to insert in place of the reference nucleo...
[ "Coding", "effect", "of", "an", "in", "-", "frame", "nucleotide", "change" ]
python
train
36.620253
tmoerman/arboreto
arboreto/algo.py
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/algo.py#L194-L231
def _prepare_input(expression_data, gene_names, tf_names): """ Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D nump...
[ "def", "_prepare_input", "(", "expression_data", ",", "gene_names", ",", "tf_names", ")", ":", "if", "isinstance", "(", "expression_data", ",", "pd", ".", "DataFrame", ")", ":", "expression_matrix", "=", "expression_data", ".", "as_matrix", "(", ")", "gene_names...
Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list...
[ "Wrangle", "the", "inputs", "into", "the", "correct", "formats", "." ]
python
train
40.263158
quantopian/zipline
zipline/data/minute_bars.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/minute_bars.py#L661-L666
def set_sid_attrs(self, sid, **kwargs): """Write all the supplied kwargs as attributes of the sid's file. """ table = self._ensure_ctable(sid) for k, v in kwargs.items(): table.attrs[k] = v
[ "def", "set_sid_attrs", "(", "self", ",", "sid", ",", "*", "*", "kwargs", ")", ":", "table", "=", "self", ".", "_ensure_ctable", "(", "sid", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "table", ".", "attrs", "[", "k", ...
Write all the supplied kwargs as attributes of the sid's file.
[ "Write", "all", "the", "supplied", "kwargs", "as", "attributes", "of", "the", "sid", "s", "file", "." ]
python
train
38
guykisel/inline-plz
inlineplz/interfaces/github.py
https://github.com/guykisel/inline-plz/blob/b5b1744e9156e31f68b519c0d8022feff79888ae/inlineplz/interfaces/github.py#L209-L232
def finish_review(self, success=True, error=False): """Mark our review as finished.""" if self.set_status: if error: self.github_repo.create_status( state="error", description="Static analysis error! inline-plz failed to run.", ...
[ "def", "finish_review", "(", "self", ",", "success", "=", "True", ",", "error", "=", "False", ")", ":", "if", "self", ".", "set_status", ":", "if", "error", ":", "self", ".", "github_repo", ".", "create_status", "(", "state", "=", "\"error\"", ",", "de...
Mark our review as finished.
[ "Mark", "our", "review", "as", "finished", "." ]
python
train
40.583333
peerplays-network/python-peerplays
peerplaysapi/websocket.py
https://github.com/peerplays-network/python-peerplays/blob/188f04238e7e21d5f73e9b01099eea44289ef6b7/peerplaysapi/websocket.py#L216-L263
def on_message(self, ws, reply, *args): """ This method is called by the websocket connection on every message that is received. If we receive a ``notice``, we hand over post-processing and signalling of events to ``process_notice``. """ log.debug("Received me...
[ "def", "on_message", "(", "self", ",", "ws", ",", "reply", ",", "*", "args", ")", ":", "log", ".", "debug", "(", "\"Received message: %s\"", "%", "str", "(", "reply", ")", ")", "data", "=", "{", "}", "try", ":", "data", "=", "json", ".", "loads", ...
This method is called by the websocket connection on every message that is received. If we receive a ``notice``, we hand over post-processing and signalling of events to ``process_notice``.
[ "This", "method", "is", "called", "by", "the", "websocket", "connection", "on", "every", "message", "that", "is", "received", ".", "If", "we", "receive", "a", "notice", "we", "hand", "over", "post", "-", "processing", "and", "signalling", "of", "events", "...
python
train
42.333333
VJftw/invoke-tools
invoke_tools/vcs/git_scm.py
https://github.com/VJftw/invoke-tools/blob/9584a1f8a402118310b6f2a495062f388fc8dc3a/invoke_tools/vcs/git_scm.py#L19-L35
def get_branch(self): """ :return: """ if self.repo.head.is_detached: if os.getenv('GIT_BRANCH'): branch = os.getenv('GIT_BRANCH') elif os.getenv('BRANCH_NAME'): branch = os.getenv('BRANCH_NAME') elif os.getenv('TRAVIS_B...
[ "def", "get_branch", "(", "self", ")", ":", "if", "self", ".", "repo", ".", "head", ".", "is_detached", ":", "if", "os", ".", "getenv", "(", "'GIT_BRANCH'", ")", ":", "branch", "=", "os", ".", "getenv", "(", "'GIT_BRANCH'", ")", "elif", "os", ".", ...
:return:
[ ":", "return", ":" ]
python
train
30.529412
mlperf/training
translation/tensorflow/transformer/utils/tokenizer.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/utils/tokenizer.py#L481-L499
def _filter_and_bucket_subtokens(subtoken_counts, min_count): """Return a bucketed list of subtokens that are filtered by count. Args: subtoken_counts: defaultdict mapping subtokens to their counts min_count: int count used to filter subtokens Returns: List of subtoken sets, where subtokens in set i...
[ "def", "_filter_and_bucket_subtokens", "(", "subtoken_counts", ",", "min_count", ")", ":", "# Create list of buckets, where subtokens in bucket i have length i.", "subtoken_buckets", "=", "[", "]", "for", "subtoken", ",", "count", "in", "six", ".", "iteritems", "(", "subt...
Return a bucketed list of subtokens that are filtered by count. Args: subtoken_counts: defaultdict mapping subtokens to their counts min_count: int count used to filter subtokens Returns: List of subtoken sets, where subtokens in set i have the same length=i.
[ "Return", "a", "bucketed", "list", "of", "subtokens", "that", "are", "filtered", "by", "count", "." ]
python
train
38.789474
FactoryBoy/factory_boy
factory/random.py
https://github.com/FactoryBoy/factory_boy/blob/edaa7c7f5a14065b229927903bd7989cc93cd069/factory/random.py#L16-L21
def set_random_state(state): """Force-set the state of factory.fuzzy's random generator.""" randgen.state_set = True randgen.setstate(state) faker.generator.random.setstate(state)
[ "def", "set_random_state", "(", "state", ")", ":", "randgen", ".", "state_set", "=", "True", "randgen", ".", "setstate", "(", "state", ")", "faker", ".", "generator", ".", "random", ".", "setstate", "(", "state", ")" ]
Force-set the state of factory.fuzzy's random generator.
[ "Force", "-", "set", "the", "state", "of", "factory", ".", "fuzzy", "s", "random", "generator", "." ]
python
train
31.833333
materials-data-facility/toolbox
mdf_toolbox/search_helper.py
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/search_helper.py#L522-L541
def match_exists(self, field, required=True, new_group=False): """Require a field to exist in the results. Matches will have some value in ``field``. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules ...
[ "def", "match_exists", "(", "self", ",", "field", ",", "required", "=", "True", ",", "new_group", "=", "False", ")", ":", "return", "self", ".", "match_field", "(", "field", ",", "\"*\"", ",", "required", "=", "required", ",", "new_group", "=", "new_grou...
Require a field to exist in the results. Matches will have some value in ``field``. Arguments: field (str): The field to check. The field must be namespaced according to Elasticsearch rules using the dot syntax. For example, ``"mdf...
[ "Require", "a", "field", "to", "exist", "in", "the", "results", ".", "Matches", "will", "have", "some", "value", "in", "field", "." ]
python
train
47.05
genialis/resolwe
resolwe/flow/models/data.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/data.py#L338-L401
def create_entity(self): """Create entity if `flow_collection` is defined in process. Following rules applies for adding `Data` object to `Entity`: * Only add `Data object` to `Entity` if process has defined `flow_collection` field * Add object to existing `Entity`, if all paren...
[ "def", "create_entity", "(", "self", ")", ":", "entity_type", "=", "self", ".", "process", ".", "entity_type", "# pylint: disable=no-member", "entity_descriptor_schema", "=", "self", ".", "process", ".", "entity_descriptor_schema", "# pylint: disable=no-member", "entity_i...
Create entity if `flow_collection` is defined in process. Following rules applies for adding `Data` object to `Entity`: * Only add `Data object` to `Entity` if process has defined `flow_collection` field * Add object to existing `Entity`, if all parents that are part of it (but ...
[ "Create", "entity", "if", "flow_collection", "is", "defined", "in", "process", "." ]
python
train
42.359375
invoice-x/invoice2data
src/invoice2data/main.py
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/main.py#L170-L215
def main(args=None): """Take folder or single file and analyze each.""" if args is None: parser = create_parser() args = parser.parse_args() if args.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) input_module = input_ma...
[ "def", "main", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "parser", "=", "create_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "debug", ":", "logging", ".", "basicConfig", "(", "...
Take folder or single file and analyze each.
[ "Take", "folder", "or", "single", "file", "and", "analyze", "each", "." ]
python
train
34.913043
spyder-ide/spyder
spyder/preferences/languageserver.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/preferences/languageserver.py#L512-L516
def selection(self, index): """Update selected row.""" self.update() self.isActiveWindow() self._parent.delete_btn.setEnabled(True)
[ "def", "selection", "(", "self", ",", "index", ")", ":", "self", ".", "update", "(", ")", "self", ".", "isActiveWindow", "(", ")", "self", ".", "_parent", ".", "delete_btn", ".", "setEnabled", "(", "True", ")" ]
Update selected row.
[ "Update", "selected", "row", "." ]
python
train
31.8
Microsoft/malmo
Malmo/samples/Python_examples/human_action.py
https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/human_action.py#L205-L222
def update(self): '''Called at regular intervals to poll the mouse position to send continuous commands.''' if self.action_space == 'continuous': # mouse movement only used for continuous action space if self.world_state and self.world_state.is_mission_running: if self.mouse_...
[ "def", "update", "(", "self", ")", ":", "if", "self", ".", "action_space", "==", "'continuous'", ":", "# mouse movement only used for continuous action space", "if", "self", ".", "world_state", "and", "self", ".", "world_state", ".", "is_mission_running", ":", "if",...
Called at regular intervals to poll the mouse position to send continuous commands.
[ "Called", "at", "regular", "intervals", "to", "poll", "the", "mouse", "position", "to", "send", "continuous", "commands", "." ]
python
train
76.611111
Nic30/hwt
hwt/simulator/vcdHdlSimConfig.py
https://github.com/Nic30/hwt/blob/8cbb399e326da3b22c233b98188a9d08dec057e6/hwt/simulator/vcdHdlSimConfig.py#L24-L33
def vcdTypeInfoForHType(t) -> Tuple[str, int, Callable[[RtlSignalBase, Value], str]]: """ :return: (vcd type name, vcd width) """ if isinstance(t, (SimBitsT, Bits, HBool)): return (VCD_SIG_TYPE.WIRE, t.bit_length(), vcdBitsFormatter) elif isinstance(t, HEnum): return (VCD_SIG_TYPE.RE...
[ "def", "vcdTypeInfoForHType", "(", "t", ")", "->", "Tuple", "[", "str", ",", "int", ",", "Callable", "[", "[", "RtlSignalBase", ",", "Value", "]", ",", "str", "]", "]", ":", "if", "isinstance", "(", "t", ",", "(", "SimBitsT", ",", "Bits", ",", "HBo...
:return: (vcd type name, vcd width)
[ ":", "return", ":", "(", "vcd", "type", "name", "vcd", "width", ")" ]
python
test
37.3
b3j0f/conf
b3j0f/conf/parser/resolver/registry.py
https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/parser/resolver/registry.py#L112-L131
def default(self, value): """Change of resolver name. :param value: new default value to use. :type value: str or callable :raises: KeyError if value is a string not already registered.""" if value is None: if self: value = list(self.keys())[0] ...
[ "def", "default", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "if", "self", ":", "value", "=", "list", "(", "self", ".", "keys", "(", ")", ")", "[", "0", "]", "elif", "not", "isinstance", "(", "value", ",", "string_type...
Change of resolver name. :param value: new default value to use. :type value: str or callable :raises: KeyError if value is a string not already registered.
[ "Change", "of", "resolver", "name", "." ]
python
train
28.75
QInfer/python-qinfer
src/qinfer/derived_models.py
https://github.com/QInfer/python-qinfer/blob/8170c84a0be1723f8c6b09e0d3c7a40a886f1fe3/src/qinfer/derived_models.py#L898-L918
def est_update_covariance(self, modelparams): """ Returns the covariance of the gaussian noise process for one unit step. In the case where the covariance is being learned, the expected covariance matrix is returned. :param modelparams: Shape `(n_models, n_modelparams)`...
[ "def", "est_update_covariance", "(", "self", ",", "modelparams", ")", ":", "if", "self", ".", "_diagonal", ":", "cov", "=", "(", "self", ".", "_fixed_scale", "**", "2", "if", "self", ".", "_has_fixed_covariance", "else", "np", ".", "mean", "(", "modelparam...
Returns the covariance of the gaussian noise process for one unit step. In the case where the covariance is being learned, the expected covariance matrix is returned. :param modelparams: Shape `(n_models, n_modelparams)` shape array of model parameters.
[ "Returns", "the", "covariance", "of", "the", "gaussian", "noise", "process", "for", "one", "unit", "step", ".", "In", "the", "case", "where", "the", "covariance", "is", "being", "learned", "the", "expected", "covariance", "matrix", "is", "returned", ".", ":"...
python
train
46
Qiskit/qiskit-terra
qiskit/transpiler/coupling.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/transpiler/coupling.py#L126-L141
def _compute_distance_matrix(self): """Compute the full distance matrix on pairs of nodes. The distance map self._dist_matrix is computed from the graph using all_pairs_shortest_path_length. """ if not self.is_connected(): raise CouplingError("coupling graph not conn...
[ "def", "_compute_distance_matrix", "(", "self", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "raise", "CouplingError", "(", "\"coupling graph not connected\"", ")", "lengths", "=", "nx", ".", "all_pairs_shortest_path_length", "(", "self", "."...
Compute the full distance matrix on pairs of nodes. The distance map self._dist_matrix is computed from the graph using all_pairs_shortest_path_length.
[ "Compute", "the", "full", "distance", "matrix", "on", "pairs", "of", "nodes", "." ]
python
test
43.6875
Kensuke-Mitsuzawa/JapaneseTokenizers
JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py
https://github.com/Kensuke-Mitsuzawa/JapaneseTokenizers/blob/3bdfb6be73de0f78e5c08f3a51376ad3efa00b6c/JapaneseTokenizer/mecab_wrapper/mecab_wrapper.py#L261-L333
def tokenize(self, sentence, normalized=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=normalize_text): # type: (text_type, bool, bool, bool, bool, Callable[[str], str])->Union[List[str], Tokenized...
[ "def", "tokenize", "(", "self", ",", "sentence", ",", "normalized", "=", "True", ",", "is_feature", "=", "False", ",", "is_surface", "=", "False", ",", "return_list", "=", "False", ",", "func_normalizer", "=", "normalize_text", ")", ":", "# type: (text_type, b...
* What you can do - Call mecab tokenizer, and return tokenized objects
[ "*", "What", "you", "can", "do", "-", "Call", "mecab", "tokenizer", "and", "return", "tokenized", "objects" ]
python
train
41.438356
nchopin/particles
particles/distributions.py
https://github.com/nchopin/particles/blob/3faa97a1073db45c5889eef3e015dd76ef350b52/particles/distributions.py#L250-L256
def posterior(self, x, sigma=1.): """Model is X_1,...,X_n ~ N(theta, sigma^2), theta~self, sigma fixed""" pr0 = 1. / self.scale**2 # prior precision prd = x.size / sigma**2 # data precision varp = 1. / (pr0 + prd) # posterior variance mu = varp * (pr0 * self.loc + prd * x.mean...
[ "def", "posterior", "(", "self", ",", "x", ",", "sigma", "=", "1.", ")", ":", "pr0", "=", "1.", "/", "self", ".", "scale", "**", "2", "# prior precision", "prd", "=", "x", ".", "size", "/", "sigma", "**", "2", "# data precision", "varp", "=", "1.",...
Model is X_1,...,X_n ~ N(theta, sigma^2), theta~self, sigma fixed
[ "Model", "is", "X_1", "...", "X_n", "~", "N", "(", "theta", "sigma^2", ")", "theta~self", "sigma", "fixed" ]
python
train
52.571429
rhgrant10/Groupy
groupy/api/groups.py
https://github.com/rhgrant10/Groupy/blob/ffd8cac57586fa1c218e3b4bfaa531142c3be766/groupy/api/groups.py#L64-L73
def get(self, id): """Get a single group by ID. :param str id: a group ID :return: a group :rtype: :class:`~groupy.api.groups.Group` """ url = utils.urljoin(self.url, id) response = self.session.get(url) return Group(self, **response.data)
[ "def", "get", "(", "self", ",", "id", ")", ":", "url", "=", "utils", ".", "urljoin", "(", "self", ".", "url", ",", "id", ")", "response", "=", "self", ".", "session", ".", "get", "(", "url", ")", "return", "Group", "(", "self", ",", "*", "*", ...
Get a single group by ID. :param str id: a group ID :return: a group :rtype: :class:`~groupy.api.groups.Group`
[ "Get", "a", "single", "group", "by", "ID", "." ]
python
train
29.5
tanghaibao/jcvi
jcvi/projects/age.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/projects/age.py#L464-L496
def extract_twin_values(triples, traits, gender=None): """Calculate the heritability of certain traits in triplets. Parameters ========== triples: (a, b, "Female/Male") triples. The sample IDs are then used to query the traits dictionary. traits: sample_id => value dictionary Retu...
[ "def", "extract_twin_values", "(", "triples", ",", "traits", ",", "gender", "=", "None", ")", ":", "# Construct the pairs of trait values", "traitValuesAbsent", "=", "0", "nanValues", "=", "0", "genderSkipped", "=", "0", "twinValues", "=", "[", "]", "for", "a", ...
Calculate the heritability of certain traits in triplets. Parameters ========== triples: (a, b, "Female/Male") triples. The sample IDs are then used to query the traits dictionary. traits: sample_id => value dictionary Returns ======= tuples of size 2, that contain paired trai...
[ "Calculate", "the", "heritability", "of", "certain", "traits", "in", "triplets", "." ]
python
train
32.484848
SCIP-Interfaces/PySCIPOpt
examples/tutorial/logical.py
https://github.com/SCIP-Interfaces/PySCIPOpt/blob/9c960b40d94a48b0304d73dbe28b467b9c065abe/examples/tutorial/logical.py#L50-L58
def or_constraint(v=0, sense="maximize"): """ OR constraint""" assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__() model, x, y, z = _init() r = model.addVar("r", "B") model.addConsOr([x,y,z], r) model.addCons(x==v) model.setObjective(r, sense=sense) _optimize("OR", model)
[ "def", "or_constraint", "(", "v", "=", "0", ",", "sense", "=", "\"maximize\"", ")", ":", "assert", "v", "in", "[", "0", ",", "1", "]", ",", "\"v must be 0 or 1 instead of %s\"", "%", "v", ".", "__repr__", "(", ")", "model", ",", "x", ",", "y", ",", ...
OR constraint
[ "OR", "constraint" ]
python
train
34.555556
CalebBell/thermo
thermo/thermal_conductivity.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/thermal_conductivity.py#L2025-L2089
def load_all_methods(self): r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, :obj:`all_methods` and obj:`all_methods_P` as a set of...
[ "def", "load_all_methods", "(", "self", ")", ":", "methods", ",", "methods_P", "=", "[", "]", ",", "[", "]", "Tmins", ",", "Tmaxs", "=", "[", "]", ",", "[", "]", "if", "self", ".", "CASRN", "in", "_VDISaturationDict", ":", "methods", ".", "append", ...
r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, :obj:`all_methods` and obj:`all_methods_P` as a set of methods for which the data ...
[ "r", "Method", "which", "picks", "out", "coefficients", "for", "the", "specified", "chemical", "from", "the", "various", "dictionaries", "and", "DataFrames", "storing", "it", ".", "All", "data", "is", "stored", "as", "attributes", ".", "This", "method", "also"...
python
valid
51.8
caseyjlaw/rtpipe
rtpipe/parsecands.py
https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/parsecands.py#L109-L196
def merge_segments(filename, scan, cleanup=True, sizelimit=0): """ Merges cands/noise pkl files from multiple segments to single cands/noise file. Expects segment cands pkls with have (1) state dict and (2) cands dict. Writes tuple state dict and duple of numpy arrays A single pkl written per scan usin...
[ "def", "merge_segments", "(", "filename", ",", "scan", ",", "cleanup", "=", "True", ",", "sizelimit", "=", "0", ")", ":", "workdir", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "fileroot", "=", "os", ".", "path", ".", "basename", "(...
Merges cands/noise pkl files from multiple segments to single cands/noise file. Expects segment cands pkls with have (1) state dict and (2) cands dict. Writes tuple state dict and duple of numpy arrays A single pkl written per scan using root name fileroot. if cleanup, it will remove segments after mer...
[ "Merges", "cands", "/", "noise", "pkl", "files", "from", "multiple", "segments", "to", "single", "cands", "/", "noise", "file", "." ]
python
train
49.261364
clchiou/startup
startup.py
https://github.com/clchiou/startup/blob/13cbf3ce1deffbc10d33a5f64c396a73129a5929/startup.py#L185-L218
def call(self, **kwargs): """Call all the functions that have previously been added to the dependency graph in topological and lexicographical order, and then return variables in a ``dict``. You may provide variable values with keyword arguments. These values will be written an...
[ "def", "call", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'funcs'", ")", ":", "raise", "StartupError", "(", "'startup cannot be called again'", ")", "for", "name", ",", "var", "in", "self", ".", "variables"...
Call all the functions that have previously been added to the dependency graph in topological and lexicographical order, and then return variables in a ``dict``. You may provide variable values with keyword arguments. These values will be written and can satisfy dependencies. ...
[ "Call", "all", "the", "functions", "that", "have", "previously", "been", "added", "to", "the", "dependency", "graph", "in", "topological", "and", "lexicographical", "order", "and", "then", "return", "variables", "in", "a", "dict", "." ]
python
train
42.117647
tjcsl/cslbot
cslbot/helpers/reloader.py
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/reloader.py#L50-L96
def do_reload(bot, target, cmdargs, server_send=None): """The reloading magic. - First, reload handler.py. - Then make copies of all the handler data we want to keep. - Create a new handler and restore all the data. """ def send(msg): if server_send is not None: server_sen...
[ "def", "do_reload", "(", "bot", ",", "target", ",", "cmdargs", ",", "server_send", "=", "None", ")", ":", "def", "send", "(", "msg", ")", ":", "if", "server_send", "is", "not", "None", ":", "server_send", "(", "\"%s\\n\"", "%", "msg", ")", "else", ":...
The reloading magic. - First, reload handler.py. - Then make copies of all the handler data we want to keep. - Create a new handler and restore all the data.
[ "The", "reloading", "magic", "." ]
python
train
33.446809
rameshg87/pyremotevbox
pyremotevbox/ZSI/wstools/WSDLTools.py
https://github.com/rameshg87/pyremotevbox/blob/123dffff27da57c8faa3ac1dd4c68b1cf4558b1a/pyremotevbox/ZSI/wstools/WSDLTools.py#L1494-L1501
def addOutHeaderInfo(self, name, type, namespace, element_type=0, mustUnderstand=0): """Add an output SOAP header description to the call info.""" headerinfo = HeaderInfo(name, type, namespace, element_type) if mustUnderstand: headerinfo.mustUnderstand = 1 ...
[ "def", "addOutHeaderInfo", "(", "self", ",", "name", ",", "type", ",", "namespace", ",", "element_type", "=", "0", ",", "mustUnderstand", "=", "0", ")", ":", "headerinfo", "=", "HeaderInfo", "(", "name", ",", "type", ",", "namespace", ",", "element_type", ...
Add an output SOAP header description to the call info.
[ "Add", "an", "output", "SOAP", "header", "description", "to", "the", "call", "info", "." ]
python
train
47.375
F5Networks/f5-common-python
f5/bigip/mixins.py
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/mixins.py#L237-L241
def exec_cmd(self, command, **kwargs): """Wrapper method that can be changed in the inheriting classes.""" self._is_allowed_command(command) self._check_command_parameters(**kwargs) return self._exec_cmd(command, **kwargs)
[ "def", "exec_cmd", "(", "self", ",", "command", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_is_allowed_command", "(", "command", ")", "self", ".", "_check_command_parameters", "(", "*", "*", "kwargs", ")", "return", "self", ".", "_exec_cmd", "(", "...
Wrapper method that can be changed in the inheriting classes.
[ "Wrapper", "method", "that", "can", "be", "changed", "in", "the", "inheriting", "classes", "." ]
python
train
50
kislyuk/aegea
aegea/packages/github3/session.py
https://github.com/kislyuk/aegea/blob/94957e9dba036eae3052e2662c208b259c08399a/aegea/packages/github3/session.py#L136-L145
def no_auth(self): """Unset authentication temporarily as a context manager.""" old_basic_auth, self.auth = self.auth, None old_token_auth = self.headers.pop('Authorization', None) yield self.auth = old_basic_auth if old_token_auth: self.headers['Authorizati...
[ "def", "no_auth", "(", "self", ")", ":", "old_basic_auth", ",", "self", ".", "auth", "=", "self", ".", "auth", ",", "None", "old_token_auth", "=", "self", ".", "headers", ".", "pop", "(", "'Authorization'", ",", "None", ")", "yield", "self", ".", "auth...
Unset authentication temporarily as a context manager.
[ "Unset", "authentication", "temporarily", "as", "a", "context", "manager", "." ]
python
train
33.2
log2timeline/plaso
plaso/parsers/interface.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/interface.py#L254-L274
def Parse(self, parser_mediator, file_object): """Parses a single file-like object. Args: parser_mediator (ParserMediator): a parser mediator. file_object (dvfvs.FileIO): a file-like object to parse. Raises: UnableToParseFile: when the file cannot be parsed. """ if not file_objec...
[ "def", "Parse", "(", "self", ",", "parser_mediator", ",", "file_object", ")", ":", "if", "not", "file_object", ":", "raise", "errors", ".", "UnableToParseFile", "(", "'Invalid file object'", ")", "if", "self", ".", "_INITIAL_FILE_OFFSET", "is", "not", "None", ...
Parses a single file-like object. Args: parser_mediator (ParserMediator): a parser mediator. file_object (dvfvs.FileIO): a file-like object to parse. Raises: UnableToParseFile: when the file cannot be parsed.
[ "Parses", "a", "single", "file", "-", "like", "object", "." ]
python
train
30.52381
luckydonald/pytgbot
pytgbot/api_types/sendable/inline.py
https://github.com/luckydonald/pytgbot/blob/67f4b5a1510d4583d40b5477e876b1ef0eb8971b/pytgbot/api_types/sendable/inline.py#L3958-L3971
def to_array(self): """ Serializes this InputTextMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(InputTextMessageContent, self).to_array() array['message_text'] = u(self.message_text) # py2: type ...
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "InputTextMessageContent", ",", "self", ")", ".", "to_array", "(", ")", "array", "[", "'message_text'", "]", "=", "u", "(", "self", ".", "message_text", ")", "# py2: type unicode, py3: typ...
Serializes this InputTextMessageContent to a dictionary. :return: dictionary representation of this object. :rtype: dict
[ "Serializes", "this", "InputTextMessageContent", "to", "a", "dictionary", "." ]
python
train
45
manahl/arctic
arctic/date/_util.py
https://github.com/manahl/arctic/blob/57e110b6e182dbab00e7e214dc26f7d9ec47c120/arctic/date/_util.py#L147-L155
def ms_to_datetime(ms, tzinfo=None): """Convert a millisecond time value to an offset-aware Python datetime object.""" if not isinstance(ms, (int, long)): raise TypeError('expected integer, not %s' % type(ms)) if tzinfo is None: tzinfo = mktz() return datetime.datetime.fromtimestamp(ms...
[ "def", "ms_to_datetime", "(", "ms", ",", "tzinfo", "=", "None", ")", ":", "if", "not", "isinstance", "(", "ms", ",", "(", "int", ",", "long", ")", ")", ":", "raise", "TypeError", "(", "'expected integer, not %s'", "%", "type", "(", "ms", ")", ")", "i...
Convert a millisecond time value to an offset-aware Python datetime object.
[ "Convert", "a", "millisecond", "time", "value", "to", "an", "offset", "-", "aware", "Python", "datetime", "object", "." ]
python
train
36.444444
tensorflow/tensor2tensor
tensor2tensor/models/research/lm_experiments.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/lm_experiments.py#L130-L137
def lmx_moe_h1k_f4k_x32(): """Transformer with mixture of experts. 890M Params.""" hparams = lmx_h1k_f4k() hparams.ffn_layer = "local_moe_tpu" hparams.moe_num_experts = 32 hparams.weight_dtype = "bfloat16" hparams.batch_size = 8192 return hparams
[ "def", "lmx_moe_h1k_f4k_x32", "(", ")", ":", "hparams", "=", "lmx_h1k_f4k", "(", ")", "hparams", ".", "ffn_layer", "=", "\"local_moe_tpu\"", "hparams", ".", "moe_num_experts", "=", "32", "hparams", ".", "weight_dtype", "=", "\"bfloat16\"", "hparams", ".", "batch...
Transformer with mixture of experts. 890M Params.
[ "Transformer", "with", "mixture", "of", "experts", ".", "890M", "Params", "." ]
python
train
31.75
hyperledger/indy-sdk
docs/how-tos/rotate-key/python/rotate_key.py
https://github.com/hyperledger/indy-sdk/blob/55240dc170308d7883c48f03f308130a6d077be6/docs/how-tos/rotate-key/python/rotate_key.py#L33-L37
def print_log(value_color="", value_noncolor=""): """set the colors for text.""" HEADER = '\033[92m' ENDC = '\033[0m' print(HEADER + value_color + ENDC + str(value_noncolor))
[ "def", "print_log", "(", "value_color", "=", "\"\"", ",", "value_noncolor", "=", "\"\"", ")", ":", "HEADER", "=", "'\\033[92m'", "ENDC", "=", "'\\033[0m'", "print", "(", "HEADER", "+", "value_color", "+", "ENDC", "+", "str", "(", "value_noncolor", ")", ")"...
set the colors for text.
[ "set", "the", "colors", "for", "text", "." ]
python
train
37.2
caffeinehit/django-follow
follow/models.py
https://github.com/caffeinehit/django-follow/blob/765a4795e58f57fbf96efdb7838d0c7222db2e56/follow/models.py#L50-L62
def get_follows(self, model_or_obj_or_qs): """ Returns all the followers of a model, an object or a queryset. """ fname = self.fname(model_or_obj_or_qs) if isinstance(model_or_obj_or_qs, QuerySet): return self.filter(**{'%s__in' % fname: model_or_obj_or_qs}) ...
[ "def", "get_follows", "(", "self", ",", "model_or_obj_or_qs", ")", ":", "fname", "=", "self", ".", "fname", "(", "model_or_obj_or_qs", ")", "if", "isinstance", "(", "model_or_obj_or_qs", ",", "QuerySet", ")", ":", "return", "self", ".", "filter", "(", "*", ...
Returns all the followers of a model, an object or a queryset.
[ "Returns", "all", "the", "followers", "of", "a", "model", "an", "object", "or", "a", "queryset", "." ]
python
train
36.153846
google/grr
grr/core/grr_response_core/lib/rdfvalues/structs.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/rdfvalues/structs.py#L879-L882
def GetDefault(self, container=None): """Return boolean value.""" return rdfvalue.RDFBool( super(ProtoBoolean, self).GetDefault(container=container))
[ "def", "GetDefault", "(", "self", ",", "container", "=", "None", ")", ":", "return", "rdfvalue", ".", "RDFBool", "(", "super", "(", "ProtoBoolean", ",", "self", ")", ".", "GetDefault", "(", "container", "=", "container", ")", ")" ]
Return boolean value.
[ "Return", "boolean", "value", "." ]
python
train
40.5
rueckstiess/mtools
mtools/mplotqueries/plottypes/event_type.py
https://github.com/rueckstiess/mtools/blob/a6a22910c3569c0c8a3908660ca218a4557e4249/mtools/mplotqueries/plottypes/event_type.py#L97-L109
def color_map(cls, group): print("Group %s" % group) """ Change default color behavior. Map certain states always to the same colors (similar to MMS). """ try: state_idx = cls.states.index(group) except ValueError: # on any unexpected stat...
[ "def", "color_map", "(", "cls", ",", "group", ")", ":", "print", "(", "\"Group %s\"", "%", "group", ")", "try", ":", "state_idx", "=", "cls", ".", "states", ".", "index", "(", "group", ")", "except", "ValueError", ":", "# on any unexpected state, return blac...
Change default color behavior. Map certain states always to the same colors (similar to MMS).
[ "Change", "default", "color", "behavior", "." ]
python
train
30.923077
saltstack/salt
salt/modules/virt.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L5135-L5157
def pool_undefine(name, **kwargs): ''' Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param ...
[ "def", "pool_undefine", "(", "name", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "__get_conn", "(", "*", "*", "kwargs", ")", "try", ":", "pool", "=", "conn", ".", "storagePoolLookupByName", "(", "name", ")", "return", "not", "bool", "(", "pool", ...
Remove a defined libvirt storage pool. The pool needs to be stopped before calling. :param name: libvirt storage pool name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding ...
[ "Remove", "a", "defined", "libvirt", "storage", "pool", ".", "The", "pool", "needs", "to", "be", "stopped", "before", "calling", "." ]
python
train
28.173913
woolfson-group/isambard
isambard/ampal/ligands.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/ligands.py#L45-L50
def category_count(self): """Returns the number of categories in `categories`.""" category_dict = self.categories count_dict = {category: len( category_dict[category]) for category in category_dict} return count_dict
[ "def", "category_count", "(", "self", ")", ":", "category_dict", "=", "self", ".", "categories", "count_dict", "=", "{", "category", ":", "len", "(", "category_dict", "[", "category", "]", ")", "for", "category", "in", "category_dict", "}", "return", "count_...
Returns the number of categories in `categories`.
[ "Returns", "the", "number", "of", "categories", "in", "categories", "." ]
python
train
42.5
pip-services3-python/pip-services3-components-python
pip_services3_components/count/CachedCounters.py
https://github.com/pip-services3-python/pip-services3-components-python/blob/1de9c1bb544cf1891111e9a5f5d67653f62c9b52/pip_services3_components/count/CachedCounters.py#L85-L94
def clear_all(self): """ Clears (resets) all counters. """ self._lock.acquire() try: self._cache = {} self._updated = False finally: self._lock.release()
[ "def", "clear_all", "(", "self", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "_cache", "=", "{", "}", "self", ".", "_updated", "=", "False", "finally", ":", "self", ".", "_lock", ".", "release", "(", ")" ]
Clears (resets) all counters.
[ "Clears", "(", "resets", ")", "all", "counters", "." ]
python
train
22.8
gem/oq-engine
openquake/commands/plot.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/commands/plot.py#L92-L117
def make_figure_uhs(extractors, what): """ $ oq plot 'uhs?kind=mean&site_id=0' """ import matplotlib.pyplot as plt fig = plt.figure() got = {} # (calc_id, kind) -> curves for i, ex in enumerate(extractors): uhs = ex.get(what) for kind in uhs.kind: got[ex.calc_id,...
[ "def", "make_figure_uhs", "(", "extractors", ",", "what", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "fig", "=", "plt", ".", "figure", "(", ")", "got", "=", "{", "}", "# (calc_id, kind) -> curves", "for", "i", ",", "ex", "in", "enumera...
$ oq plot 'uhs?kind=mean&site_id=0'
[ "$", "oq", "plot", "uhs?kind", "=", "mean&site_id", "=", "0" ]
python
train
33.923077
eagleflo/adjutant
adjutant.py
https://github.com/eagleflo/adjutant/blob/85d800d9979fa122e0888af48c2e6a697f9da458/adjutant.py#L109-L119
def vlq2int(data): """Read one VLQ-encoded integer value from an input data stream.""" # The VLQ is little-endian. byte = ord(data.read(1)) value = byte & 0x7F shift = 1 while byte & 0x80 != 0: byte = ord(data.read(1)) value = ((byte & 0x7F) << shift * 7) | value shift +...
[ "def", "vlq2int", "(", "data", ")", ":", "# The VLQ is little-endian.", "byte", "=", "ord", "(", "data", ".", "read", "(", "1", ")", ")", "value", "=", "byte", "&", "0x7F", "shift", "=", "1", "while", "byte", "&", "0x80", "!=", "0", ":", "byte", "=...
Read one VLQ-encoded integer value from an input data stream.
[ "Read", "one", "VLQ", "-", "encoded", "integer", "value", "from", "an", "input", "data", "stream", "." ]
python
test
30
santoshphilip/eppy
eppy/EPlusInterfaceFunctions/mylib2.py
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/EPlusInterfaceFunctions/mylib2.py#L175-L195
def tree2doe(str1): """tree2doe""" retstuff = makedoedict(str1) ddict = makedoetree(retstuff[0], retstuff[1]) ddict = retstuff[0] retstuff[1] = {}# don't need it anymore str1 = ''#just re-using it l1list = list(ddict.keys()) l1list.sort() for i in range(0, len(l1list)): str1...
[ "def", "tree2doe", "(", "str1", ")", ":", "retstuff", "=", "makedoedict", "(", "str1", ")", "ddict", "=", "makedoetree", "(", "retstuff", "[", "0", "]", ",", "retstuff", "[", "1", "]", ")", "ddict", "=", "retstuff", "[", "0", "]", "retstuff", "[", ...
tree2doe
[ "tree2doe" ]
python
train
32.047619
ArangoDB-Community/pyArango
pyArango/collection.py
https://github.com/ArangoDB-Community/pyArango/blob/dd72e5f6c540e5e148943d615ddf7553bb78ce0b/pyArango/collection.py#L695-L726
def getEdges(self, vertex, inEdges = True, outEdges = True, rawResults = False) : """returns in, out, or both edges liked to a given document. vertex can be either a Document object or a string for an _id. If rawResults a arango results will be return as fetched, if false, will return a liste of Edge ob...
[ "def", "getEdges", "(", "self", ",", "vertex", ",", "inEdges", "=", "True", ",", "outEdges", "=", "True", ",", "rawResults", "=", "False", ")", ":", "if", "isinstance", "(", "vertex", ",", "Document", ")", ":", "vId", "=", "vertex", ".", "_id", "elif...
returns in, out, or both edges liked to a given document. vertex can be either a Document object or a string for an _id. If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects
[ "returns", "in", "out", "or", "both", "edges", "liked", "to", "a", "given", "document", ".", "vertex", "can", "be", "either", "a", "Document", "object", "or", "a", "string", "for", "an", "_id", ".", "If", "rawResults", "a", "arango", "results", "will", ...
python
train
41.03125
theelous3/asks
asks/request_object.py
https://github.com/theelous3/asks/blob/ea522ea971ecb031d488a6301dc2718516cadcd6/asks/request_object.py#L126-L230
async def make_request(self, redirect=False): ''' Acts as the central hub for preparing requests to be sent, and returning them upon completion. Generally just pokes through self's attribs and makes decisions about what to do. Returns: sock: The socket to be returned...
[ "async", "def", "make_request", "(", "self", ",", "redirect", "=", "False", ")", ":", "h11_connection", "=", "h11", ".", "Connection", "(", "our_role", "=", "h11", ".", "CLIENT", ")", "(", "self", ".", "scheme", ",", "self", ".", "host", ",", "self", ...
Acts as the central hub for preparing requests to be sent, and returning them upon completion. Generally just pokes through self's attribs and makes decisions about what to do. Returns: sock: The socket to be returned to the calling session's pool. Respon...
[ "Acts", "as", "the", "central", "hub", "for", "preparing", "requests", "to", "be", "sent", "and", "returning", "them", "upon", "completion", ".", "Generally", "just", "pokes", "through", "self", "s", "attribs", "and", "makes", "decisions", "about", "what", "...
python
train
38.619048
soasme/rio
rio/models/utils.py
https://github.com/soasme/rio/blob/f722eb0ff4b0382bceaff77737f0b87cb78429e7/rio/models/utils.py#L43-L61
def ins2dict(ins, kind=''): """Turn a SQLAlchemy Model instance to dict. :param ins: a SQLAlchemy instance. :param kind: specify which kind of dict tranformer should be called. :return: dict, instance data. If model has defined `to_xxx_dict`, then ins2dict(ins, 'xxx') will call `model.to_xxx_d...
[ "def", "ins2dict", "(", "ins", ",", "kind", "=", "''", ")", ":", "if", "kind", "and", "hasattr", "(", "ins", ",", "'to_%s_dict'", "%", "kind", ")", ":", "return", "getattr", "(", "ins", ",", "'to_%s_dict'", "%", "kind", ")", "(", ")", "elif", "hasa...
Turn a SQLAlchemy Model instance to dict. :param ins: a SQLAlchemy instance. :param kind: specify which kind of dict tranformer should be called. :return: dict, instance data. If model has defined `to_xxx_dict`, then ins2dict(ins, 'xxx') will call `model.to_xxx_dict()`. Default kind is ''. If...
[ "Turn", "a", "SQLAlchemy", "Model", "instance", "to", "dict", "." ]
python
train
35.263158
dpkp/kafka-python
kafka/producer/sender.py
https://github.com/dpkp/kafka-python/blob/f6a8a38937688ea2cc5dc13d3d1039493be5c9b5/kafka/producer/sender.py#L162-L166
def initiate_close(self): """Start closing the sender (won't complete until all data is sent).""" self._running = False self._accumulator.close() self.wakeup()
[ "def", "initiate_close", "(", "self", ")", ":", "self", ".", "_running", "=", "False", "self", ".", "_accumulator", ".", "close", "(", ")", "self", ".", "wakeup", "(", ")" ]
Start closing the sender (won't complete until all data is sent).
[ "Start", "closing", "the", "sender", "(", "won", "t", "complete", "until", "all", "data", "is", "sent", ")", "." ]
python
train
37.4
nickmckay/LiPD-utilities
Python/lipd/__init__.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L649-L665
def showLipds(D=None): """ Display the dataset names of a given LiPD data | Example | lipd.showLipds(D) :pararm dict D: LiPD data :return none: """ if not D: print("Error: LiPD data not provided. Pass LiPD data into the function.") else: print(json.dumps(D.keys(), ...
[ "def", "showLipds", "(", "D", "=", "None", ")", ":", "if", "not", "D", ":", "print", "(", "\"Error: LiPD data not provided. Pass LiPD data into the function.\"", ")", "else", ":", "print", "(", "json", ".", "dumps", "(", "D", ".", "keys", "(", ")", ",", "i...
Display the dataset names of a given LiPD data | Example | lipd.showLipds(D) :pararm dict D: LiPD data :return none:
[ "Display", "the", "dataset", "names", "of", "a", "given", "LiPD", "data" ]
python
train
19.176471
ejeschke/ginga
ginga/examples/gl/example_wireframe.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/examples/gl/example_wireframe.py#L110-L128
def get_wireframe(viewer, x, y, z, **kwargs): """Produce a compound object of paths implementing a wireframe. x, y, z are expected to be 2D arrays of points making up the mesh. """ # TODO: something like this would make a great utility function # for ginga n, m = x.shape objs = [] for i ...
[ "def", "get_wireframe", "(", "viewer", ",", "x", ",", "y", ",", "z", ",", "*", "*", "kwargs", ")", ":", "# TODO: something like this would make a great utility function", "# for ginga", "n", ",", "m", "=", "x", ".", "shape", "objs", "=", "[", "]", "for", "...
Produce a compound object of paths implementing a wireframe. x, y, z are expected to be 2D arrays of points making up the mesh.
[ "Produce", "a", "compound", "object", "of", "paths", "implementing", "a", "wireframe", ".", "x", "y", "z", "are", "expected", "to", "be", "2D", "arrays", "of", "points", "making", "up", "the", "mesh", "." ]
python
train
36
sbarham/dsrt
dsrt/data/SampleSet.py
https://github.com/sbarham/dsrt/blob/bc664739f2f52839461d3e72773b71146fd56a9a/dsrt/data/SampleSet.py#L36-L40
def save_sampleset(self, f, name): '''Serialize the sampleset to file using the HDF5 format. Name is usually in {train, test}.''' f.create_dataset(name + '_encoder_x', data=self.encoder_x) f.create_dataset(name + '_decoder_x', data=self.decoder_x) f.create_dataset(name + '_decoder_y', da...
[ "def", "save_sampleset", "(", "self", ",", "f", ",", "name", ")", ":", "f", ".", "create_dataset", "(", "name", "+", "'_encoder_x'", ",", "data", "=", "self", ".", "encoder_x", ")", "f", ".", "create_dataset", "(", "name", "+", "'_decoder_x'", ",", "da...
Serialize the sampleset to file using the HDF5 format. Name is usually in {train, test}.
[ "Serialize", "the", "sampleset", "to", "file", "using", "the", "HDF5", "format", ".", "Name", "is", "usually", "in", "{", "train", "test", "}", "." ]
python
train
66.8
tjcsl/cslbot
cslbot/helpers/acl.py
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/acl.py#L24-L45
def set_admin(msg, handler): """Handle admin verification responses from NickServ. | If NickServ tells us that the nick is authed, mark it as verified. """ if handler.config['feature']['servicestype'] == "ircservices": match = re.match("STATUS (.*) ([0-3])", msg) elif handler.config['featu...
[ "def", "set_admin", "(", "msg", ",", "handler", ")", ":", "if", "handler", ".", "config", "[", "'feature'", "]", "[", "'servicestype'", "]", "==", "\"ircservices\"", ":", "match", "=", "re", ".", "match", "(", "\"STATUS (.*) ([0-3])\"", ",", "msg", ")", ...
Handle admin verification responses from NickServ. | If NickServ tells us that the nick is authed, mark it as verified.
[ "Handle", "admin", "verification", "responses", "from", "NickServ", "." ]
python
train
40.090909
Neurita/boyle
boyle/mhd/write.py
https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/mhd/write.py#L73-L147
def write_mhd_file(filename, data, shape=None, meta_dict=None): """ Write the `data` and `meta_dict` in two files with names that use `filename` as a prefix. Parameters ---------- filename: str Path to the output file. This is going to be used as a preffix. Two files will be...
[ "def", "write_mhd_file", "(", "filename", ",", "data", ",", "shape", "=", "None", ",", "meta_dict", "=", "None", ")", ":", "# check its extension", "ext", "=", "get_extension", "(", "filename", ")", "fname", "=", "op", ".", "basename", "(", "filename", ")"...
Write the `data` and `meta_dict` in two files with names that use `filename` as a prefix. Parameters ---------- filename: str Path to the output file. This is going to be used as a preffix. Two files will be created, one with a '.mhd' extension and another with '.raw'. I...
[ "Write", "the", "data", "and", "meta_dict", "in", "two", "files", "with", "names", "that", "use", "filename", "as", "a", "prefix", "." ]
python
valid
34.213333
OLC-Bioinformatics/sipprverse
cgecore/utility.py
https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/cgecore/utility.py#L576-L584
def copy_dir(src, dst): """ this function will simply copy the file from the source path to the dest path given as input """ try: debug.log("copy dir from "+ src, "to "+ dst) shutil.copytree(src, dst) except Exception as e: debug.log("Error: happened while copying!\n%s\n"%e)
[ "def", "copy_dir", "(", "src", ",", "dst", ")", ":", "try", ":", "debug", ".", "log", "(", "\"copy dir from \"", "+", "src", ",", "\"to \"", "+", "dst", ")", "shutil", ".", "copytree", "(", "src", ",", "dst", ")", "except", "Exception", "as", "e", ...
this function will simply copy the file from the source path to the dest path given as input
[ "this", "function", "will", "simply", "copy", "the", "file", "from", "the", "source", "path", "to", "the", "dest", "path", "given", "as", "input" ]
python
train
33.333333
tumblr/pytumblr
pytumblr/__init__.py
https://github.com/tumblr/pytumblr/blob/4a5cd7c4b8ae78d12811d9fd52620afa1692a415/pytumblr/__init__.py#L372-L389
def create_chat(self, blogname, **kwargs): """ Create a chat post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a st...
[ "def", "create_chat", "(", "self", ",", "blogname", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "\"type\"", ":", "\"chat\"", "}", ")", "return", "self", ".", "_send_post", "(", "blogname", ",", "kwargs", ")" ]
Create a chat post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a string, the customized tweet that you want :param date: a...
[ "Create", "a", "chat", "post", "on", "a", "blog" ]
python
train
47.944444
tylertreat/BigQuery-Python
bigquery/client.py
https://github.com/tylertreat/BigQuery-Python/blob/88d99de42d954d49fc281460068f0e95003da098/bigquery/client.py#L2007-L2049
def dataset_resource(self, ref_id, friendly_name=None, description=None, access=None, location=None, project_id=None): """See https://developers.google.com/bigquery/docs/reference/v2/datasets#resource Parameters ---------- ref_id : str Datase...
[ "def", "dataset_resource", "(", "self", ",", "ref_id", ",", "friendly_name", "=", "None", ",", "description", "=", "None", ",", "access", "=", "None", ",", "location", "=", "None", ",", "project_id", "=", "None", ")", ":", "project_id", "=", "self", ".",...
See https://developers.google.com/bigquery/docs/reference/v2/datasets#resource Parameters ---------- ref_id : str Dataset id (the reference id, not the integer id) friendly_name : str, optional An optional descriptive name for the dataset ...
[ "See", "https", ":", "//", "developers", ".", "google", ".", "com", "/", "bigquery", "/", "docs", "/", "reference", "/", "v2", "/", "datasets#resource" ]
python
train
32.906977
baccuslab/shannon
shannon/bottleneck.py
https://github.com/baccuslab/shannon/blob/38abb4d9e53208ffd1c4149ef9fdf3abceccac48/shannon/bottleneck.py#L31-L38
def change_response(x, prob, index): ''' change every response in x that matches 'index' by randomly sampling from prob ''' #pdb.set_trace() N = (x==index).sum() #x[x==index]=9 x[x==index] = dist.sample(N)
[ "def", "change_response", "(", "x", ",", "prob", ",", "index", ")", ":", "#pdb.set_trace()", "N", "=", "(", "x", "==", "index", ")", ".", "sum", "(", ")", "#x[x==index]=9", "x", "[", "x", "==", "index", "]", "=", "dist", ".", "sample", "(", "N", ...
change every response in x that matches 'index' by randomly sampling from prob
[ "change", "every", "response", "in", "x", "that", "matches", "index", "by", "randomly", "sampling", "from", "prob" ]
python
train
28.25
BlueBrain/NeuroM
neurom/morphmath.py
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/morphmath.py#L129-L139
def scalar_projection(v1, v2): '''compute the scalar projection of v1 upon v2 Args: v1, v2: iterable indices 0, 1, 2 corresponding to cartesian coordinates Returns: 3-vector of the projection of point p onto the direction of v ''' return np.dot(v1, v2) / np.linalg.norm(v2)
[ "def", "scalar_projection", "(", "v1", ",", "v2", ")", ":", "return", "np", ".", "dot", "(", "v1", ",", "v2", ")", "/", "np", ".", "linalg", ".", "norm", "(", "v2", ")" ]
compute the scalar projection of v1 upon v2 Args: v1, v2: iterable indices 0, 1, 2 corresponding to cartesian coordinates Returns: 3-vector of the projection of point p onto the direction of v
[ "compute", "the", "scalar", "projection", "of", "v1", "upon", "v2" ]
python
train
28.090909
log2timeline/plaso
plaso/engine/processing_status.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/engine/processing_status.py#L471-L518
def UpdateWorkerStatus( self, identifier, status, pid, used_memory, display_name, number_of_consumed_sources, number_of_produced_sources, number_of_consumed_events, number_of_produced_events, number_of_consumed_event_tags, number_of_produced_event_tags, number_of_consumed_reports, number_o...
[ "def", "UpdateWorkerStatus", "(", "self", ",", "identifier", ",", "status", ",", "pid", ",", "used_memory", ",", "display_name", ",", "number_of_consumed_sources", ",", "number_of_produced_sources", ",", "number_of_consumed_events", ",", "number_of_produced_events", ",", ...
Updates the status of a worker. Args: identifier (str): worker identifier. status (str): human readable status of the worker e.g. 'Idle'. pid (int): process identifier (PID). used_memory (int): size of used memory in bytes. display_name (str): human readable of the file entry currentl...
[ "Updates", "the", "status", "of", "a", "worker", "." ]
python
train
48.854167