repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
librosa/librosa
librosa/beat.py
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/beat.py#L408-L414
def __beat_local_score(onset_envelope, period): '''Construct the local score for an onset envlope and given period''' window = np.exp(-0.5 * (np.arange(-period, period+1)*32.0/period)**2) return scipy.signal.convolve(__normalize_onsets(onset_envelope), window, ...
[ "def", "__beat_local_score", "(", "onset_envelope", ",", "period", ")", ":", "window", "=", "np", ".", "exp", "(", "-", "0.5", "*", "(", "np", ".", "arange", "(", "-", "period", ",", "period", "+", "1", ")", "*", "32.0", "/", "period", ")", "**", ...
Construct the local score for an onset envlope and given period
[ "Construct", "the", "local", "score", "for", "an", "onset", "envlope", "and", "given", "period" ]
python
test
CalebBell/thermo
thermo/utils.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/utils.py#L427-L489
def phase_identification_parameter(V, dP_dT, dP_dV, d2P_dV2, d2P_dVdT): r'''Calculate the Phase Identification Parameter developed in [1]_ for the accurate and efficient determination of whether a fluid is a liquid or a gas based on the results of an equation of state. For supercritical conditions, thi...
[ "def", "phase_identification_parameter", "(", "V", ",", "dP_dT", ",", "dP_dV", ",", "d2P_dV2", ",", "d2P_dVdT", ")", ":", "return", "V", "*", "(", "d2P_dVdT", "/", "dP_dT", "-", "d2P_dV2", "/", "dP_dV", ")" ]
r'''Calculate the Phase Identification Parameter developed in [1]_ for the accurate and efficient determination of whether a fluid is a liquid or a gas based on the results of an equation of state. For supercritical conditions, this provides a good method for choosing which property correlations to us...
[ "r", "Calculate", "the", "Phase", "Identification", "Parameter", "developed", "in", "[", "1", "]", "_", "for", "the", "accurate", "and", "efficient", "determination", "of", "whether", "a", "fluid", "is", "a", "liquid", "or", "a", "gas", "based", "on", "the...
python
valid
astroswego/plotypus
src/plotypus/lightcurve.py
https://github.com/astroswego/plotypus/blob/b1162194ca1d4f6c00e79afe3e6fb40f0eaffcb9/src/plotypus/lightcurve.py#L411-L492
def plot_lightcurve(name, lightcurve, period, data, output='.', legend=False, sanitize_latex=False, color=True, n_phases=100, err_const=0.005, **kwargs): """plot_lightcurve(name, lightcurve, period, data, output='.', legend=False, color...
[ "def", "plot_lightcurve", "(", "name", ",", "lightcurve", ",", "period", ",", "data", ",", "output", "=", "'.'", ",", "legend", "=", "False", ",", "sanitize_latex", "=", "False", ",", "color", "=", "True", ",", "n_phases", "=", "100", ",", "err_const", ...
plot_lightcurve(name, lightcurve, period, data, output='.', legend=False, color=True, n_phases=100, err_const=0.005, **kwargs) Save a plot of the given *lightcurve* to directory *output*. **Parameters** name : str Name of the star. Used in filename and plot title. lightcurve : array-like, sha...
[ "plot_lightcurve", "(", "name", "lightcurve", "period", "data", "output", "=", ".", "legend", "=", "False", "color", "=", "True", "n_phases", "=", "100", "err_const", "=", "0", ".", "005", "**", "kwargs", ")" ]
python
train
hydraplatform/hydra-base
hydra_base/util/__init__.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/__init__.py#L220-L236
def get_layout_as_string(layout): """ Take a dict or string and return a string. The dict will be json dumped. The string will json parsed to check for json validity. In order to deal with strings which have been json encoded multiple times, keep json decoding until a dict is...
[ "def", "get_layout_as_string", "(", "layout", ")", ":", "if", "isinstance", "(", "layout", ",", "dict", ")", ":", "return", "json", ".", "dumps", "(", "layout", ")", "if", "(", "isinstance", "(", "layout", ",", "six", ".", "string_types", ")", ")", ":"...
Take a dict or string and return a string. The dict will be json dumped. The string will json parsed to check for json validity. In order to deal with strings which have been json encoded multiple times, keep json decoding until a dict is retrieved or until a non-json structure is identi...
[ "Take", "a", "dict", "or", "string", "and", "return", "a", "string", ".", "The", "dict", "will", "be", "json", "dumped", ".", "The", "string", "will", "json", "parsed", "to", "check", "for", "json", "validity", ".", "In", "order", "to", "deal", "with",...
python
train
antonybholmes/libdna
libdna/decode.py
https://github.com/antonybholmes/libdna/blob/96badfd33c8896c799b1c633bb9fb75cec65a83a/libdna/decode.py#L340-L377
def dna(self, loc, mask='lower', rev_comp=False, lowercase=False): """ Returns the DNA for a location. Parameters ---------- mask : str, optional Indicate whether masked bases should be represented as is ('upper'), lowercase ('lower'), or as N ('n...
[ "def", "dna", "(", "self", ",", "loc", ",", "mask", "=", "'lower'", ",", "rev_comp", "=", "False", ",", "lowercase", "=", "False", ")", ":", "l", "=", "libdna", ".", "parse_loc", "(", "loc", ")", "ret", "=", "self", ".", "_read_dna", "(", "l", ",...
Returns the DNA for a location. Parameters ---------- mask : str, optional Indicate whether masked bases should be represented as is ('upper'), lowercase ('lower'), or as N ('n') lowercase : bool, optional Indicates whether sequence should be ...
[ "Returns", "the", "DNA", "for", "a", "location", ".", "Parameters", "----------", "mask", ":", "str", "optional", "Indicate", "whether", "masked", "bases", "should", "be", "represented", "as", "is", "(", "upper", ")", "lowercase", "(", "lower", ")", "or", ...
python
train
pkgw/pwkit
pwkit/synphot.py
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/synphot.py#L333-L344
def mag_to_fnu(self, mag): """Convert a magnitude in this band to a f_ν flux density. It is assumed that the magnitude has been computed in the appropriate photometric system. The definition of "appropriate" will vary from case to case. """ if self.native_flux_kind == '...
[ "def", "mag_to_fnu", "(", "self", ",", "mag", ")", ":", "if", "self", ".", "native_flux_kind", "==", "'flam'", ":", "return", "flam_ang_to_fnu_cgs", "(", "self", ".", "mag_to_flam", "(", "mag", ")", ",", "self", ".", "pivot_wavelength", "(", ")", ")", "r...
Convert a magnitude in this band to a f_ν flux density. It is assumed that the magnitude has been computed in the appropriate photometric system. The definition of "appropriate" will vary from case to case.
[ "Convert", "a", "magnitude", "in", "this", "band", "to", "a", "f_ν", "flux", "density", "." ]
python
train
lvjiyong/configreset
configreset/__init__.py
https://github.com/lvjiyong/configreset/blob/cde0a426e993a6aa483d6934358e61750c944de9/configreset/__init__.py#L286-L306
def _get_value(first, second): """ 数据转化 :param first: :param second: :return: >>> _get_value(1,'2') 2 >>> _get_value([1,2],[2,3]) [1, 2, 3] """ if isinstance(first, list) and isinstance(second, list): return list(set(first).union(set(second))) elif isinstance(fir...
[ "def", "_get_value", "(", "first", ",", "second", ")", ":", "if", "isinstance", "(", "first", ",", "list", ")", "and", "isinstance", "(", "second", ",", "list", ")", ":", "return", "list", "(", "set", "(", "first", ")", ".", "union", "(", "set", "(...
数据转化 :param first: :param second: :return: >>> _get_value(1,'2') 2 >>> _get_value([1,2],[2,3]) [1, 2, 3]
[ "数据转化", ":", "param", "first", ":", ":", "param", "second", ":", ":", "return", ":", ">>>", "_get_value", "(", "1", "2", ")", "2", ">>>", "_get_value", "(", "[", "1", "2", "]", "[", "2", "3", "]", ")", "[", "1", "2", "3", "]" ]
python
train
sdcooke/django_bundles
django_bundles/utils/__init__.py
https://github.com/sdcooke/django_bundles/blob/2810fc455ec7391283792c1f108f4e8340f5d12f/django_bundles/utils/__init__.py#L1-L21
def get_class(class_string): """ Get a class from a dotted string """ split_string = class_string.encode('ascii').split('.') import_path = '.'.join(split_string[:-1]) class_name = split_string[-1] if class_name: try: if import_path: mod = __import__(impor...
[ "def", "get_class", "(", "class_string", ")", ":", "split_string", "=", "class_string", ".", "encode", "(", "'ascii'", ")", ".", "split", "(", "'.'", ")", "import_path", "=", "'.'", ".", "join", "(", "split_string", "[", ":", "-", "1", "]", ")", "class...
Get a class from a dotted string
[ "Get", "a", "class", "from", "a", "dotted", "string" ]
python
train
google/pyringe
pyringe/payload/libpython.py
https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/payload/libpython.py#L223-L260
def proxyval(self, visited): ''' Scrape a value from the inferior process, and try to represent it within the gdb process, whilst (hopefully) avoiding crashes when the remote data is corrupt. Derived classes will override this. For example, a PyIntObject* with ob_ival 4...
[ "def", "proxyval", "(", "self", ",", "visited", ")", ":", "class", "FakeRepr", "(", "object", ")", ":", "\"\"\"\n Class representing a non-descript PyObject* value in the inferior\n process for when we don't have a custom scraper, intended to have\n a san...
Scrape a value from the inferior process, and try to represent it within the gdb process, whilst (hopefully) avoiding crashes when the remote data is corrupt. Derived classes will override this. For example, a PyIntObject* with ob_ival 42 in the inferior process should result i...
[ "Scrape", "a", "value", "from", "the", "inferior", "process", "and", "try", "to", "represent", "it", "within", "the", "gdb", "process", "whilst", "(", "hopefully", ")", "avoiding", "crashes", "when", "the", "remote", "data", "is", "corrupt", "." ]
python
train
mozilla/amo-validator
validator/errorbundler.py
https://github.com/mozilla/amo-validator/blob/0251bfbd7d93106e01ecdb6de5fcd1dc1a180664/validator/errorbundler.py#L263-L271
def get_resource(self, name): 'Retrieves an object that has been stored by another test.' if name in self.resources: return self.resources[name] elif name in self.pushable_resources: return self.pushable_resources[name] else: return False
[ "def", "get_resource", "(", "self", ",", "name", ")", ":", "if", "name", "in", "self", ".", "resources", ":", "return", "self", ".", "resources", "[", "name", "]", "elif", "name", "in", "self", ".", "pushable_resources", ":", "return", "self", ".", "pu...
Retrieves an object that has been stored by another test.
[ "Retrieves", "an", "object", "that", "has", "been", "stored", "by", "another", "test", "." ]
python
train
pyscaffold/configupdater
src/configupdater/configupdater.py
https://github.com/pyscaffold/configupdater/blob/6ebac0b1fa7b8222baacdd4991d18cfc61659f84/src/configupdater/configupdater.py#L478-L492
def set_values(self, values, separator='\n', indent=4*' '): """Sets the value to a given list of options, e.g. multi-line values Args: values (list): list of values separator (str): separator for values, default: line separator indent (str): indentation depth in case...
[ "def", "set_values", "(", "self", ",", "values", ",", "separator", "=", "'\\n'", ",", "indent", "=", "4", "*", "' '", ")", ":", "self", ".", "_updated", "=", "True", "self", ".", "_multiline_value_joined", "=", "True", "self", ".", "_values", "=", "val...
Sets the value to a given list of options, e.g. multi-line values Args: values (list): list of values separator (str): separator for values, default: line separator indent (str): indentation depth in case of line separator
[ "Sets", "the", "value", "to", "a", "given", "list", "of", "options", "e", ".", "g", ".", "multi", "-", "line", "values" ]
python
train
ChristopherRogers1991/python-irsend
py_irsend/irsend.py
https://github.com/ChristopherRogers1991/python-irsend/blob/aab8ee05d47cc0e3c8c84d220bc6777aa720b232/py_irsend/irsend.py#L26-L50
def list_remotes(device=None, address=None): """ List the available remotes. All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- device: str address: str Returns ------- [str] Notes ----- No att...
[ "def", "list_remotes", "(", "device", "=", "None", ",", "address", "=", "None", ")", ":", "output", "=", "_call", "(", "[", "\"list\"", ",", "\"\"", ",", "\"\"", "]", ",", "None", ",", "device", ",", "address", ")", "remotes", "=", "[", "l", ".", ...
List the available remotes. All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- device: str address: str Returns ------- [str] Notes ----- No attempt is made to catch or handle errors. See the documenta...
[ "List", "the", "available", "remotes", "." ]
python
train
markuskiller/textblob-de
textblob_de/classifiers.py
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/classifiers.py#L100-L105
def contains_extractor(document): """A basic document feature extractor that returns a dict of words that the document contains.""" tokens = _get_document_tokens(document) features = dict((u'contains({0})'.format(w), True) for w in tokens) return features
[ "def", "contains_extractor", "(", "document", ")", ":", "tokens", "=", "_get_document_tokens", "(", "document", ")", "features", "=", "dict", "(", "(", "u'contains({0})'", ".", "format", "(", "w", ")", ",", "True", ")", "for", "w", "in", "tokens", ")", "...
A basic document feature extractor that returns a dict of words that the document contains.
[ "A", "basic", "document", "feature", "extractor", "that", "returns", "a", "dict", "of", "words", "that", "the", "document", "contains", "." ]
python
train
pycontribs/pyrax
pyrax/object_storage.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/object_storage.py#L1659-L1668
def change_content_type(self, new_ctype, guess=False): """ Copies object to itself, but applies a new content-type. The guess feature requires the container to be CDN-enabled. If not then the content-type must be supplied. If using guess with a CDN-enabled container, new_ctype ca...
[ "def", "change_content_type", "(", "self", ",", "new_ctype", ",", "guess", "=", "False", ")", ":", "self", ".", "container", ".", "change_object_content_type", "(", "self", ",", "new_ctype", "=", "new_ctype", ",", "guess", "=", "guess", ")" ]
Copies object to itself, but applies a new content-type. The guess feature requires the container to be CDN-enabled. If not then the content-type must be supplied. If using guess with a CDN-enabled container, new_ctype can be set to None. Failure during the put will result in a swift exc...
[ "Copies", "object", "to", "itself", "but", "applies", "a", "new", "content", "-", "type", ".", "The", "guess", "feature", "requires", "the", "container", "to", "be", "CDN", "-", "enabled", ".", "If", "not", "then", "the", "content", "-", "type", "must", ...
python
train
facetoe/zenpy
zenpy/lib/generator.py
https://github.com/facetoe/zenpy/blob/34c54c7e408b9ed01604ddf8b3422204c8bf31ea/zenpy/lib/generator.py#L59-L63
def update_attrs(self): """ Add attributes such as count/end_time that can be present """ for key, value in self._response_json.items(): if key != 'results' and type(value) not in (list, dict): setattr(self, key, value)
[ "def", "update_attrs", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "_response_json", ".", "items", "(", ")", ":", "if", "key", "!=", "'results'", "and", "type", "(", "value", ")", "not", "in", "(", "list", ",", "dict", ")"...
Add attributes such as count/end_time that can be present
[ "Add", "attributes", "such", "as", "count", "/", "end_time", "that", "can", "be", "present" ]
python
train
summa-tx/riemann
riemann/simple.py
https://github.com/summa-tx/riemann/blob/04ae336dfd4007ceaed748daadc91cc32fa278ec/riemann/simple.py#L62-L69
def output(value, address): ''' int, str -> TxOut accepts base58 or bech32 addresses ''' script = addr.to_output_script(address) value = utils.i2le_padded(value, 8) return tb._make_output(value, script)
[ "def", "output", "(", "value", ",", "address", ")", ":", "script", "=", "addr", ".", "to_output_script", "(", "address", ")", "value", "=", "utils", ".", "i2le_padded", "(", "value", ",", "8", ")", "return", "tb", ".", "_make_output", "(", "value", ","...
int, str -> TxOut accepts base58 or bech32 addresses
[ "int", "str", "-", ">", "TxOut", "accepts", "base58", "or", "bech32", "addresses" ]
python
train
GNS3/gns3-server
gns3server/controller/gns3vm/__init__.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/gns3vm/__init__.py#L222-L236
def list(self, engine): """ List VMS for an engine """ engine = self._get_engine(engine) vms = [] try: for vm in (yield from engine.list()): vms.append({"vmname": vm["vmname"]}) except GNS3VMError as e: # We raise error only...
[ "def", "list", "(", "self", ",", "engine", ")", ":", "engine", "=", "self", ".", "_get_engine", "(", "engine", ")", "vms", "=", "[", "]", "try", ":", "for", "vm", "in", "(", "yield", "from", "engine", ".", "list", "(", ")", ")", ":", "vms", "."...
List VMS for an engine
[ "List", "VMS", "for", "an", "engine" ]
python
train
angr/claripy
claripy/vsa/strided_interval.py
https://github.com/angr/claripy/blob/4ed61924880af1ea8fb778047d896ec0156412a6/claripy/vsa/strided_interval.py#L559-L592
def _signed_bounds(self): """ Get lower bound and upper bound for `self` in signed arithmetic. :return: a list of (lower_bound, upper_bound) tuples """ nsplit = self._nsplit() if len(nsplit) == 1: lb = nsplit[0].lower_bound ub = nsplit[0].upper_b...
[ "def", "_signed_bounds", "(", "self", ")", ":", "nsplit", "=", "self", ".", "_nsplit", "(", ")", "if", "len", "(", "nsplit", ")", "==", "1", ":", "lb", "=", "nsplit", "[", "0", "]", ".", "lower_bound", "ub", "=", "nsplit", "[", "0", "]", ".", "...
Get lower bound and upper bound for `self` in signed arithmetic. :return: a list of (lower_bound, upper_bound) tuples
[ "Get", "lower", "bound", "and", "upper", "bound", "for", "self", "in", "signed", "arithmetic", "." ]
python
train
marcomusy/vtkplotter
vtkplotter/actors.py
https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/actors.py#L1453-L1492
def threshold(self, scalars, vmin=None, vmax=None, useCells=False): """ Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: ...
[ "def", "threshold", "(", "self", ",", "scalars", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ",", "useCells", "=", "False", ")", ":", "if", "utils", ".", "isSequence", "(", "scalars", ")", ":", "self", ".", "addPointScalars", "(", "scalars", ...
Extracts cells where scalar value satisfies threshold criterion. :param scalars: name of the scalars array. :type scalars: str, list :param float vmin: minimum value of the scalar :param float vmax: maximum value of the scalar :param bool useCells: if `True`, assume array scalar...
[ "Extracts", "cells", "where", "scalar", "value", "satisfies", "threshold", "criterion", "." ]
python
train
willkg/everett
everett/ext/inifile.py
https://github.com/willkg/everett/blob/5653134af59f439d2b33f3939fab2b8544428f11/everett/ext/inifile.py#L142-L156
def parse_ini_file(self, path): """Parse ini file at ``path`` and return dict.""" cfgobj = ConfigObj(path, list_values=False) def extract_section(namespace, d): cfg = {} for key, val in d.items(): if isinstance(d[key], dict): cfg.updat...
[ "def", "parse_ini_file", "(", "self", ",", "path", ")", ":", "cfgobj", "=", "ConfigObj", "(", "path", ",", "list_values", "=", "False", ")", "def", "extract_section", "(", "namespace", ",", "d", ")", ":", "cfg", "=", "{", "}", "for", "key", ",", "val...
Parse ini file at ``path`` and return dict.
[ "Parse", "ini", "file", "at", "path", "and", "return", "dict", "." ]
python
train
thespacedoctor/sherlock
sherlock/transient_catalogue_crossmatch.py
https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/transient_catalogue_crossmatch.py#L264-L512
def angular_crossmatch_against_catalogue( self, objectList, searchPara={}, search_name="", brightnessFilter=False, physicalSearch=False, classificationType=False ): """*perform an angular separation crossmatch against a given catalogue in the database ...
[ "def", "angular_crossmatch_against_catalogue", "(", "self", ",", "objectList", ",", "searchPara", "=", "{", "}", ",", "search_name", "=", "\"\"", ",", "brightnessFilter", "=", "False", ",", "physicalSearch", "=", "False", ",", "classificationType", "=", "False", ...
*perform an angular separation crossmatch against a given catalogue in the database and annotate the crossmatch with some value added parameters (distances, physical separations, sub-type of transient etc)* **Key Arguments:** - ``objectList`` -- the list of transient locations to match against the ...
[ "*", "perform", "an", "angular", "separation", "crossmatch", "against", "a", "given", "catalogue", "in", "the", "database", "and", "annotate", "the", "crossmatch", "with", "some", "value", "added", "parameters", "(", "distances", "physical", "separations", "sub", ...
python
train
JNRowe/upoints
upoints/utils.py
https://github.com/JNRowe/upoints/blob/1e4b7a53ed2a06cd854523d54c36aabdccea3830/upoints/utils.py#L436-L449
def isoformat(self): """Generate an ISO 8601 formatted time stamp. Returns: str: `ISO 8601`_ formatted time stamp .. _ISO 8601: http://www.cl.cam.ac.uk/~mgk25/iso-time.html """ text = [self.strftime('%Y-%m-%dT%H:%M:%S'), ] if self.tzinfo: text.ap...
[ "def", "isoformat", "(", "self", ")", ":", "text", "=", "[", "self", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S'", ")", ",", "]", "if", "self", ".", "tzinfo", ":", "text", ".", "append", "(", "self", ".", "tzinfo", ".", "as_timezone", "(", ")", ")", ...
Generate an ISO 8601 formatted time stamp. Returns: str: `ISO 8601`_ formatted time stamp .. _ISO 8601: http://www.cl.cam.ac.uk/~mgk25/iso-time.html
[ "Generate", "an", "ISO", "8601", "formatted", "time", "stamp", "." ]
python
train
fastai/fastai
fastai/vision/data.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/data.py#L191-L196
def download_images(urls:Collection[str], dest:PathOrStr, max_pics:int=1000, max_workers:int=8, timeout=4): "Download images listed in text file `urls` to path `dest`, at most `max_pics`" urls = open(urls).read().strip().split("\n")[:max_pics] dest = Path(dest) dest.mkdir(exist_ok=True) parallel(par...
[ "def", "download_images", "(", "urls", ":", "Collection", "[", "str", "]", ",", "dest", ":", "PathOrStr", ",", "max_pics", ":", "int", "=", "1000", ",", "max_workers", ":", "int", "=", "8", ",", "timeout", "=", "4", ")", ":", "urls", "=", "open", "...
Download images listed in text file `urls` to path `dest`, at most `max_pics`
[ "Download", "images", "listed", "in", "text", "file", "urls", "to", "path", "dest", "at", "most", "max_pics" ]
python
train
jeffrimko/Auxly
lib/auxly/filesys.py
https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/filesys.py#L239-L263
def delete(path, regex=None, recurse=False, test=False): """Deletes the file or directory at `path`. If `path` is a directory and `regex` is provided, matching files will be deleted; `recurse` controls whether subdirectories are recursed. A list of deleted items is returned. If `test` is true, nothing w...
[ "def", "delete", "(", "path", ",", "regex", "=", "None", ",", "recurse", "=", "False", ",", "test", "=", "False", ")", ":", "deleted", "=", "[", "]", "if", "op", ".", "isfile", "(", "path", ")", ":", "if", "not", "test", ":", "os", ".", "remove...
Deletes the file or directory at `path`. If `path` is a directory and `regex` is provided, matching files will be deleted; `recurse` controls whether subdirectories are recursed. A list of deleted items is returned. If `test` is true, nothing will be deleted and a list of items that would have been dele...
[ "Deletes", "the", "file", "or", "directory", "at", "path", ".", "If", "path", "is", "a", "directory", "and", "regex", "is", "provided", "matching", "files", "will", "be", "deleted", ";", "recurse", "controls", "whether", "subdirectories", "are", "recursed", ...
python
train
fulfilio/python-magento
magento/catalog.py
https://github.com/fulfilio/python-magento/blob/720ec136a6e438a9ee4ee92848a9820b91732750/magento/catalog.py#L80-L93
def update(self, category_id, data, store_view=None): """ Update Category :param category_id: ID of category :param data: Category Data :param store_view: Store view ID or code :return: Boolean """ return bool( self.call( 'cata...
[ "def", "update", "(", "self", ",", "category_id", ",", "data", ",", "store_view", "=", "None", ")", ":", "return", "bool", "(", "self", ".", "call", "(", "'catalog_category.update'", ",", "[", "category_id", ",", "data", ",", "store_view", "]", ")", ")" ...
Update Category :param category_id: ID of category :param data: Category Data :param store_view: Store view ID or code :return: Boolean
[ "Update", "Category" ]
python
train
numenta/nupic
src/nupic/algorithms/knn_classifier.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/algorithms/knn_classifier.py#L294-L306
def prototypeSetCategory(self, idToCategorize, newCategory): """ Allows ids to be assigned a category and subsequently enables users to use: - :meth:`~.KNNClassifier.KNNClassifier.removeCategory` - :meth:`~.KNNClassifier.KNNClassifier.closestTrainingPattern` - :meth:`~.KNNClassifier.KNNClassi...
[ "def", "prototypeSetCategory", "(", "self", ",", "idToCategorize", ",", "newCategory", ")", ":", "if", "idToCategorize", "not", "in", "self", ".", "_categoryRecencyList", ":", "return", "recordIndex", "=", "self", ".", "_categoryRecencyList", ".", "index", "(", ...
Allows ids to be assigned a category and subsequently enables users to use: - :meth:`~.KNNClassifier.KNNClassifier.removeCategory` - :meth:`~.KNNClassifier.KNNClassifier.closestTrainingPattern` - :meth:`~.KNNClassifier.KNNClassifier.closestOtherTrainingPattern`
[ "Allows", "ids", "to", "be", "assigned", "a", "category", "and", "subsequently", "enables", "users", "to", "use", ":" ]
python
valid
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_access_list.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_mac_access_list.py#L184-L201
def mac_access_list_extended_hide_mac_acl_ext_seq_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") mac = ET.SubElement(config, "mac", xmlns="urn:brocade.com:mgmt:brocade-mac-access-list") access_list = ET.SubElement(mac, "access-list") exte...
[ "def", "mac_access_list_extended_hide_mac_acl_ext_seq_action", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "mac", "=", "ET", ".", "SubElement", "(", "config", ",", "\"mac\"", ",", "xmlns", "=",...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
ToFuProject/tofu
tofu/geom/_core.py
https://github.com/ToFuProject/tofu/blob/39d6b2e7ced9e13666572dfd37e19403f1d6ff8d/tofu/geom/_core.py#L721-L758
def get_InsideConvexPoly(self, RelOff=_def.TorRelOff, ZLim='Def', Spline=True, Splprms=_def.TorSplprms, NP=_def.TorInsideNP, Plot=False, Test=True): """ Return a polygon that is a smaller and smoothed approximation of Ves.Poly, useful for excluding the d...
[ "def", "get_InsideConvexPoly", "(", "self", ",", "RelOff", "=", "_def", ".", "TorRelOff", ",", "ZLim", "=", "'Def'", ",", "Spline", "=", "True", ",", "Splprms", "=", "_def", ".", "TorSplprms", ",", "NP", "=", "_def", ".", "TorInsideNP", ",", "Plot", "=...
Return a polygon that is a smaller and smoothed approximation of Ves.Poly, useful for excluding the divertor region in a Tokamak For some uses, it can be practical to approximate the polygon defining the Ves object (which can be non-convex, like with a divertor), by a simpler, sligthly smaller and convex polyg...
[ "Return", "a", "polygon", "that", "is", "a", "smaller", "and", "smoothed", "approximation", "of", "Ves", ".", "Poly", "useful", "for", "excluding", "the", "divertor", "region", "in", "a", "Tokamak" ]
python
train
klavinslab/coral
coral/reaction/_central_dogma.py
https://github.com/klavinslab/coral/blob/17f59591211562a59a051f474cd6cecba4829df9/coral/reaction/_central_dogma.py#L42-L86
def coding_sequence(rna): '''Extract coding sequence from an RNA template. :param seq: Sequence from which to extract a coding sequence. :type seq: coral.RNA :param material: Type of sequence ('dna' or 'rna') :type material: str :returns: The first coding sequence (start codon -> stop codon) ma...
[ "def", "coding_sequence", "(", "rna", ")", ":", "if", "isinstance", "(", "rna", ",", "coral", ".", "DNA", ")", ":", "rna", "=", "transcribe", "(", "rna", ")", "codons_left", "=", "len", "(", "rna", ")", "//", "3", "start_codon", "=", "coral", ".", ...
Extract coding sequence from an RNA template. :param seq: Sequence from which to extract a coding sequence. :type seq: coral.RNA :param material: Type of sequence ('dna' or 'rna') :type material: str :returns: The first coding sequence (start codon -> stop codon) matched from 5' to 3'...
[ "Extract", "coding", "sequence", "from", "an", "RNA", "template", "." ]
python
train
pipermerriam/flex
flex/cli.py
https://github.com/pipermerriam/flex/blob/233f8149fb851a6255753bcec948cb6fefb2723b/flex/cli.py#L12-L29
def main(source): """ For a given command line supplied argument, negotiate the content, parse the schema and then return any issues to stdout or if no schema issues, return success exit code. """ if source is None: click.echo( "You need to supply a file or url to a schema to...
[ "def", "main", "(", "source", ")", ":", "if", "source", "is", "None", ":", "click", ".", "echo", "(", "\"You need to supply a file or url to a schema to a swagger schema, for\"", "\"the validator to work.\"", ")", "return", "1", "try", ":", "load", "(", "source", ")...
For a given command line supplied argument, negotiate the content, parse the schema and then return any issues to stdout or if no schema issues, return success exit code.
[ "For", "a", "given", "command", "line", "supplied", "argument", "negotiate", "the", "content", "parse", "the", "schema", "and", "then", "return", "any", "issues", "to", "stdout", "or", "if", "no", "schema", "issues", "return", "success", "exit", "code", "." ...
python
train
materialsproject/pymatgen
pymatgen/optimization/linear_assignment_numpy.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/optimization/linear_assignment_numpy.py#L91-L98
def min_cost(self): """ Returns the cost of the best assignment """ if self._min_cost: return self._min_cost self._min_cost = np.sum(self.c[np.arange(self.nx), self.solution]) return self._min_cost
[ "def", "min_cost", "(", "self", ")", ":", "if", "self", ".", "_min_cost", ":", "return", "self", ".", "_min_cost", "self", ".", "_min_cost", "=", "np", ".", "sum", "(", "self", ".", "c", "[", "np", ".", "arange", "(", "self", ".", "nx", ")", ",",...
Returns the cost of the best assignment
[ "Returns", "the", "cost", "of", "the", "best", "assignment" ]
python
train
mitsei/dlkit
dlkit/handcar/learning/managers.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/learning/managers.py#L2402-L2427
def get_objective_query_session(self, proxy): """Gets the ``OsidSession`` associated with the objective query service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: an ``ObjectiveQuerySession`` :rtype: ``osid.learning.ObjectiveQuerySession`` :raise: ``...
[ "def", "get_objective_query_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_objective_query", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "import", "sessions", "except", "ImportError", ":", "...
Gets the ``OsidSession`` associated with the objective query service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: an ``ObjectiveQuerySession`` :rtype: ``osid.learning.ObjectiveQuerySession`` :raise: ``NullArgument`` -- ``proxy`` is ``null`` :raise: `...
[ "Gets", "the", "OsidSession", "associated", "with", "the", "objective", "query", "service", "." ]
python
train
rosenbrockc/fortpy
fortpy/scripts/analyze.py
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/scripts/analyze.py#L954-L979
def _plot_generic(self, filename=None): """Plots the current state of the shell, saving the value to the specified file if specified. """ #Since the filename is being passed directly from the argument, check its validity. if filename == "": filename = None if...
[ "def", "_plot_generic", "(", "self", ",", "filename", "=", "None", ")", ":", "#Since the filename is being passed directly from the argument, check its validity.", "if", "filename", "==", "\"\"", ":", "filename", "=", "None", "if", "\"x\"", "not", "in", "self", ".", ...
Plots the current state of the shell, saving the value to the specified file if specified.
[ "Plots", "the", "current", "state", "of", "the", "shell", "saving", "the", "value", "to", "the", "specified", "file", "if", "specified", "." ]
python
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/cocoapy.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/cocoapy.py#L1085-L1090
def cfset_to_set(cfset): """Convert CFSet to python set.""" count = cf.CFSetGetCount(cfset) buffer = (c_void_p * count)() cf.CFSetGetValues(cfset, byref(buffer)) return set([cftype_to_value(c_void_p(buffer[i])) for i in range(count)])
[ "def", "cfset_to_set", "(", "cfset", ")", ":", "count", "=", "cf", ".", "CFSetGetCount", "(", "cfset", ")", "buffer", "=", "(", "c_void_p", "*", "count", ")", "(", ")", "cf", ".", "CFSetGetValues", "(", "cfset", ",", "byref", "(", "buffer", ")", ")",...
Convert CFSet to python set.
[ "Convert", "CFSet", "to", "python", "set", "." ]
python
train
pvlib/pvlib-python
pvlib/forecast.py
https://github.com/pvlib/pvlib-python/blob/2e844a595b820b43d1170269781fa66bd0ccc8a3/pvlib/forecast.py#L308-L325
def rename(self, data, variables=None): """ Renames the columns according the variable mapping. Parameters ---------- data: DataFrame variables: None or dict, default None If None, uses self.variables Returns ------- data: DataFrame ...
[ "def", "rename", "(", "self", ",", "data", ",", "variables", "=", "None", ")", ":", "if", "variables", "is", "None", ":", "variables", "=", "self", ".", "variables", "return", "data", ".", "rename", "(", "columns", "=", "{", "y", ":", "x", "for", "...
Renames the columns according the variable mapping. Parameters ---------- data: DataFrame variables: None or dict, default None If None, uses self.variables Returns ------- data: DataFrame Renamed data.
[ "Renames", "the", "columns", "according", "the", "variable", "mapping", "." ]
python
train
PSPC-SPAC-buyandsell/von_anchor
von_anchor/nodepool/protocol.py
https://github.com/PSPC-SPAC-buyandsell/von_anchor/blob/78ac1de67be42a676274f4bf71fe12f66e72f309/von_anchor/nodepool/protocol.py#L76-L88
def cred_def_id(self, issuer_did: str, schema_seq_no: int) -> str: """ Return credential definition identifier for input issuer DID and schema sequence number. :param issuer_did: DID of credential definition issuer :param schema_seq_no: schema sequence number :return: credential...
[ "def", "cred_def_id", "(", "self", ",", "issuer_did", ":", "str", ",", "schema_seq_no", ":", "int", ")", "->", "str", ":", "return", "'{}:3:CL:{}{}'", ".", "format", "(", "# 3 marks indy cred def id, CL is sig type", "issuer_did", ",", "schema_seq_no", ",", "self"...
Return credential definition identifier for input issuer DID and schema sequence number. :param issuer_did: DID of credential definition issuer :param schema_seq_no: schema sequence number :return: credential definition identifier
[ "Return", "credential", "definition", "identifier", "for", "input", "issuer", "DID", "and", "schema", "sequence", "number", "." ]
python
train
MillionIntegrals/vel
vel/rl/modules/action_head.py
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/modules/action_head.py#L68-L87
def kl_divergence(self, params_q, params_p): """ Categorical distribution KL divergence calculation KL(Q || P) = sum Q_i log (Q_i / P_i) Formula is: log(sigma_p) - log(sigma_q) + (sigma_q^2 + (mu_q - mu_p)^2))/(2 * sigma_p^2) """ means_q = params_q[:, :, 0] ...
[ "def", "kl_divergence", "(", "self", ",", "params_q", ",", "params_p", ")", ":", "means_q", "=", "params_q", "[", ":", ",", ":", ",", "0", "]", "log_std_q", "=", "params_q", "[", ":", ",", ":", ",", "1", "]", "means_p", "=", "params_p", "[", ":", ...
Categorical distribution KL divergence calculation KL(Q || P) = sum Q_i log (Q_i / P_i) Formula is: log(sigma_p) - log(sigma_q) + (sigma_q^2 + (mu_q - mu_p)^2))/(2 * sigma_p^2)
[ "Categorical", "distribution", "KL", "divergence", "calculation", "KL", "(", "Q", "||", "P", ")", "=", "sum", "Q_i", "log", "(", "Q_i", "/", "P_i", ")" ]
python
train
DataBiosphere/toil
src/toil/provisioners/clusterScaler.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/provisioners/clusterScaler.py#L65-L76
def binPack(self, jobShapes): """Pack a list of jobShapes into the fewest nodes reasonable. Can be run multiple times.""" # TODO: Check for redundancy with batchsystems.mesos.JobQueue() sorting logger.debug('Running bin packing for node shapes %s and %s job(s).', self.nodeSh...
[ "def", "binPack", "(", "self", ",", "jobShapes", ")", ":", "# TODO: Check for redundancy with batchsystems.mesos.JobQueue() sorting", "logger", ".", "debug", "(", "'Running bin packing for node shapes %s and %s job(s).'", ",", "self", ".", "nodeShapes", ",", "len", "(", "jo...
Pack a list of jobShapes into the fewest nodes reasonable. Can be run multiple times.
[ "Pack", "a", "list", "of", "jobShapes", "into", "the", "fewest", "nodes", "reasonable", ".", "Can", "be", "run", "multiple", "times", "." ]
python
train
earwig/mwparserfromhell
mwparserfromhell/parser/tokenizer.py
https://github.com/earwig/mwparserfromhell/blob/98dc30902d35c714a70aca8e6616f49d71cb24cc/mwparserfromhell/parser/tokenizer.py#L1223-L1234
def _handle_end(self): """Handle the end of the stream of wikitext.""" if self._context & contexts.FAIL: if self._context & contexts.TAG_BODY: if is_single(self._stack[1].text): return self._handle_single_tag_end() if self._context & contexts.T...
[ "def", "_handle_end", "(", "self", ")", ":", "if", "self", ".", "_context", "&", "contexts", ".", "FAIL", ":", "if", "self", ".", "_context", "&", "contexts", ".", "TAG_BODY", ":", "if", "is_single", "(", "self", ".", "_stack", "[", "1", "]", ".", ...
Handle the end of the stream of wikitext.
[ "Handle", "the", "end", "of", "the", "stream", "of", "wikitext", "." ]
python
train
aliyun/aliyun-odps-python-sdk
odps/df/backends/frame.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/backends/frame.py#L364-L406
def to_html(self, buf=None, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=None, index_names=True, justify=None, bold_rows=True, classes=None, escape=True, max_rows=None, max_cols=None, sho...
[ "def", "to_html", "(", "self", ",", "buf", "=", "None", ",", "columns", "=", "None", ",", "col_space", "=", "None", ",", "header", "=", "True", ",", "index", "=", "True", ",", "na_rep", "=", "'NaN'", ",", "formatters", "=", "None", ",", "float_format...
Render a DataFrame as an HTML table. `to_html`-specific options: bold_rows : boolean, default True Make the row labels bold in the output classes : str or list or tuple, default None CSS class(es) to apply to the resulting html table escape : boolean, default Tr...
[ "Render", "a", "DataFrame", "as", "an", "HTML", "table", "." ]
python
train
GPflow/GPflow
gpflow/expectations.py
https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/expectations.py#L858-L880
def _expectation(p, kern1, feat1, kern2, feat2, nghp=None): r""" Compute the expectation: expectation[n] = <(\Sum_i K1_i_{Z1, x_n}) (\Sum_j K2_j_{x_n, Z2})>_p(x_n) - \Sum_i K1_i_{.,.}, \Sum_j K2_j_{.,.} :: Sum kernels :return: NxM1xM2 """ crossexps = [] if kern1 == kern2 and feat1 ...
[ "def", "_expectation", "(", "p", ",", "kern1", ",", "feat1", ",", "kern2", ",", "feat2", ",", "nghp", "=", "None", ")", ":", "crossexps", "=", "[", "]", "if", "kern1", "==", "kern2", "and", "feat1", "==", "feat2", ":", "# avoid duplicate computation by u...
r""" Compute the expectation: expectation[n] = <(\Sum_i K1_i_{Z1, x_n}) (\Sum_j K2_j_{x_n, Z2})>_p(x_n) - \Sum_i K1_i_{.,.}, \Sum_j K2_j_{.,.} :: Sum kernels :return: NxM1xM2
[ "r", "Compute", "the", "expectation", ":", "expectation", "[", "n", "]", "=", "<", "(", "\\", "Sum_i", "K1_i_", "{", "Z1", "x_n", "}", ")", "(", "\\", "Sum_j", "K2_j_", "{", "x_n", "Z2", "}", ")", ">", "_p", "(", "x_n", ")", "-", "\\", "Sum_i",...
python
train
dmlc/gluon-nlp
src/gluonnlp/model/bert.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/bert.py#L364-L368
def _get_classifier(self, prefix): """ Construct a decoder for the next sentence prediction task """ with self.name_scope(): classifier = nn.Dense(2, prefix=prefix) return classifier
[ "def", "_get_classifier", "(", "self", ",", "prefix", ")", ":", "with", "self", ".", "name_scope", "(", ")", ":", "classifier", "=", "nn", ".", "Dense", "(", "2", ",", "prefix", "=", "prefix", ")", "return", "classifier" ]
Construct a decoder for the next sentence prediction task
[ "Construct", "a", "decoder", "for", "the", "next", "sentence", "prediction", "task" ]
python
train
quantopian/pyfolio
pyfolio/txn.py
https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/txn.py#L83-L110
def get_txn_vol(transactions): """ Extract daily transaction data from set of transaction objects. Parameters ---------- transactions : pd.DataFrame Time series containing one row per symbol (and potentially duplicate datetime indices) and columns for amount and price. ...
[ "def", "get_txn_vol", "(", "transactions", ")", ":", "txn_norm", "=", "transactions", ".", "copy", "(", ")", "txn_norm", ".", "index", "=", "txn_norm", ".", "index", ".", "normalize", "(", ")", "amounts", "=", "txn_norm", ".", "amount", ".", "abs", "(", ...
Extract daily transaction data from set of transaction objects. Parameters ---------- transactions : pd.DataFrame Time series containing one row per symbol (and potentially duplicate datetime indices) and columns for amount and price. Returns ------- pd.DataFrame ...
[ "Extract", "daily", "transaction", "data", "from", "set", "of", "transaction", "objects", "." ]
python
valid
mdickinson/bigfloat
bigfloat/core.py
https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L2104-L2114
def j1(x, context=None): """ Return the value of the first kind Bessel function of order 1 at x. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_j1, (BigFloat._implicit_convert(x),), context, )
[ "def", "j1", "(", "x", ",", "context", "=", "None", ")", ":", "return", "_apply_function_in_current_context", "(", "BigFloat", ",", "mpfr", ".", "mpfr_j1", ",", "(", "BigFloat", ".", "_implicit_convert", "(", "x", ")", ",", ")", ",", "context", ",", ")" ...
Return the value of the first kind Bessel function of order 1 at x.
[ "Return", "the", "value", "of", "the", "first", "kind", "Bessel", "function", "of", "order", "1", "at", "x", "." ]
python
train
pricingassistant/mrq
mrq/queue_raw.py
https://github.com/pricingassistant/mrq/blob/d0a5a34de9cba38afa94fb7c9e17f9b570b79a50/mrq/queue_raw.py#L239-L265
def get_sorted_graph( self, start=0, stop=100, slices=100, include_inf=False, exact=False): """ Returns a graph of the distribution of jobs in a sorted set """ if not self.is_sorted: raise Exception("Not a sorted queue"...
[ "def", "get_sorted_graph", "(", "self", ",", "start", "=", "0", ",", "stop", "=", "100", ",", "slices", "=", "100", ",", "include_inf", "=", "False", ",", "exact", "=", "False", ")", ":", "if", "not", "self", ".", "is_sorted", ":", "raise", "Exceptio...
Returns a graph of the distribution of jobs in a sorted set
[ "Returns", "a", "graph", "of", "the", "distribution", "of", "jobs", "in", "a", "sorted", "set" ]
python
train
briancappello/flask-unchained
flask_unchained/bundles/security/views/security_controller.py
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L76-L88
def logout(self): """ View function to log a user out. Supports html and json requests. """ if current_user.is_authenticated: self.security_service.logout_user() if request.is_json: return '', HTTPStatus.NO_CONTENT self.flash(_('flask_unchained.b...
[ "def", "logout", "(", "self", ")", ":", "if", "current_user", ".", "is_authenticated", ":", "self", ".", "security_service", ".", "logout_user", "(", ")", "if", "request", ".", "is_json", ":", "return", "''", ",", "HTTPStatus", ".", "NO_CONTENT", "self", "...
View function to log a user out. Supports html and json requests.
[ "View", "function", "to", "log", "a", "user", "out", ".", "Supports", "html", "and", "json", "requests", "." ]
python
train
koalalorenzo/python-digitalocean
digitalocean/Manager.py
https://github.com/koalalorenzo/python-digitalocean/blob/d0221b57856fb1e131cafecf99d826f7b07a947c/digitalocean/Manager.py#L266-L273
def get_load_balancer(self, id): """ Returns a Load Balancer object by its ID. Args: id (str): Load Balancer ID """ return LoadBalancer.get_object(api_token=self.token, id=id)
[ "def", "get_load_balancer", "(", "self", ",", "id", ")", ":", "return", "LoadBalancer", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "id", "=", "id", ")" ]
Returns a Load Balancer object by its ID. Args: id (str): Load Balancer ID
[ "Returns", "a", "Load", "Balancer", "object", "by", "its", "ID", "." ]
python
valid
tensorflow/tensor2tensor
tensor2tensor/layers/discretization.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/discretization.py#L57-L72
def slice_hidden(x, hidden_size, num_blocks): """Slice encoder hidden state under num_blocks. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: Sliced states of shape [batch_size...
[ "def", "slice_hidden", "(", "x", ",", "hidden_size", ",", "num_blocks", ")", ":", "batch_size", ",", "latent_dim", ",", "_", "=", "common_layers", ".", "shape_list", "(", "x", ")", "block_dim", "=", "hidden_size", "//", "num_blocks", "x_sliced", "=", "tf", ...
Slice encoder hidden state under num_blocks. Args: x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size]. hidden_size: Dimension of the latent space. num_blocks: Number of blocks in DVQ. Returns: Sliced states of shape [batch_size, latent_dim, num_blocks, block_dim].
[ "Slice", "encoder", "hidden", "state", "under", "num_blocks", "." ]
python
train
noxdafox/pebble
pebble/functions.py
https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/functions.py#L102-L113
def prepare_threads(new_function): """Replaces threading._get_ident() function in order to notify the waiting Condition.""" with _waitforthreads_lock: if hasattr(threading, 'get_ident'): old_function = threading.get_ident threading.get_ident = new_function else: ...
[ "def", "prepare_threads", "(", "new_function", ")", ":", "with", "_waitforthreads_lock", ":", "if", "hasattr", "(", "threading", ",", "'get_ident'", ")", ":", "old_function", "=", "threading", ".", "get_ident", "threading", ".", "get_ident", "=", "new_function", ...
Replaces threading._get_ident() function in order to notify the waiting Condition.
[ "Replaces", "threading", ".", "_get_ident", "()", "function", "in", "order", "to", "notify", "the", "waiting", "Condition", "." ]
python
train
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/pip/compat/dictconfig.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/pip/compat/dictconfig.py#L521-L527
def add_handlers(self, logger, handlers): """Add handlers to a logger from a list of names.""" for h in handlers: try: logger.addHandler(self.config['handlers'][h]) except StandardError as e: raise ValueError('Unable to add handler %r: %s' % (h, e)...
[ "def", "add_handlers", "(", "self", ",", "logger", ",", "handlers", ")", ":", "for", "h", "in", "handlers", ":", "try", ":", "logger", ".", "addHandler", "(", "self", ".", "config", "[", "'handlers'", "]", "[", "h", "]", ")", "except", "StandardError",...
Add handlers to a logger from a list of names.
[ "Add", "handlers", "to", "a", "logger", "from", "a", "list", "of", "names", "." ]
python
test
boriel/zxbasic
arch/zx48k/optimizer.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/arch/zx48k/optimizer.py#L2345-L2388
def optimize(initial_memory): """ This will remove useless instructions """ global BLOCKS global PROC_COUNTER LABELS.clear() JUMP_LABELS.clear() del MEMORY[:] PROC_COUNTER = 0 cleanupmem(initial_memory) if OPTIONS.optimization.value <= 2: return '\n'.join(x for x in ini...
[ "def", "optimize", "(", "initial_memory", ")", ":", "global", "BLOCKS", "global", "PROC_COUNTER", "LABELS", ".", "clear", "(", ")", "JUMP_LABELS", ".", "clear", "(", ")", "del", "MEMORY", "[", ":", "]", "PROC_COUNTER", "=", "0", "cleanupmem", "(", "initial...
This will remove useless instructions
[ "This", "will", "remove", "useless", "instructions" ]
python
train
openai/baselines
baselines/common/tf_util.py
https://github.com/openai/baselines/blob/3301089b48c42b87b396e246ea3f56fa4bfc9678/baselines/common/tf_util.py#L58-L72
def make_session(config=None, num_cpu=None, make_default=False, graph=None): """Returns a session that will use <num_cpu> CPU's only""" if num_cpu is None: num_cpu = int(os.getenv('RCALL_NUM_CPU', multiprocessing.cpu_count())) if config is None: config = tf.ConfigProto( allow_sof...
[ "def", "make_session", "(", "config", "=", "None", ",", "num_cpu", "=", "None", ",", "make_default", "=", "False", ",", "graph", "=", "None", ")", ":", "if", "num_cpu", "is", "None", ":", "num_cpu", "=", "int", "(", "os", ".", "getenv", "(", "'RCALL_...
Returns a session that will use <num_cpu> CPU's only
[ "Returns", "a", "session", "that", "will", "use", "<num_cpu", ">", "CPU", "s", "only" ]
python
valid
tanghaibao/jcvi
jcvi/assembly/goldenpath.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/goldenpath.py#L156-L183
def update_clr(self, aclr, bclr): """ Zip the two sequences together, using "left-greedy" rule ============= seqA |||| ====(===============) seqB """ print(aclr, bclr, file=sys.stderr) otype = self.otype if ot...
[ "def", "update_clr", "(", "self", ",", "aclr", ",", "bclr", ")", ":", "print", "(", "aclr", ",", "bclr", ",", "file", "=", "sys", ".", "stderr", ")", "otype", "=", "self", ".", "otype", "if", "otype", "==", "1", ":", "if", "aclr", ".", "orientati...
Zip the two sequences together, using "left-greedy" rule ============= seqA |||| ====(===============) seqB
[ "Zip", "the", "two", "sequences", "together", "using", "left", "-", "greedy", "rule" ]
python
train
markovmodel/PyEMMA
pyemma/_base/progress/reporter/__init__.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/progress/reporter/__init__.py#L155-L160
def _progress_set_description(self, stage, description): """ set description of an already existing progress """ self.__check_stage_registered(stage) self._prog_rep_descriptions[stage] = description if self._prog_rep_progressbars[stage]: self._prog_rep_progressbars[stage].set...
[ "def", "_progress_set_description", "(", "self", ",", "stage", ",", "description", ")", ":", "self", ".", "__check_stage_registered", "(", "stage", ")", "self", ".", "_prog_rep_descriptions", "[", "stage", "]", "=", "description", "if", "self", ".", "_prog_rep_p...
set description of an already existing progress
[ "set", "description", "of", "an", "already", "existing", "progress" ]
python
train
coin-or/GiMPy
src/gimpy/graph.py
https://github.com/coin-or/GiMPy/blob/51853122a50eb6019d06bbdedbfc396a833b5a22/src/gimpy/graph.py#L2903-L2926
def get_simplex_solution_graph(self): ''' API: get_simplex_solution_graph(self): Description: Assumes a feasible flow solution stored in 'flow' attribute's of arcs. Returns the graph with arcs that have flow between 0 and capacity. Pre: ...
[ "def", "get_simplex_solution_graph", "(", "self", ")", ":", "simplex_g", "=", "Graph", "(", "type", "=", "DIRECTED_GRAPH", ")", "for", "i", "in", "self", ".", "neighbors", ":", "simplex_g", ".", "add_node", "(", "i", ")", "for", "e", "in", "self", ".", ...
API: get_simplex_solution_graph(self): Description: Assumes a feasible flow solution stored in 'flow' attribute's of arcs. Returns the graph with arcs that have flow between 0 and capacity. Pre: (1) 'flow' attribute represents a feasible flow s...
[ "API", ":", "get_simplex_solution_graph", "(", "self", ")", ":", "Description", ":", "Assumes", "a", "feasible", "flow", "solution", "stored", "in", "flow", "attribute", "s", "of", "arcs", ".", "Returns", "the", "graph", "with", "arcs", "that", "have", "flow...
python
train
jason-weirather/py-seq-tools
seqtools/graph/__init__.py
https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/graph/__init__.py#L148-L174
def move_edges(self,n1,n2): """Move edges from node 1 to node 2 Not self edges though Overwrites edges """ #Traverse edges to find incoming with n1 incoming = [] for e in self._edges.values(): if e.node2.id == n1.id: incoming.append(e) #Traverse edges to...
[ "def", "move_edges", "(", "self", ",", "n1", ",", "n2", ")", ":", "#Traverse edges to find incoming with n1", "incoming", "=", "[", "]", "for", "e", "in", "self", ".", "_edges", ".", "values", "(", ")", ":", "if", "e", ".", "node2", ".", "id", "==", ...
Move edges from node 1 to node 2 Not self edges though Overwrites edges
[ "Move", "edges", "from", "node", "1", "to", "node", "2", "Not", "self", "edges", "though" ]
python
train
keenlabs/KeenClient-Python
keen/api.py
https://github.com/keenlabs/KeenClient-Python/blob/266387c3376d1e000d117e17c45045ae3439d43f/keen/api.py#L130-L166
def _order_by_is_valid_or_none(self, params): """ Validates that a given order_by has proper syntax. :param params: Query params. :return: Returns True if either no order_by is present, or if the order_by is well-formed. """ if not "order_by" in params or not params["ord...
[ "def", "_order_by_is_valid_or_none", "(", "self", ",", "params", ")", ":", "if", "not", "\"order_by\"", "in", "params", "or", "not", "params", "[", "\"order_by\"", "]", ":", "return", "True", "def", "_order_by_dict_is_not_well_formed", "(", "d", ")", ":", "if"...
Validates that a given order_by has proper syntax. :param params: Query params. :return: Returns True if either no order_by is present, or if the order_by is well-formed.
[ "Validates", "that", "a", "given", "order_by", "has", "proper", "syntax", "." ]
python
train
uber/tchannel-python
tchannel/tornado/message_factory.py
https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L115-L151
def build_raw_response_message(self, response, args, is_completed=False): """build protocol level message based on response and args. response object contains meta information about outgoing response. args are the currently chunk data from argstreams is_completed tells the flags of the ...
[ "def", "build_raw_response_message", "(", "self", ",", "response", ",", "args", ",", "is_completed", "=", "False", ")", ":", "response", ".", "flags", "=", "FlagsType", ".", "none", "if", "is_completed", "else", "FlagsType", ".", "fragment", "# TODO decide what ...
build protocol level message based on response and args. response object contains meta information about outgoing response. args are the currently chunk data from argstreams is_completed tells the flags of the message :param response: Response :param args: array of arg streams ...
[ "build", "protocol", "level", "message", "based", "on", "response", "and", "args", "." ]
python
train
wonambi-python/wonambi
wonambi/widgets/info.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/info.py#L426-L433
def toggle_buttons(self): """Turn buttons on and off.""" all_time_on = self.all_time.get_value() all_chan_on = self.all_chan.get_value() self.times['beg'].setEnabled(not all_time_on) self.times['end'].setEnabled(not all_time_on) self.idx_chan.setEnabled(not all_chan_on)
[ "def", "toggle_buttons", "(", "self", ")", ":", "all_time_on", "=", "self", ".", "all_time", ".", "get_value", "(", ")", "all_chan_on", "=", "self", ".", "all_chan", ".", "get_value", "(", ")", "self", ".", "times", "[", "'beg'", "]", ".", "setEnabled", ...
Turn buttons on and off.
[ "Turn", "buttons", "on", "and", "off", "." ]
python
train
allenai/allennlp
allennlp/modules/residual_with_layer_dropout.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/residual_with_layer_dropout.py#L21-L59
def forward(self, layer_input: torch.Tensor, layer_output: torch.Tensor, layer_index: int = None, total_layers: int = None) -> torch.Tensor: # pylint: disable=arguments-differ """ Apply dropout to this layer, for this whole mini-bat...
[ "def", "forward", "(", "self", ",", "layer_input", ":", "torch", ".", "Tensor", ",", "layer_output", ":", "torch", ".", "Tensor", ",", "layer_index", ":", "int", "=", "None", ",", "total_layers", ":", "int", "=", "None", ")", "->", "torch", ".", "Tenso...
Apply dropout to this layer, for this whole mini-batch. dropout_prob = layer_index / total_layers * undecayed_dropout_prob if layer_idx and total_layers is specified, else it will use the undecayed_dropout_prob directly. Parameters ---------- layer_input ``torch.FloatTensor`` re...
[ "Apply", "dropout", "to", "this", "layer", "for", "this", "whole", "mini", "-", "batch", ".", "dropout_prob", "=", "layer_index", "/", "total_layers", "*", "undecayed_dropout_prob", "if", "layer_idx", "and", "total_layers", "is", "specified", "else", "it", "will...
python
train
tanghaibao/goatools
goatools/parsers/ncbi_gene_file_reader.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/parsers/ncbi_gene_file_reader.py#L215-L226
def convert_ints_floats(self, flds): """Convert strings to ints and floats, if so specified.""" for idx in self.idxs_float: flds[idx] = float(flds[idx]) for idx in self.idxs_int: dig = flds[idx] #print 'idx={} ({}) {}'.format(idx, flds[idx], flds) # DVK ...
[ "def", "convert_ints_floats", "(", "self", ",", "flds", ")", ":", "for", "idx", "in", "self", ".", "idxs_float", ":", "flds", "[", "idx", "]", "=", "float", "(", "flds", "[", "idx", "]", ")", "for", "idx", "in", "self", ".", "idxs_int", ":", "dig",...
Convert strings to ints and floats, if so specified.
[ "Convert", "strings", "to", "ints", "and", "floats", "if", "so", "specified", "." ]
python
train
CalebBell/fluids
fluids/friction.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/friction.py#L1712-L1760
def Prandtl_von_Karman_Nikuradse(Re): r'''Calculates Darcy friction factor for smooth pipes as a function of Reynolds number from the Prandtl-von Karman Nikuradse equation as given in [1]_ and [2]_: .. math:: \frac{1}{\sqrt{f}} = -2\log_{10}\left(\frac{2.51}{Re\sqrt{f}}\right) Paramet...
[ "def", "Prandtl_von_Karman_Nikuradse", "(", "Re", ")", ":", "# Good 1E150 to 1E-150", "c1", "=", "1.151292546497022842008995727342182103801", "# log(10)/2", "c2", "=", "1.325474527619599502640416597148504422899", "# log(10)**2/4", "return", "c2", "/", "float", "(", "lambertw"...
r'''Calculates Darcy friction factor for smooth pipes as a function of Reynolds number from the Prandtl-von Karman Nikuradse equation as given in [1]_ and [2]_: .. math:: \frac{1}{\sqrt{f}} = -2\log_{10}\left(\frac{2.51}{Re\sqrt{f}}\right) Parameters ---------- Re : float ...
[ "r", "Calculates", "Darcy", "friction", "factor", "for", "smooth", "pipes", "as", "a", "function", "of", "Reynolds", "number", "from", "the", "Prandtl", "-", "von", "Karman", "Nikuradse", "equation", "as", "given", "in", "[", "1", "]", "_", "and", "[", "...
python
train
saltstack/salt
salt/modules/virt.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/virt.py#L3103-L3132
def define_vol_xml_path(path, **kwargs): ''' Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param us...
[ "def", "define_vol_xml_path", "(", "path", ",", "*", "*", "kwargs", ")", ":", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "path", ",", "'r'", ")", "as", "fp_", ":", "return", "define_vol_xml_str", "(", "salt", ".", "uti...
Define a volume based on the XML-file path passed to the function :param path: path to a file containing the libvirt XML definition of the volume :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults...
[ "Define", "a", "volume", "based", "on", "the", "XML", "-", "file", "path", "passed", "to", "the", "function" ]
python
train
google/grr
grr/server/grr_response_server/check_lib/checks.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/check_lib/checks.py#L612-L645
def FindChecks(cls, artifact=None, os_name=None, cpe=None, labels=None, restrict_checks=None): """Takes targeting info, identifies relevant checks. FindChecks will return results when a host has the conditions necessary for ...
[ "def", "FindChecks", "(", "cls", ",", "artifact", "=", "None", ",", "os_name", "=", "None", ",", "cpe", "=", "None", ",", "labels", "=", "None", ",", "restrict_checks", "=", "None", ")", ":", "check_ids", "=", "set", "(", ")", "conditions", "=", "lis...
Takes targeting info, identifies relevant checks. FindChecks will return results when a host has the conditions necessary for a check to occur. Conditions with partial results are not returned. For example, FindChecks will not return checks that if a check targets os_name=["Linux"], labels=["foo"] and ...
[ "Takes", "targeting", "info", "identifies", "relevant", "checks", "." ]
python
train
planetlabs/planet-client-python
planet/api/utils.py
https://github.com/planetlabs/planet-client-python/blob/1c62ce7d416819951dddee0c22068fef6d40b027/planet/api/utils.py#L210-L227
def get_random_filename(content_type=None): """Get a pseudo-random, Planet-looking filename. >>> from planet.api import utils >>> print(utils.get_random_filename()) #doctest:+SKIP planet-61FPnh7K >>> print(utils.get_random_filename('image/tiff')) #doctest:+SKIP planet-V8ELYxy5.tif >>> ...
[ "def", "get_random_filename", "(", "content_type", "=", "None", ")", ":", "extension", "=", "mimetypes", ".", "guess_extension", "(", "content_type", "or", "''", ")", "or", "''", "characters", "=", "string", ".", "ascii_letters", "+", "'0123456789'", "letters", ...
Get a pseudo-random, Planet-looking filename. >>> from planet.api import utils >>> print(utils.get_random_filename()) #doctest:+SKIP planet-61FPnh7K >>> print(utils.get_random_filename('image/tiff')) #doctest:+SKIP planet-V8ELYxy5.tif >>> :returns: a filename (i.e. ``basename``) :rtype...
[ "Get", "a", "pseudo", "-", "random", "Planet", "-", "looking", "filename", "." ]
python
train
websocket-client/websocket-client
websocket/_core.py
https://github.com/websocket-client/websocket-client/blob/3c25814664fef5b78716ed8841123ed1c0d17824/websocket/_core.py#L186-L239
def connect(self, url, **options): """ Connect to url. url is websocket url scheme. ie. ws://host:port/resource You can customize using 'options'. If you set "header" list object, you can set your own custom header. >>> ws = WebSocket() >>> ws.connect("ws://echo....
[ "def", "connect", "(", "self", ",", "url", ",", "*", "*", "options", ")", ":", "# FIXME: \"subprotocols\" are getting lost, not passed down", "# FIXME: \"header\", \"cookie\", \"origin\" and \"host\" too", "self", ".", "sock_opt", ".", "timeout", "=", "options", ".", "get...
Connect to url. url is websocket url scheme. ie. ws://host:port/resource You can customize using 'options'. If you set "header" list object, you can set your own custom header. >>> ws = WebSocket() >>> ws.connect("ws://echo.websocket.org/", ... header=["User-...
[ "Connect", "to", "url", ".", "url", "is", "websocket", "url", "scheme", ".", "ie", ".", "ws", ":", "//", "host", ":", "port", "/", "resource", "You", "can", "customize", "using", "options", ".", "If", "you", "set", "header", "list", "object", "you", ...
python
train
tanghaibao/jcvi
jcvi/assembly/hic.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/hic.py#L412-L426
def M(self): """ Contact frequency matrix. Each cell contains how many inter-contig links between i-th and j-th contigs. """ N = self.N tig_to_idx = self.tig_to_idx M = np.zeros((N, N), dtype=int) for (at, bt), links in self.contacts.items(): i...
[ "def", "M", "(", "self", ")", ":", "N", "=", "self", ".", "N", "tig_to_idx", "=", "self", ".", "tig_to_idx", "M", "=", "np", ".", "zeros", "(", "(", "N", ",", "N", ")", ",", "dtype", "=", "int", ")", "for", "(", "at", ",", "bt", ")", ",", ...
Contact frequency matrix. Each cell contains how many inter-contig links between i-th and j-th contigs.
[ "Contact", "frequency", "matrix", ".", "Each", "cell", "contains", "how", "many", "inter", "-", "contig", "links", "between", "i", "-", "th", "and", "j", "-", "th", "contigs", "." ]
python
train
inspirehep/inspire-dojson
inspire_dojson/hepnames/rules.py
https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L119-L172
def ids2marc(self, key, value): """Populate the ``035`` MARC field. Also populates the ``8564`` and ``970`` MARC field through side effects. """ def _is_schema_inspire_bai(id_, schema): return schema == 'INSPIRE BAI' def _is_schema_inspire_id(id_, schema): return schema == 'INSPIRE...
[ "def", "ids2marc", "(", "self", ",", "key", ",", "value", ")", ":", "def", "_is_schema_inspire_bai", "(", "id_", ",", "schema", ")", ":", "return", "schema", "==", "'INSPIRE BAI'", "def", "_is_schema_inspire_id", "(", "id_", ",", "schema", ")", ":", "retur...
Populate the ``035`` MARC field. Also populates the ``8564`` and ``970`` MARC field through side effects.
[ "Populate", "the", "035", "MARC", "field", "." ]
python
train
woolfson-group/isambard
isambard/optimisation/optimizer.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/optimisation/optimizer.py#L142-L203
def run_opt(self, popsize, numgen, processors, plot=False, log=False, **kwargs): """ Runs the optimizer. :param popsize: :param numgen: :param processors: :param plot: :param log: :param kwargs: :return: """ self._pa...
[ "def", "run_opt", "(", "self", ",", "popsize", ",", "numgen", ",", "processors", ",", "plot", "=", "False", ",", "log", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_params", "[", "'popsize'", "]", "=", "popsize", "self", ".", "_p...
Runs the optimizer. :param popsize: :param numgen: :param processors: :param plot: :param log: :param kwargs: :return:
[ "Runs", "the", "optimizer", ".", ":", "param", "popsize", ":", ":", "param", "numgen", ":", ":", "param", "processors", ":", ":", "param", "plot", ":", ":", "param", "log", ":", ":", "param", "kwargs", ":", ":", "return", ":" ]
python
train
stephanepechard/projy
projy/cmdline.py
https://github.com/stephanepechard/projy/blob/3146b0e3c207b977e1b51fcb33138746dae83c23/projy/cmdline.py#L41-L51
def run_list(): """ Print the list of all available templates. """ term = TerminalView() term.print_info("These are the available templates:") import pkgutil, projy.templates pkgpath = os.path.dirname(projy.templates.__file__) templates = [name for _, name, _ in pkgutil.iter_modules([pkgpath])] ...
[ "def", "run_list", "(", ")", ":", "term", "=", "TerminalView", "(", ")", "term", ".", "print_info", "(", "\"These are the available templates:\"", ")", "import", "pkgutil", ",", "projy", ".", "templates", "pkgpath", "=", "os", ".", "path", ".", "dirname", "(...
Print the list of all available templates.
[ "Print", "the", "list", "of", "all", "available", "templates", "." ]
python
train
elastic/elasticsearch-py
elasticsearch/client/xpack/ml.py
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/xpack/ml.py#L478-L502
def get_model_snapshots(self, job_id, snapshot_id=None, body=None, params=None): """ `<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-snapshot.html>`_ :arg job_id: The ID of the job to fetch :arg snapshot_id: The ID of the snapshot to fetch :arg body: Mode...
[ "def", "get_model_snapshots", "(", "self", ",", "job_id", ",", "snapshot_id", "=", "None", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "if", "job_id", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a requir...
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-get-snapshot.html>`_ :arg job_id: The ID of the job to fetch :arg snapshot_id: The ID of the snapshot to fetch :arg body: Model snapshot selection criteria :arg desc: True if the results should be sorted in descending o...
[ "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "ml", "-", "get", "-", "snapshot", ".", "html", ">", "_" ]
python
train
ciena/afkak
afkak/_protocol.py
https://github.com/ciena/afkak/blob/6f5e05ba6f135ea3c29cdb80efda009f7845569a/afkak/_protocol.py#L94-L101
def connectionLost(self, reason=connectionDone): """ Mark the protocol as failed and fail all pending operations. """ self._failed = reason pending, self._pending = self._pending, None for d in pending.values(): d.errback(reason)
[ "def", "connectionLost", "(", "self", ",", "reason", "=", "connectionDone", ")", ":", "self", ".", "_failed", "=", "reason", "pending", ",", "self", ".", "_pending", "=", "self", ".", "_pending", ",", "None", "for", "d", "in", "pending", ".", "values", ...
Mark the protocol as failed and fail all pending operations.
[ "Mark", "the", "protocol", "as", "failed", "and", "fail", "all", "pending", "operations", "." ]
python
train
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_output.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_output.py#L90-L103
def cmd_output_remove(self, args): '''remove an output''' device = args[0] for i in range(len(self.mpstate.mav_outputs)): conn = self.mpstate.mav_outputs[i] if str(i) == device or conn.address == device: print("Removing output %s" % conn.address) ...
[ "def", "cmd_output_remove", "(", "self", ",", "args", ")", ":", "device", "=", "args", "[", "0", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "mpstate", ".", "mav_outputs", ")", ")", ":", "conn", "=", "self", ".", "mpstate", ".", ...
remove an output
[ "remove", "an", "output" ]
python
train
tchellomello/python-arlo
pyarlo/__init__.py
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/__init__.py#L86-L91
def cleanup_headers(self): """Reset the headers and params.""" headers = {'Content-Type': 'application/json'} headers['Authorization'] = self.__token self.__headers = headers self.__params = {}
[ "def", "cleanup_headers", "(", "self", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "headers", "[", "'Authorization'", "]", "=", "self", ".", "__token", "self", ".", "__headers", "=", "headers", "self", ".", "__params", "=...
Reset the headers and params.
[ "Reset", "the", "headers", "and", "params", "." ]
python
train
basecrm/basecrm-python
basecrm/services.py
https://github.com/basecrm/basecrm-python/blob/7c1cf97dbaba8aeb9ff89f8a54f945a8702349f6/basecrm/services.py#L81-L103
def create(self, deal_id, *args, **kwargs): """ Create an associated contact Creates a deal's associated contact and its role If the specified deal or contact does not exist, the request will return an error :calls: ``post /deals/{deal_id}/associated_contacts`` :param i...
[ "def", "create", "(", "self", ",", "deal_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "args", "and", "not", "kwargs", ":", "raise", "Exception", "(", "'attributes for AssociatedContact are missing'", ")", "attributes", "=", "args", ...
Create an associated contact Creates a deal's associated contact and its role If the specified deal or contact does not exist, the request will return an error :calls: ``post /deals/{deal_id}/associated_contacts`` :param int deal_id: Unique identifier of a Deal. :param tuple *a...
[ "Create", "an", "associated", "contact" ]
python
train
edx/django-user-tasks
user_tasks/rules.py
https://github.com/edx/django-user-tasks/blob/6a9cf3821f4d8e202e6b48703e6a62e2a889adfb/user_tasks/rules.py#L64-L78
def add_rules(): """ Use the rules provided in this module to implement authorization checks for the ``django-user-tasks`` models. These rules allow only superusers and the user who triggered a task to view its status or artifacts, cancel the task, or delete the status information and all its related a...
[ "def", "add_rules", "(", ")", ":", "rules", ".", "add_perm", "(", "'user_tasks.view_usertaskstatus'", ",", "STATUS_PERMISSION", ")", "rules", ".", "add_perm", "(", "'user_tasks.cancel_usertaskstatus'", ",", "STATUS_PERMISSION", ")", "rules", ".", "add_perm", "(", "'...
Use the rules provided in this module to implement authorization checks for the ``django-user-tasks`` models. These rules allow only superusers and the user who triggered a task to view its status or artifacts, cancel the task, or delete the status information and all its related artifacts. Only superusers ar...
[ "Use", "the", "rules", "provided", "in", "this", "module", "to", "implement", "authorization", "checks", "for", "the", "django", "-", "user", "-", "tasks", "models", "." ]
python
train
Yubico/python-pyhsm
pyhsm/val/validation_server.py
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validation_server.py#L122-L186
def do_GET(self): """ Process validation GET requests. All modes of validation (OTP, OATH and PWHASH) must be explicitly enabled in `args' to be allowed. """ if self.path.startswith(args.serve_url): res = None log_res = None mode = Non...
[ "def", "do_GET", "(", "self", ")", ":", "if", "self", ".", "path", ".", "startswith", "(", "args", ".", "serve_url", ")", ":", "res", "=", "None", "log_res", "=", "None", "mode", "=", "None", "params", "=", "urlparse", ".", "parse_qs", "(", "self", ...
Process validation GET requests. All modes of validation (OTP, OATH and PWHASH) must be explicitly enabled in `args' to be allowed.
[ "Process", "validation", "GET", "requests", "." ]
python
train
tensorflow/tensorboard
tensorboard/backend/event_processing/directory_watcher.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/backend/event_processing/directory_watcher.py#L96-L145
def _LoadInternal(self): """Internal implementation of Load(). The only difference between this and Load() is that the latter will throw DirectoryDeletedError on I/O errors if it thinks that the directory has been permanently deleted. Yields: All values that have not been yielded yet. ""...
[ "def", "_LoadInternal", "(", "self", ")", ":", "# If the loader exists, check it for a value.", "if", "not", "self", ".", "_loader", ":", "self", ".", "_InitializeLoader", "(", ")", "while", "True", ":", "# Yield all the new events in the path we're currently loading from."...
Internal implementation of Load(). The only difference between this and Load() is that the latter will throw DirectoryDeletedError on I/O errors if it thinks that the directory has been permanently deleted. Yields: All values that have not been yielded yet.
[ "Internal", "implementation", "of", "Load", "()", "." ]
python
train
uw-it-aca/uw-restclients-canvas
uw_canvas/external_tools.py
https://github.com/uw-it-aca/uw-restclients-canvas/blob/9845faf33d49a8f06908efc22640c001116d6ea2/uw_canvas/external_tools.py#L154-L162
def get_sessionless_launch_url_from_course_sis_id( self, tool_id, course_sis_id): """ Get a sessionless launch url for an external tool. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.generate_sessionless_launch """ return self.get_s...
[ "def", "get_sessionless_launch_url_from_course_sis_id", "(", "self", ",", "tool_id", ",", "course_sis_id", ")", ":", "return", "self", ".", "get_sessionless_launch_url_from_course", "(", "tool_id", ",", "self", ".", "_sis_id", "(", "course_sis_id", ",", "\"course\"", ...
Get a sessionless launch url for an external tool. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.generate_sessionless_launch
[ "Get", "a", "sessionless", "launch", "url", "for", "an", "external", "tool", "." ]
python
test
dslackw/slpkg
slpkg/main.py
https://github.com/dslackw/slpkg/blob/dd2e08a80e944d337d157b992167ba631a4343de/slpkg/main.py#L381-L418
def pkg_tracking(self): """Tracking package dependencies """ flag = [] options = [ "-t", "--tracking" ] additional_options = [ "--check-deps", "--graph=", "--case-ins" ] for arg in self.args[2:]: ...
[ "def", "pkg_tracking", "(", "self", ")", ":", "flag", "=", "[", "]", "options", "=", "[", "\"-t\"", ",", "\"--tracking\"", "]", "additional_options", "=", "[", "\"--check-deps\"", ",", "\"--graph=\"", ",", "\"--case-ins\"", "]", "for", "arg", "in", "self", ...
Tracking package dependencies
[ "Tracking", "package", "dependencies" ]
python
train
cjdrake/pyeda
pyeda/parsing/boolexpr.py
https://github.com/cjdrake/pyeda/blob/554ee53aa678f4b61bcd7e07ba2c74ddc749d665/pyeda/parsing/boolexpr.py#L593-L602
def _zom_arg(lexer): """Return zero or more arguments.""" tok = next(lexer) # ',' EXPR ZOM_X if isinstance(tok, COMMA): return (_expr(lexer), ) + _zom_arg(lexer) # null else: lexer.unpop_token(tok) return tuple()
[ "def", "_zom_arg", "(", "lexer", ")", ":", "tok", "=", "next", "(", "lexer", ")", "# ',' EXPR ZOM_X", "if", "isinstance", "(", "tok", ",", "COMMA", ")", ":", "return", "(", "_expr", "(", "lexer", ")", ",", ")", "+", "_zom_arg", "(", "lexer", ")", "...
Return zero or more arguments.
[ "Return", "zero", "or", "more", "arguments", "." ]
python
train
dossier/dossier.models
dossier/models/web/routes.py
https://github.com/dossier/dossier.models/blob/c9e282f690eab72963926329efe1600709e48b13/dossier/models/web/routes.py#L726-L741
def maybe_store_highlights(file_id, data, tfidf, kvlclient): '''wrapper around :func:`create_highlights` that stores the response payload in the `kvlayer` table called `highlights` as a stored value if data['store'] is `False`. This allows error values as well as successful responses from :func:`create...
[ "def", "maybe_store_highlights", "(", "file_id", ",", "data", ",", "tfidf", ",", "kvlclient", ")", ":", "payload", "=", "create_highlights", "(", "data", ",", "tfidf", ")", "if", "data", "[", "'store'", "]", "is", "True", ":", "stored_payload", "=", "{", ...
wrapper around :func:`create_highlights` that stores the response payload in the `kvlayer` table called `highlights` as a stored value if data['store'] is `False`. This allows error values as well as successful responses from :func:`create_highlights` to both get stored.
[ "wrapper", "around", ":", "func", ":", "create_highlights", "that", "stores", "the", "response", "payload", "in", "the", "kvlayer", "table", "called", "highlights", "as", "a", "stored", "value", "if", "data", "[", "store", "]", "is", "False", ".", "This", ...
python
train
huggingface/pytorch-pretrained-BERT
pytorch_pretrained_bert/modeling_gpt2.py
https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling_gpt2.py#L351-L362
def init_weights(self, module): """ Initialize the weights. """ if isinstance(module, (nn.Linear, nn.Embedding)): # Slightly different from the TF version which uses truncated_normal for initialization # cf https://github.com/pytorch/pytorch/pull/5617 module.w...
[ "def", "init_weights", "(", "self", ",", "module", ")", ":", "if", "isinstance", "(", "module", ",", "(", "nn", ".", "Linear", ",", "nn", ".", "Embedding", ")", ")", ":", "# Slightly different from the TF version which uses truncated_normal for initialization", "# c...
Initialize the weights.
[ "Initialize", "the", "weights", "." ]
python
train
mfcloud/python-zvm-sdk
zvmconnector/restclient.py
https://github.com/mfcloud/python-zvm-sdk/blob/de9994ceca764f5460ce51bd74237986341d8e3c/zvmconnector/restclient.py#L1001-L1008
def _save_file(self, data, path): """Save an file to the specified path. :param data: binary data of the file :param path: path to save the file to """ with open(path, 'wb') as tfile: for chunk in data: tfile.write(chunk)
[ "def", "_save_file", "(", "self", ",", "data", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'wb'", ")", "as", "tfile", ":", "for", "chunk", "in", "data", ":", "tfile", ".", "write", "(", "chunk", ")" ]
Save an file to the specified path. :param data: binary data of the file :param path: path to save the file to
[ "Save", "an", "file", "to", "the", "specified", "path", ".", ":", "param", "data", ":", "binary", "data", "of", "the", "file", ":", "param", "path", ":", "path", "to", "save", "the", "file", "to" ]
python
train
dtcooper/python-fitparse
fitparse/records.py
https://github.com/dtcooper/python-fitparse/blob/40fa2918c3e91bd8f89908ad3bad81c1c1189dd2/fitparse/records.py#L376-L387
def calculate(cls, byte_arr, crc=0): """Compute CRC for input bytes.""" for byte in byte_iter(byte_arr): # Taken verbatim from FIT SDK docs tmp = cls.CRC_TABLE[crc & 0xF] crc = (crc >> 4) & 0x0FFF crc = crc ^ tmp ^ cls.CRC_TABLE[byte & 0xF] tm...
[ "def", "calculate", "(", "cls", ",", "byte_arr", ",", "crc", "=", "0", ")", ":", "for", "byte", "in", "byte_iter", "(", "byte_arr", ")", ":", "# Taken verbatim from FIT SDK docs", "tmp", "=", "cls", ".", "CRC_TABLE", "[", "crc", "&", "0xF", "]", "crc", ...
Compute CRC for input bytes.
[ "Compute", "CRC", "for", "input", "bytes", "." ]
python
train
jonathf/chaospy
chaospy/poly/collection/arithmetics.py
https://github.com/jonathf/chaospy/blob/25ecfa7bf5608dc10c0b31d142ded0e3755f5d74/chaospy/poly/collection/arithmetics.py#L76-L130
def mul(*args): """Polynomial multiplication.""" if len(args) > 2: return add(args[0], add(args[1], args[1:])) if len(args) == 1: return args[0] part1, part2 = args if not isinstance(part2, Poly): if isinstance(part2, (float, int)): part2 = np.asarray(part2) ...
[ "def", "mul", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", ">", "2", ":", "return", "add", "(", "args", "[", "0", "]", ",", "add", "(", "args", "[", "1", "]", ",", "args", "[", "1", ":", "]", ")", ")", "if", "len", "(", "a...
Polynomial multiplication.
[ "Polynomial", "multiplication", "." ]
python
train
Jajcus/pyxmpp2
pyxmpp2/mainloop/threads.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L461-L502
def stop(self, join = False, timeout = None): """Stop the threads. :Parameters: - `join`: join the threads (wait until they exit) - `timeout`: maximum time (in seconds) to wait when `join` is `True`). No limit when `timeout` is `None`. """ logger.d...
[ "def", "stop", "(", "self", ",", "join", "=", "False", ",", "timeout", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"Closing the io handlers...\"", ")", "for", "handler", "in", "self", ".", "io_handlers", ":", "handler", ".", "close", "(", ")", ...
Stop the threads. :Parameters: - `join`: join the threads (wait until they exit) - `timeout`: maximum time (in seconds) to wait when `join` is `True`). No limit when `timeout` is `None`.
[ "Stop", "the", "threads", "." ]
python
valid
annoviko/pyclustering
pyclustering/nnet/cnn.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/nnet/cnn.py#L449-L476
def show_network(self): """! @brief Shows structure of the network: neurons and connections between them. """ dimension = len(self.__location[0]) if (dimension != 3) and (dimension != 2): raise NameError('Network that is located in different ...
[ "def", "show_network", "(", "self", ")", ":", "dimension", "=", "len", "(", "self", ".", "__location", "[", "0", "]", ")", "if", "(", "dimension", "!=", "3", ")", "and", "(", "dimension", "!=", "2", ")", ":", "raise", "NameError", "(", "'Network that...
! @brief Shows structure of the network: neurons and connections between them.
[ "!" ]
python
valid
inasafe/inasafe
safe/gui/tools/wizard/step_fc90_analysis.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/wizard/step_fc90_analysis.py#L302-L310
def show_busy(self): """Lock buttons and enable the busy cursor.""" self.progress_bar.show() self.parent.pbnNext.setEnabled(False) self.parent.pbnBack.setEnabled(False) self.parent.pbnCancel.setEnabled(False) self.parent.repaint() enable_busy_cursor() QgsA...
[ "def", "show_busy", "(", "self", ")", ":", "self", ".", "progress_bar", ".", "show", "(", ")", "self", ".", "parent", ".", "pbnNext", ".", "setEnabled", "(", "False", ")", "self", ".", "parent", ".", "pbnBack", ".", "setEnabled", "(", "False", ")", "...
Lock buttons and enable the busy cursor.
[ "Lock", "buttons", "and", "enable", "the", "busy", "cursor", "." ]
python
train
python-security/pyt
pyt/formatters/screen.py
https://github.com/python-security/pyt/blob/efc0cfb716e40e0c8df4098f1cc8cf43723cd31f/pyt/formatters/screen.py#L17-L46
def report( vulnerabilities, fileobj, print_sanitised, ): """ Prints issues in color-coded text format. Args: vulnerabilities: list of vulnerabilities to report fileobj: The output file object, which may be sys.stdout """ n_vulnerabilities = len(vulnerabilities) unsa...
[ "def", "report", "(", "vulnerabilities", ",", "fileobj", ",", "print_sanitised", ",", ")", ":", "n_vulnerabilities", "=", "len", "(", "vulnerabilities", ")", "unsanitised_vulnerabilities", "=", "[", "v", "for", "v", "in", "vulnerabilities", "if", "not", "isinsta...
Prints issues in color-coded text format. Args: vulnerabilities: list of vulnerabilities to report fileobj: The output file object, which may be sys.stdout
[ "Prints", "issues", "in", "color", "-", "coded", "text", "format", "." ]
python
train
benoitkugler/abstractDataLibrary
pyDLib/Core/sql.py
https://github.com/benoitkugler/abstractDataLibrary/blob/16be28e99837e40287a63803bbfdf67ac1806b7b/pyDLib/Core/sql.py#L209-L223
def cree_local_DB(scheme): """Create emmpt DB according to the given scheme : dict { table : [ (column_name, column_type), .. ]} Usefull at installation of application (and for developement) """ conn = LocalConnexion() req = "" for table, fields in scheme.items(): req += f"DROP TABLE IF ...
[ "def", "cree_local_DB", "(", "scheme", ")", ":", "conn", "=", "LocalConnexion", "(", ")", "req", "=", "\"\"", "for", "table", ",", "fields", "in", "scheme", ".", "items", "(", ")", ":", "req", "+=", "f\"DROP TABLE IF EXISTS {table};\"", "req_fields", "=", ...
Create emmpt DB according to the given scheme : dict { table : [ (column_name, column_type), .. ]} Usefull at installation of application (and for developement)
[ "Create", "emmpt", "DB", "according", "to", "the", "given", "scheme", ":", "dict", "{", "table", ":", "[", "(", "column_name", "column_type", ")", "..", "]", "}", "Usefull", "at", "installation", "of", "application", "(", "and", "for", "developement", ")" ...
python
train
attilaolah/diffbot.py
diffbot.py
https://github.com/attilaolah/diffbot.py/blob/b66d68a36a22c944297c0575413db23687029af4/diffbot.py#L195-L197
def api(name, url, token, **kwargs): """Shortcut for caling methods on `Client(token, version)`.""" return Client(token).api(name, url, **kwargs)
[ "def", "api", "(", "name", ",", "url", ",", "token", ",", "*", "*", "kwargs", ")", ":", "return", "Client", "(", "token", ")", ".", "api", "(", "name", ",", "url", ",", "*", "*", "kwargs", ")" ]
Shortcut for caling methods on `Client(token, version)`.
[ "Shortcut", "for", "caling", "methods", "on", "Client", "(", "token", "version", ")", "." ]
python
train
juju/python-libjuju
juju/utils.py
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/utils.py#L32-L43
def _read_ssh_key(): ''' Inner function for read_ssh_key, suitable for passing to our Executor. ''' default_data_dir = Path(Path.home(), ".local", "share", "juju") juju_data = os.environ.get("JUJU_DATA", default_data_dir) ssh_key_path = Path(juju_data, 'ssh', 'juju_id_rsa.pub') with ssh...
[ "def", "_read_ssh_key", "(", ")", ":", "default_data_dir", "=", "Path", "(", "Path", ".", "home", "(", ")", ",", "\".local\"", ",", "\"share\"", ",", "\"juju\"", ")", "juju_data", "=", "os", ".", "environ", ".", "get", "(", "\"JUJU_DATA\"", ",", "default...
Inner function for read_ssh_key, suitable for passing to our Executor.
[ "Inner", "function", "for", "read_ssh_key", "suitable", "for", "passing", "to", "our", "Executor", "." ]
python
train
GGiecold/Cluster_Ensembles
src/Cluster_Ensembles/Cluster_Ensembles.py
https://github.com/GGiecold/Cluster_Ensembles/blob/d1b1ce9f541fc937ac7c677e964520e0e9163dc7/src/Cluster_Ensembles/Cluster_Ensembles.py#L1224-L1322
def overlap_matrix(hdf5_file_name, consensus_labels, cluster_runs): """Writes on disk (in an HDF5 file whose handle is provided as the first argument to this function) a stack of matrices, each describing for a particular run the overlap of cluster ID's that are matching each of the cluster ID...
[ "def", "overlap_matrix", "(", "hdf5_file_name", ",", "consensus_labels", ",", "cluster_runs", ")", ":", "if", "reduce", "(", "operator", ".", "mul", ",", "cluster_runs", ".", "shape", ",", "1", ")", "==", "max", "(", "cluster_runs", ".", "shape", ")", ":",...
Writes on disk (in an HDF5 file whose handle is provided as the first argument to this function) a stack of matrices, each describing for a particular run the overlap of cluster ID's that are matching each of the cluster ID's stored in 'consensus_labels' (the vector of labels obtained by e...
[ "Writes", "on", "disk", "(", "in", "an", "HDF5", "file", "whose", "handle", "is", "provided", "as", "the", "first", "argument", "to", "this", "function", ")", "a", "stack", "of", "matrices", "each", "describing", "for", "a", "particular", "run", "the", "...
python
train
totalgood/nlpia
src/nlpia/loaders.py
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L806-L817
def get_ftp_filemeta(parsed_url, username='anonymous', password='nlpia@totalgood.com'): """ FIXME: Get file size, hostname, path metadata from FTP server using parsed_url (urlparse)""" return dict( url=parsed_url.geturl(), hostname=parsed_url.hostname, path=parsed_url.path, username=(parsed_url....
[ "def", "get_ftp_filemeta", "(", "parsed_url", ",", "username", "=", "'anonymous'", ",", "password", "=", "'nlpia@totalgood.com'", ")", ":", "return", "dict", "(", "url", "=", "parsed_url", ".", "geturl", "(", ")", ",", "hostname", "=", "parsed_url", ".", "ho...
FIXME: Get file size, hostname, path metadata from FTP server using parsed_url (urlparse)
[ "FIXME", ":", "Get", "file", "size", "hostname", "path", "metadata", "from", "FTP", "server", "using", "parsed_url", "(", "urlparse", ")" ]
python
train
PythonCharmers/python-future
src/future/types/newbytes.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/types/newbytes.py#L335-L359
def index(self, sub, *args): ''' Returns index of sub in bytes. Raises ValueError if byte is not in bytes and TypeError if can't be converted bytes or its length is not 1. ''' if isinstance(sub, int): if len(args) == 0: start, end = 0, len(self...
[ "def", "index", "(", "self", ",", "sub", ",", "*", "args", ")", ":", "if", "isinstance", "(", "sub", ",", "int", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "start", ",", "end", "=", "0", ",", "len", "(", "self", ")", "elif", "...
Returns index of sub in bytes. Raises ValueError if byte is not in bytes and TypeError if can't be converted bytes or its length is not 1.
[ "Returns", "index", "of", "sub", "in", "bytes", ".", "Raises", "ValueError", "if", "byte", "is", "not", "in", "bytes", "and", "TypeError", "if", "can", "t", "be", "converted", "bytes", "or", "its", "length", "is", "not", "1", "." ]
python
train
vsjha18/nsetools
nse.py
https://github.com/vsjha18/nsetools/blob/c306b568471701c19195d2f17e112cc92022d3e0/nse.py#L316-L321
def is_valid_index(self, code): """ returns: True | Flase , based on whether code is valid """ index_list = self.get_index_list() return True if code.upper() in index_list else False
[ "def", "is_valid_index", "(", "self", ",", "code", ")", ":", "index_list", "=", "self", ".", "get_index_list", "(", ")", "return", "True", "if", "code", ".", "upper", "(", ")", "in", "index_list", "else", "False" ]
returns: True | Flase , based on whether code is valid
[ "returns", ":", "True", "|", "Flase", "based", "on", "whether", "code", "is", "valid" ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/__init__.py#L12030-L12051
def _set_cee_map(self, v, load=False): """ Setter method for cee_map, mapped from YANG variable /cee_map (list) If this variable is read-only (config: false) in the source YANG file, then _set_cee_map is considered as a private method. Backends looking to populate this variable should do so via ...
[ "def", "_set_cee_map", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "base",...
Setter method for cee_map, mapped from YANG variable /cee_map (list) If this variable is read-only (config: false) in the source YANG file, then _set_cee_map is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_cee_map() directly.
[ "Setter", "method", "for", "cee_map", "mapped", "from", "YANG", "variable", "/", "cee_map", "(", "list", ")", "If", "this", "variable", "is", "read", "-", "only", "(", "config", ":", "false", ")", "in", "the", "source", "YANG", "file", "then", "_set_cee_...
python
train
persephone-tools/persephone
persephone/utterance.py
https://github.com/persephone-tools/persephone/blob/f94c63e4d5fe719fb1deba449b177bb299d225fb/persephone/utterance.py#L45-L65
def write_transcriptions(utterances: List[Utterance], tgt_dir: Path, ext: str, lazy: bool) -> None: """ Write the utterance transcriptions to files in the tgt_dir. Is lazy and checks if the file already exists. Args: utterances: A list of Utterance objects to be written. ...
[ "def", "write_transcriptions", "(", "utterances", ":", "List", "[", "Utterance", "]", ",", "tgt_dir", ":", "Path", ",", "ext", ":", "str", ",", "lazy", ":", "bool", ")", "->", "None", ":", "tgt_dir", ".", "mkdir", "(", "parents", "=", "True", ",", "e...
Write the utterance transcriptions to files in the tgt_dir. Is lazy and checks if the file already exists. Args: utterances: A list of Utterance objects to be written. tgt_dir: The directory in which to write the text of the utterances, one file per utterance. ext: The file ...
[ "Write", "the", "utterance", "transcriptions", "to", "files", "in", "the", "tgt_dir", ".", "Is", "lazy", "and", "checks", "if", "the", "file", "already", "exists", "." ]
python
train
ask/redish
redish/client.py
https://github.com/ask/redish/blob/4845f8d5e12fd953ecad624b4e1e89f79a082a3e/redish/client.py#L135-L142
def rename(self, old_name, new_name): """Rename key to a new name.""" try: self.api.rename(mkey(old_name), mkey(new_name)) except ResponseError, exc: if "no such key" in exc.args: raise KeyError(old_name) raise
[ "def", "rename", "(", "self", ",", "old_name", ",", "new_name", ")", ":", "try", ":", "self", ".", "api", ".", "rename", "(", "mkey", "(", "old_name", ")", ",", "mkey", "(", "new_name", ")", ")", "except", "ResponseError", ",", "exc", ":", "if", "\...
Rename key to a new name.
[ "Rename", "key", "to", "a", "new", "name", "." ]
python
train