repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
saltstack/salt
salt/states/rabbitmq_vhost.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_vhost.py#L35-L93
def present(name): ''' Ensure the RabbitMQ VHost exists. name VHost name user Initial user permission to set on the VHost, if present .. deprecated:: 2015.8.0 owner Initial owner permission to set on the VHost, if present .. deprecated:: 2015.8.0 conf ...
[ "def", "present", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "vhost_exists", "=", "__salt__", "[", "'rabbitmq.vhost_exists'", "]", "(",...
Ensure the RabbitMQ VHost exists. name VHost name user Initial user permission to set on the VHost, if present .. deprecated:: 2015.8.0 owner Initial owner permission to set on the VHost, if present .. deprecated:: 2015.8.0 conf Initial conf string to ...
[ "Ensure", "the", "RabbitMQ", "VHost", "exists", "." ]
python
train
26.016949
craffel/mir_eval
mir_eval/segment.py
https://github.com/craffel/mir_eval/blob/f41c8dafaea04b411252a516d1965af43c7d531b/mir_eval/segment.py#L263-L321
def deviation(reference_intervals, estimated_intervals, trim=False): """Compute the median deviations between reference and estimated boundary times. Examples -------- >>> ref_intervals, _ = mir_eval.io.load_labeled_intervals('ref.lab') >>> est_intervals, _ = mir_eval.io.load_labeled_intervals(...
[ "def", "deviation", "(", "reference_intervals", ",", "estimated_intervals", ",", "trim", "=", "False", ")", ":", "validate_boundary", "(", "reference_intervals", ",", "estimated_intervals", ",", "trim", ")", "# Convert intervals to boundaries", "reference_boundaries", "="...
Compute the median deviations between reference and estimated boundary times. Examples -------- >>> ref_intervals, _ = mir_eval.io.load_labeled_intervals('ref.lab') >>> est_intervals, _ = mir_eval.io.load_labeled_intervals('est.lab') >>> r_to_e, e_to_r = mir_eval.boundary.deviation(ref_interval...
[ "Compute", "the", "median", "deviations", "between", "reference", "and", "estimated", "boundary", "times", "." ]
python
train
37.559322
angr/angr
angr/calling_conventions.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/calling_conventions.py#L96-L111
def _fix_offset(self, state, size, arch=None): """ This is a hack to deal with small values being stored at offsets into large registers unpredictably """ if state is not None: arch = state.arch if arch is None: raise ValueError('Either "state" or "arch" ...
[ "def", "_fix_offset", "(", "self", ",", "state", ",", "size", ",", "arch", "=", "None", ")", ":", "if", "state", "is", "not", "None", ":", "arch", "=", "state", ".", "arch", "if", "arch", "is", "None", ":", "raise", "ValueError", "(", "'Either \"stat...
This is a hack to deal with small values being stored at offsets into large registers unpredictably
[ "This", "is", "a", "hack", "to", "deal", "with", "small", "values", "being", "stored", "at", "offsets", "into", "large", "registers", "unpredictably" ]
python
train
37.6875
NASA-AMMOS/AIT-Core
ait/core/bsc.py
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L649-L667
def get_capture_handler_config_by_name(self, name): ''' Return data for handlers of a given name. Args: name: Name of the capture handler(s) to return config data for. Returns: Dictionary dump from the named capture handler as given by the :f...
[ "def", "get_capture_handler_config_by_name", "(", "self", ",", "name", ")", ":", "handler_confs", "=", "[", "]", "for", "address", ",", "stream_capturer", "in", "self", ".", "_stream_capturers", ".", "iteritems", "(", ")", ":", "handler_data", "=", "stream_captu...
Return data for handlers of a given name. Args: name: Name of the capture handler(s) to return config data for. Returns: Dictionary dump from the named capture handler as given by the :func:`SocketStreamCapturer.dump_handler_config_data` method.
[ "Return", "data", "for", "handlers", "of", "a", "given", "name", "." ]
python
train
37.210526
proycon/pynlpl
pynlpl/textprocessors.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/textprocessors.py#L426-L441
def swap(tokens, maxdist=2): """Perform a swap operation on a sequence of tokens, exhaustively swapping all tokens up to the maximum specified distance. This is a subset of all permutations.""" assert maxdist >= 2 tokens = list(tokens) if maxdist > len(tokens): maxdist = len(tokens) l = len(...
[ "def", "swap", "(", "tokens", ",", "maxdist", "=", "2", ")", ":", "assert", "maxdist", ">=", "2", "tokens", "=", "list", "(", "tokens", ")", "if", "maxdist", ">", "len", "(", "tokens", ")", ":", "maxdist", "=", "len", "(", "tokens", ")", "l", "="...
Perform a swap operation on a sequence of tokens, exhaustively swapping all tokens up to the maximum specified distance. This is a subset of all permutations.
[ "Perform", "a", "swap", "operation", "on", "a", "sequence", "of", "tokens", "exhaustively", "swapping", "all", "tokens", "up", "to", "the", "maximum", "specified", "distance", ".", "This", "is", "a", "subset", "of", "all", "permutations", "." ]
python
train
42.125
duniter/duniter-python-api
duniterpy/grammars/output.py
https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/grammars/output.py#L143-L152
def token(cls: Type[CLTVType], timestamp: int) -> CLTVType: """ Return CLTV instance from timestamp :param timestamp: Timestamp :return: """ cltv = cls() cltv.timestamp = str(timestamp) return cltv
[ "def", "token", "(", "cls", ":", "Type", "[", "CLTVType", "]", ",", "timestamp", ":", "int", ")", "->", "CLTVType", ":", "cltv", "=", "cls", "(", ")", "cltv", ".", "timestamp", "=", "str", "(", "timestamp", ")", "return", "cltv" ]
Return CLTV instance from timestamp :param timestamp: Timestamp :return:
[ "Return", "CLTV", "instance", "from", "timestamp" ]
python
train
25.3
icometrix/dicom2nifti
dicom2nifti/image_reorientation.py
https://github.com/icometrix/dicom2nifti/blob/1462ae5dd979fa3f276fe7a78ceb9b028121536f/dicom2nifti/image_reorientation.py#L112-L133
def _reorient_3d(image): """ Reorganize the data for a 3d nifti """ # Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size # of the array in each direction is the same with the corresponding direction of the input image. new_image = numpy.z...
[ "def", "_reorient_3d", "(", "image", ")", ":", "# Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size", "# of the array in each direction is the same with the corresponding direction of the input image.", "new_image", "=", "numpy", ".", ...
Reorganize the data for a 3d nifti
[ "Reorganize", "the", "data", "for", "a", "3d", "nifti" ]
python
train
58.090909
ConsenSys/mythril-classic
mythril/laser/smt/__init__.py
https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/laser/smt/__init__.py#L174-L178
def BitVecVal( value: int, size: int, annotations: Annotations = None ) -> z3.BitVecRef: """Creates a new bit vector with a concrete value.""" return z3.BitVecVal(value, size)
[ "def", "BitVecVal", "(", "value", ":", "int", ",", "size", ":", "int", ",", "annotations", ":", "Annotations", "=", "None", ")", "->", "z3", ".", "BitVecRef", ":", "return", "z3", ".", "BitVecVal", "(", "value", ",", "size", ")" ]
Creates a new bit vector with a concrete value.
[ "Creates", "a", "new", "bit", "vector", "with", "a", "concrete", "value", "." ]
python
train
39.8
okpy/ok-client
client/utils/locking.py
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/utils/locking.py#L5-L7
def lock(key, text): """Locks the given text using the given key and returns the result""" return hmac.new(key.encode('utf-8'), text.encode('utf-8')).hexdigest()
[ "def", "lock", "(", "key", ",", "text", ")", ":", "return", "hmac", ".", "new", "(", "key", ".", "encode", "(", "'utf-8'", ")", ",", "text", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")" ]
Locks the given text using the given key and returns the result
[ "Locks", "the", "given", "text", "using", "the", "given", "key", "and", "returns", "the", "result" ]
python
train
55.666667
wkentaro/pytorch-fcn
torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py
https://github.com/wkentaro/pytorch-fcn/blob/97189cbccb2c9b8bd776b356a1fd4b6c03f67d79/torchfcn/ext/fcn.berkeleyvision.org/nyud_layers.py#L125-L134
def load_label(self, idx): """ Load label image as 1 x height x width integer array of label indices. Shift labels so that classes are 0-39 and void is 255 (to ignore it). The leading singleton dimension is required by the loss. """ label = scipy.io.loadmat('{}/segmentati...
[ "def", "load_label", "(", "self", ",", "idx", ")", ":", "label", "=", "scipy", ".", "io", ".", "loadmat", "(", "'{}/segmentation/img_{}.mat'", ".", "format", "(", "self", ".", "nyud_dir", ",", "idx", ")", ")", "[", "'segmentation'", "]", ".", "astype", ...
Load label image as 1 x height x width integer array of label indices. Shift labels so that classes are 0-39 and void is 255 (to ignore it). The leading singleton dimension is required by the loss.
[ "Load", "label", "image", "as", "1", "x", "height", "x", "width", "integer", "array", "of", "label", "indices", ".", "Shift", "labels", "so", "that", "classes", "are", "0", "-", "39", "and", "void", "is", "255", "(", "to", "ignore", "it", ")", ".", ...
python
train
48.2
saltstack/salt
salt/utils/hashutils.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L117-L123
def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() )
[ "def", "sha512_digest", "(", "instr", ")", ":", "return", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "hashlib", ".", "sha512", "(", "salt", ".", "utils", ".", "stringutils", ".", "to_bytes", "(", "instr", ")", ")", ".", "hexdigest"...
Generate a sha512 hash of a given string
[ "Generate", "a", "sha512", "hash", "of", "a", "given", "string" ]
python
train
29.571429
ranaroussi/qtpylib
qtpylib/indicators.py
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/indicators.py#L598-L602
def pvt(bars): """ Price Volume Trend """ trend = ((bars['close'] - bars['close'].shift(1)) / bars['close'].shift(1)) * bars['volume'] return trend.cumsum()
[ "def", "pvt", "(", "bars", ")", ":", "trend", "=", "(", "(", "bars", "[", "'close'", "]", "-", "bars", "[", "'close'", "]", ".", "shift", "(", "1", ")", ")", "/", "bars", "[", "'close'", "]", ".", "shift", "(", "1", ")", ")", "*", "bars", "...
Price Volume Trend
[ "Price", "Volume", "Trend" ]
python
train
35.4
LogicalDash/LiSE
allegedb/allegedb/cache.py
https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/allegedb/allegedb/cache.py#L444-L473
def store(self, *args, planning=None, forward=None, loading=False, contra=True): """Put a value in various dictionaries for later .retrieve(...). Needs at least five arguments, of which the -1th is the value to store, the -2th is the tick to store it at, the -3th is the turn to store it...
[ "def", "store", "(", "self", ",", "*", "args", ",", "planning", "=", "None", ",", "forward", "=", "None", ",", "loading", "=", "False", ",", "contra", "=", "True", ")", ":", "db", "=", "self", ".", "db", "if", "planning", "is", "None", ":", "plan...
Put a value in various dictionaries for later .retrieve(...). Needs at least five arguments, of which the -1th is the value to store, the -2th is the tick to store it at, the -3th is the turn to store it in, the -4th is the branch the revision is in, the -5th is the key the value is for...
[ "Put", "a", "value", "in", "various", "dictionaries", "for", "later", ".", "retrieve", "(", "...", ")", "." ]
python
train
46.9
rkhleics/wagtailmodeladmin
wagtailmodeladmin/templatetags/wagtailmodeladmin_tags.py
https://github.com/rkhleics/wagtailmodeladmin/blob/7fddc853bab2ff3868b8c7a03329308c55f16358/wagtailmodeladmin/templatetags/wagtailmodeladmin_tags.py#L26-L78
def items_for_result(view, result): """ Generates the actual list of data. """ model_admin = view.model_admin for field_name in view.list_display: empty_value_display = model_admin.get_empty_value_display() row_classes = ['field-%s' % field_name] try: f, attr, val...
[ "def", "items_for_result", "(", "view", ",", "result", ")", ":", "model_admin", "=", "view", ".", "model_admin", "for", "field_name", "in", "view", ".", "list_display", ":", "empty_value_display", "=", "model_admin", ".", "get_empty_value_display", "(", ")", "ro...
Generates the actual list of data.
[ "Generates", "the", "actual", "list", "of", "data", "." ]
python
train
48.886792
pygobject/pgi
pgi/codegen/utils.py
https://github.com/pygobject/pgi/blob/2090435df6241a15ec2a78379a36b738b728652c/pgi/codegen/utils.py#L94-L102
def add_dependency(self, name, obj): """Add a code dependency so it gets inserted into globals""" if name in self._deps: if self._deps[name] is obj: return raise ValueError( "There exists a different dep with the same name : %r" % name) se...
[ "def", "add_dependency", "(", "self", ",", "name", ",", "obj", ")", ":", "if", "name", "in", "self", ".", "_deps", ":", "if", "self", ".", "_deps", "[", "name", "]", "is", "obj", ":", "return", "raise", "ValueError", "(", "\"There exists a different dep ...
Add a code dependency so it gets inserted into globals
[ "Add", "a", "code", "dependency", "so", "it", "gets", "inserted", "into", "globals" ]
python
train
36.888889
sixty-north/cosmic-ray
src/cosmic_ray/commands/init.py
https://github.com/sixty-north/cosmic-ray/blob/c654e074afbb7b7fcbc23359083c1287c0d3e991/src/cosmic_ray/commands/init.py#L77-L82
def apply_interceptors(work_db, enabled_interceptors): """Apply each registered interceptor to the WorkDB.""" names = (name for name in interceptor_names() if name in enabled_interceptors) for name in names: interceptor = get_interceptor(name) interceptor(work_db)
[ "def", "apply_interceptors", "(", "work_db", ",", "enabled_interceptors", ")", ":", "names", "=", "(", "name", "for", "name", "in", "interceptor_names", "(", ")", "if", "name", "in", "enabled_interceptors", ")", "for", "name", "in", "names", ":", "interceptor"...
Apply each registered interceptor to the WorkDB.
[ "Apply", "each", "registered", "interceptor", "to", "the", "WorkDB", "." ]
python
train
47.833333
woolfson-group/isambard
isambard/optimisation/evo_optimizers.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/optimisation/evo_optimizers.py#L472-L477
def _initial_individual(self): """Generates an individual with random parameters within bounds.""" ind = creator.Individual( [random.uniform(-1, 1) for _ in range(len(self.value_means))]) return ind
[ "def", "_initial_individual", "(", "self", ")", ":", "ind", "=", "creator", ".", "Individual", "(", "[", "random", ".", "uniform", "(", "-", "1", ",", "1", ")", "for", "_", "in", "range", "(", "len", "(", "self", ".", "value_means", ")", ")", "]", ...
Generates an individual with random parameters within bounds.
[ "Generates", "an", "individual", "with", "random", "parameters", "within", "bounds", "." ]
python
train
40.333333
mosdef-hub/mbuild
mbuild/utils/conversion.py
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/utils/conversion.py#L4-L23
def RB_to_OPLS(c0, c1, c2, c3, c4, c5): """Converts Ryckaert-Bellemans type dihedrals to OPLS type. Parameters ---------- c0, c1, c2, c3, c4, c5 : Ryckaert-Belleman coefficients (in kcal/mol) Returns ------- opls_coeffs : np.array, shape=(4,) Array containing the OPLS dihedrals coe...
[ "def", "RB_to_OPLS", "(", "c0", ",", "c1", ",", "c2", ",", "c3", ",", "c4", ",", "c5", ")", ":", "f1", "=", "(", "-", "1.5", "*", "c3", ")", "-", "(", "2", "*", "c1", ")", "f2", "=", "c0", "+", "c1", "+", "c3", "f3", "=", "-", "0.5", ...
Converts Ryckaert-Bellemans type dihedrals to OPLS type. Parameters ---------- c0, c1, c2, c3, c4, c5 : Ryckaert-Belleman coefficients (in kcal/mol) Returns ------- opls_coeffs : np.array, shape=(4,) Array containing the OPLS dihedrals coeffs f1, f2, f3, and f4 (in kcal/mol)
[ "Converts", "Ryckaert", "-", "Bellemans", "type", "dihedrals", "to", "OPLS", "type", "." ]
python
train
24.3
rq/rq-scheduler
rq_scheduler/scheduler.py
https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L217-L239
def cron(self, cron_string, func, args=None, kwargs=None, repeat=None, queue_name=None, id=None, timeout=None, description=None, meta=None): """ Schedule a cronjob """ scheduled_time = get_next_scheduled_time(cron_string) # Set result_ttl to -1, as jobs scheduled vi...
[ "def", "cron", "(", "self", ",", "cron_string", ",", "func", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "repeat", "=", "None", ",", "queue_name", "=", "None", ",", "id", "=", "None", ",", "timeout", "=", "None", ",", "description", ...
Schedule a cronjob
[ "Schedule", "a", "cronjob" ]
python
train
39.086957
rackerlabs/fleece
fleece/handlers/connexion.py
https://github.com/rackerlabs/fleece/blob/42d79dfa0777e99dbb09bc46105449a9be5dbaa9/fleece/handlers/connexion.py#L63-L150
def call_api(self, event): """Make a request against the API defined by this app. Return any result from the API call as a JSON object/dict. In the event of a client or server error response from the API endpoint handler (4xx or 5xx), raise a :class:`fleece.httperror.HTTPError` containi...
[ "def", "call_api", "(", "self", ",", "event", ")", ":", "try", ":", "environ", "=", "_build_wsgi_env", "(", "event", ",", "self", ".", "import_name", ")", "response", "=", "werkzeug", ".", "wrappers", ".", "Response", ".", "from_app", "(", "self", ",", ...
Make a request against the API defined by this app. Return any result from the API call as a JSON object/dict. In the event of a client or server error response from the API endpoint handler (4xx or 5xx), raise a :class:`fleece.httperror.HTTPError` containing some context about the erro...
[ "Make", "a", "request", "against", "the", "API", "defined", "by", "this", "app", "." ]
python
train
49.840909
NoneGG/aredis
aredis/commands/strings.py
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/strings.py#L228-L237
async def psetex(self, name, time_ms, value): """ Set the value of key ``name`` to ``value`` that expires in ``time_ms`` milliseconds. ``time_ms`` can be represented by an integer or a Python timedelta object """ if isinstance(time_ms, datetime.timedelta): ms ...
[ "async", "def", "psetex", "(", "self", ",", "name", ",", "time_ms", ",", "value", ")", ":", "if", "isinstance", "(", "time_ms", ",", "datetime", ".", "timedelta", ")", ":", "ms", "=", "int", "(", "time_ms", ".", "microseconds", "/", "1000", ")", "tim...
Set the value of key ``name`` to ``value`` that expires in ``time_ms`` milliseconds. ``time_ms`` can be represented by an integer or a Python timedelta object
[ "Set", "the", "value", "of", "key", "name", "to", "value", "that", "expires", "in", "time_ms", "milliseconds", ".", "time_ms", "can", "be", "represented", "by", "an", "integer", "or", "a", "Python", "timedelta", "object" ]
python
train
49.8
turbidsoul/tsutil
tsutil/encoder.py
https://github.com/turbidsoul/tsutil/blob/2c86d872791edc0f17f2c48b6f15d5c79b4551f7/tsutil/encoder.py#L72-L95
def base64_decode(data): """ Base 64 decoder """ data = data.replace(__enc64__[64], '') total = len(data) result = [] mod = 0 for i in range(total): mod = i % 4 cur = __enc64__.index(data[i]) if mod == 0: continue elif mod == 1: pre...
[ "def", "base64_decode", "(", "data", ")", ":", "data", "=", "data", ".", "replace", "(", "__enc64__", "[", "64", "]", ",", "''", ")", "total", "=", "len", "(", "data", ")", "result", "=", "[", "]", "mod", "=", "0", "for", "i", "in", "range", "(...
Base 64 decoder
[ "Base", "64", "decoder" ]
python
train
27.833333
DataONEorg/d1_python
gmn/src/d1_gmn/app/auth.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/auth.py#L164-L195
def is_allowed(request, level, pid): """Check if one or more subjects are allowed to perform action level on object. If a subject holds permissions for one action level on object, all lower action levels are also allowed. Any included subject that is unknown to this MN is treated as a subject without p...
[ "def", "is_allowed", "(", "request", ",", "level", ",", "pid", ")", ":", "if", "is_trusted_subject", "(", "request", ")", ":", "return", "True", "return", "d1_gmn", ".", "app", ".", "models", ".", "Permission", ".", "objects", ".", "filter", "(", "sciobj...
Check if one or more subjects are allowed to perform action level on object. If a subject holds permissions for one action level on object, all lower action levels are also allowed. Any included subject that is unknown to this MN is treated as a subject without permissions. Returns: bool ...
[ "Check", "if", "one", "or", "more", "subjects", "are", "allowed", "to", "perform", "action", "level", "on", "object", "." ]
python
train
41.9375
stefankoegl/kdtree
kdtree.py
https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L399-L428
def search_knn(self, point, k, dist=None): """ Return the k nearest neighbors of point and their distances point must be an actual point, not a node. k is the number of results to return. The actual results can be less (if there aren't more nodes to return) or more in case of equal ...
[ "def", "search_knn", "(", "self", ",", "point", ",", "k", ",", "dist", "=", "None", ")", ":", "if", "k", "<", "1", ":", "raise", "ValueError", "(", "\"k must be greater than 0.\"", ")", "if", "dist", "is", "None", ":", "get_dist", "=", "lambda", "n", ...
Return the k nearest neighbors of point and their distances point must be an actual point, not a node. k is the number of results to return. The actual results can be less (if there aren't more nodes to return) or more in case of equal distances. dist is a distance function, e...
[ "Return", "the", "k", "nearest", "neighbors", "of", "point", "and", "their", "distances" ]
python
train
33.833333
sebdah/dynamic-dynamodb
dynamic_dynamodb/statistics/table.py
https://github.com/sebdah/dynamic-dynamodb/blob/bfd0ca806b1c3301e724696de90ef0f973410493/dynamic_dynamodb/statistics/table.py#L14-L55
def get_consumed_read_units_percent( table_name, lookback_window_start=15, lookback_period=5): """ Returns the number of consumed read units in percent :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: Relative...
[ "def", "get_consumed_read_units_percent", "(", "table_name", ",", "lookback_window_start", "=", "15", ",", "lookback_period", "=", "5", ")", ":", "try", ":", "metrics", "=", "__get_aws_metric", "(", "table_name", ",", "lookback_window_start", ",", "lookback_period", ...
Returns the number of consumed read units in percent :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookback_window_start: Relative start time for the CloudWatch metric :type lookback_period: int :param lookback_period: Number of minu...
[ "Returns", "the", "number", "of", "consumed", "read", "units", "in", "percent" ]
python
train
32.119048
Devoxin/Lavalink.py
examples/music-v2.py
https://github.com/Devoxin/Lavalink.py/blob/63f55c3d726d24c4cfd3674d3cd6aab6f5be110d/examples/music-v2.py#L91-L109
async def _seek(self, ctx, *, time: str): """ Seeks to a given position in a track. """ player = self.bot.lavalink.players.get(ctx.guild.id) if not player.is_playing: return await ctx.send('Not playing.') seconds = time_rx.search(time) if not seconds: ...
[ "async", "def", "_seek", "(", "self", ",", "ctx", ",", "*", ",", "time", ":", "str", ")", ":", "player", "=", "self", ".", "bot", ".", "lavalink", ".", "players", ".", "get", "(", "ctx", ".", "guild", ".", "id", ")", "if", "not", "player", ".",...
Seeks to a given position in a track.
[ "Seeks", "to", "a", "given", "position", "in", "a", "track", "." ]
python
valid
35.421053
lpantano/seqcluster
seqcluster/seqbuster/snps.py
https://github.com/lpantano/seqcluster/blob/774e23add8cd4fdc83d626cea3bd1f458e7d060d/seqcluster/seqbuster/snps.py#L40-L56
def _get_pct(isomirs, mirna): """ Get pct of variants respect to the reference using reads and different sequences """ pass_pos = [] for isomir in isomirs.iterrows(): mir = isomir[1]["chrom"] mut = isomir[1]["sv"] mut_counts = isomir[1]["counts"] total = mirna.loc...
[ "def", "_get_pct", "(", "isomirs", ",", "mirna", ")", ":", "pass_pos", "=", "[", "]", "for", "isomir", "in", "isomirs", ".", "iterrows", "(", ")", ":", "mir", "=", "isomir", "[", "1", "]", "[", "\"chrom\"", "]", "mut", "=", "isomir", "[", "1", "]...
Get pct of variants respect to the reference using reads and different sequences
[ "Get", "pct", "of", "variants", "respect", "to", "the", "reference", "using", "reads", "and", "different", "sequences" ]
python
train
34.411765
liampauling/betfair
betfairlightweight/filters.py
https://github.com/liampauling/betfair/blob/8479392eb4849c525d78d43497c32c0bb108e977/betfairlightweight/filters.py#L144-L160
def price_projection(price_data=price_data(), ex_best_offers_overrides=ex_best_offers_overrides(), virtualise=True, rollover_stakes=False): """ Selection criteria of the returning price data. :param list price_data: PriceData filter to specify what market data we wish to receive. :p...
[ "def", "price_projection", "(", "price_data", "=", "price_data", "(", ")", ",", "ex_best_offers_overrides", "=", "ex_best_offers_overrides", "(", ")", ",", "virtualise", "=", "True", ",", "rollover_stakes", "=", "False", ")", ":", "args", "=", "locals", "(", "...
Selection criteria of the returning price data. :param list price_data: PriceData filter to specify what market data we wish to receive. :param dict ex_best_offers_overrides: define order book depth, rollup method. :param bool virtualise: whether to receive virtualised prices also. :param bool rollover_...
[ "Selection", "criteria", "of", "the", "returning", "price", "data", ".", ":", "param", "list", "price_data", ":", "PriceData", "filter", "to", "specify", "what", "market", "data", "we", "wish", "to", "receive", ".", ":", "param", "dict", "ex_best_offers_overri...
python
train
45.352941
aboSamoor/polyglot
polyglot/transliteration/base.py
https://github.com/aboSamoor/polyglot/blob/d0d2aa8d06cec4e03bd96618ae960030f7069a17/polyglot/transliteration/base.py#L42-L49
def _encoder(self): """Transliterate a string from the input language to English.""" if self.source_lang == 'en': return Transliterator._dummy_coder else: weights = load_transliteration_table(self.source_lang) encoder_weights = weights["encoder"] return Transliterator._transliterate_...
[ "def", "_encoder", "(", "self", ")", ":", "if", "self", ".", "source_lang", "==", "'en'", ":", "return", "Transliterator", ".", "_dummy_coder", "else", ":", "weights", "=", "load_transliteration_table", "(", "self", ".", "source_lang", ")", "encoder_weights", ...
Transliterate a string from the input language to English.
[ "Transliterate", "a", "string", "from", "the", "input", "language", "to", "English", "." ]
python
train
42
ShadowBlip/Neteria
neteria/client.py
https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/client.py#L233-L321
def handle_message(self, msg, host): """Processes messages that have been delivered from the transport protocol Args: msg (string): The raw packet data delivered from the transport protocol. host (tuple): A tuple containing the (address, port) combination of ...
[ "def", "handle_message", "(", "self", ",", "msg", ",", "host", ")", ":", "logger", ".", "debug", "(", "\"Executing handle_message method.\"", ")", "response", "=", "None", "# Unserialize the data packet", "# If encryption is enabled, and we've receive the server's public key"...
Processes messages that have been delivered from the transport protocol Args: msg (string): The raw packet data delivered from the transport protocol. host (tuple): A tuple containing the (address, port) combination of the message's origin. Returns: ...
[ "Processes", "messages", "that", "have", "been", "delivered", "from", "the", "transport", "protocol" ]
python
train
39.044944
swimlane/swimlane-python
swimlane/core/fields/text.py
https://github.com/swimlane/swimlane-python/blob/588fc503a76799bcdb5aecdf2f64a6ee05e3922d/swimlane/core/fields/text.py#L15-L23
def set_python(self, value): """Set field internal value from the python representation of field value""" # hook exists to stringify before validation # set to string if not string or unicode if value is not None and not isinstance(value, self.supported_types) or isinstance(val...
[ "def", "set_python", "(", "self", ",", "value", ")", ":", "# hook exists to stringify before validation", "# set to string if not string or unicode", "if", "value", "is", "not", "None", "and", "not", "isinstance", "(", "value", ",", "self", ".", "supported_types", ")"...
Set field internal value from the python representation of field value
[ "Set", "field", "internal", "value", "from", "the", "python", "representation", "of", "field", "value" ]
python
train
45.333333
econ-ark/HARK
HARK/core.py
https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/core.py#L1047-L1074
def mill(self): ''' Processes the variables collected from agents using the function millRule, storing the results in attributes named in aggr_sow. Parameters ---------- none Returns ------- none ''' # Make a dictionary of inputs ...
[ "def", "mill", "(", "self", ")", ":", "# Make a dictionary of inputs for the millRule", "reap_vars_string", "=", "''", "for", "name", "in", "self", ".", "reap_vars", ":", "reap_vars_string", "+=", "' \\''", "+", "name", "+", "'\\' : self.'", "+", "name", "+", "'...
Processes the variables collected from agents using the function millRule, storing the results in attributes named in aggr_sow. Parameters ---------- none Returns ------- none
[ "Processes", "the", "variables", "collected", "from", "agents", "using", "the", "function", "millRule", "storing", "the", "results", "in", "attributes", "named", "in", "aggr_sow", "." ]
python
train
34
python-escpos/python-escpos
src/escpos/magicencode.py
https://github.com/python-escpos/python-escpos/blob/52719c0b7de8948fabdffd180a2d71c22cf4c02b/src/escpos/magicencode.py#L235-L245
def force_encoding(self, encoding): """Sets a fixed encoding. The change is emitted right away. From now one, this buffer will switch the code page anymore. However, it will still keep track of the current code page. """ if not encoding: self.disabled = False ...
[ "def", "force_encoding", "(", "self", ",", "encoding", ")", ":", "if", "not", "encoding", ":", "self", ".", "disabled", "=", "False", "else", ":", "self", ".", "write_with_encoding", "(", "encoding", ",", "None", ")", "self", ".", "disabled", "=", "True"...
Sets a fixed encoding. The change is emitted right away. From now one, this buffer will switch the code page anymore. However, it will still keep track of the current code page.
[ "Sets", "a", "fixed", "encoding", ".", "The", "change", "is", "emitted", "right", "away", "." ]
python
train
36.545455
Shapeways/coyote_framework
coyote_framework/database/coyote_db.py
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L242-L256
def get_object_from_dictionary_representation(dictionary, class_type): """Instantiates a new class (that takes no init params) and populates its attributes with a dictionary @type dictionary: dict @param dictionary: Dictionary representation of the object @param class_type: type ...
[ "def", "get_object_from_dictionary_representation", "(", "dictionary", ",", "class_type", ")", ":", "assert", "inspect", ".", "isclass", "(", "class_type", ")", ",", "'Cannot instantiate an object that is not a class'", "instance", "=", "class_type", "(", ")", "CoyoteDb",...
Instantiates a new class (that takes no init params) and populates its attributes with a dictionary @type dictionary: dict @param dictionary: Dictionary representation of the object @param class_type: type @return: None
[ "Instantiates", "a", "new", "class", "(", "that", "takes", "no", "init", "params", ")", "and", "populates", "its", "attributes", "with", "a", "dictionary" ]
python
train
38
wavycloud/pyboto3
pyboto3/elasticbeanstalk.py
https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/elasticbeanstalk.py#L2729-L2886
def update_environment(ApplicationName=None, EnvironmentId=None, EnvironmentName=None, GroupName=None, Description=None, Tier=None, VersionLabel=None, TemplateName=None, SolutionStackName=None, PlatformArn=None, OptionSettings=None, OptionsToRemove=None): """ Updates the environment description, deploys a new a...
[ "def", "update_environment", "(", "ApplicationName", "=", "None", ",", "EnvironmentId", "=", "None", ",", "EnvironmentName", "=", "None", ",", "GroupName", "=", "None", ",", "Description", "=", "None", ",", "Tier", "=", "None", ",", "VersionLabel", "=", "Non...
Updates the environment description, deploys a new application version, updates the configuration settings to an entirely new configuration template, or updates select configuration option values in the running environment. Attempting to update both the release and configuration is not allowed and AWS Elastic Beans...
[ "Updates", "the", "environment", "description", "deploys", "a", "new", "application", "version", "updates", "the", "configuration", "settings", "to", "an", "entirely", "new", "configuration", "template", "or", "updates", "select", "configuration", "option", "values", ...
python
train
48.905063
sirfoga/pyhal
hal/mongodb/models.py
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/mongodb/models.py#L25-L33
def get_documents_count(self): """Counts documents in database :return: Number of documents in db """ db_collections = [ self.database[c] for c in self.get_collection_names() ] # list of all collections in database return sum([c.count() for c in db_collectio...
[ "def", "get_documents_count", "(", "self", ")", ":", "db_collections", "=", "[", "self", ".", "database", "[", "c", "]", "for", "c", "in", "self", ".", "get_collection_names", "(", ")", "]", "# list of all collections in database", "return", "sum", "(", "[", ...
Counts documents in database :return: Number of documents in db
[ "Counts", "documents", "in", "database" ]
python
train
35.111111
croscon/fleaker
fleaker/marshmallow/fields/phone_number.py
https://github.com/croscon/fleaker/blob/046b026b79c9912bceebb17114bc0c5d2d02e3c7/fleaker/marshmallow/fields/phone_number.py#L89-L94
def _deserialize(self, value, attr, data): """Format and validate the phone number using libphonenumber.""" if value: value = self._format_phone_number(value, attr) return super(PhoneNumberField, self)._deserialize(value, attr, data)
[ "def", "_deserialize", "(", "self", ",", "value", ",", "attr", ",", "data", ")", ":", "if", "value", ":", "value", "=", "self", ".", "_format_phone_number", "(", "value", ",", "attr", ")", "return", "super", "(", "PhoneNumberField", ",", "self", ")", "...
Format and validate the phone number using libphonenumber.
[ "Format", "and", "validate", "the", "phone", "number", "using", "libphonenumber", "." ]
python
train
44.166667
HiPERCAM/hcam_widgets
hcam_widgets/widgets.py
https://github.com/HiPERCAM/hcam_widgets/blob/7219f0d96dd3a8ebe3139c7f542a72c02d02fce8/hcam_widgets/widgets.py#L430-L445
def validate(self, value): """ Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes. """ try: # trap blank fields here if not self.blank or value: v = int(value) ...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "try", ":", "# trap blank fields here", "if", "not", "self", ".", "blank", "or", "value", ":", "v", "=", "int", "(", "value", ")", "if", "v", "<", "0", ":", "return", "None", "return", "value", ...
Applies the validation criteria. Returns value, new value, or None if invalid. Overload this in derived classes.
[ "Applies", "the", "validation", "criteria", ".", "Returns", "value", "new", "value", "or", "None", "if", "invalid", "." ]
python
train
26.75
JasonKessler/scattertext
scattertext/diachronic/GanttChart.py
https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/diachronic/GanttChart.py#L72-L89
def get_temporal_score_df(self): ''' Returns ------- ''' scoredf = {} tdf = self.term_ranker(self.corpus).get_ranks() for cat in sorted(self.corpus.get_categories()): if cat >= self.starting_time_step: negative_categories = self._get_negative_categories(cat, tdf) scores = self.term_scorer.get_...
[ "def", "get_temporal_score_df", "(", "self", ")", ":", "scoredf", "=", "{", "}", "tdf", "=", "self", ".", "term_ranker", "(", "self", ".", "corpus", ")", ".", "get_ranks", "(", ")", "for", "cat", "in", "sorted", "(", "self", ".", "corpus", ".", "get_...
Returns -------
[ "Returns", "-------" ]
python
train
29.055556
redhat-cip/dci-control-server
dci/trackers/__init__.py
https://github.com/redhat-cip/dci-control-server/blob/b416cf935ec93e4fdd5741f61a21cabecf8454d2/dci/trackers/__init__.py#L39-L54
def dump(self): """Return the object itself.""" return { 'title': self.title, 'issue_id': self.issue_id, 'reporter': self.reporter, 'assignee': self.assignee, 'status': self.status, 'product': self.product, 'component':...
[ "def", "dump", "(", "self", ")", ":", "return", "{", "'title'", ":", "self", ".", "title", ",", "'issue_id'", ":", "self", ".", "issue_id", ",", "'reporter'", ":", "self", ".", "reporter", ",", "'assignee'", ":", "self", ".", "assignee", ",", "'status'...
Return the object itself.
[ "Return", "the", "object", "itself", "." ]
python
train
31.375
apache/incubator-heron
heron/tools/ui/src/python/handlers/api/topology.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/heron/tools/ui/src/python/handlers/api/topology.py#L37-L82
def get(self, cluster, environ, topology, comp_name): ''' :param cluster: :param environ: :param topology: :param comp_name: :return: ''' start_time = time.time() comp_names = [] if comp_name == "All": lplan = yield access.get_logical_plan(cluster, environ, topology) ...
[ "def", "get", "(", "self", ",", "cluster", ",", "environ", ",", "topology", ",", "comp_name", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "comp_names", "=", "[", "]", "if", "comp_name", "==", "\"All\"", ":", "lplan", "=", "yield", "ac...
:param cluster: :param environ: :param topology: :param comp_name: :return:
[ ":", "param", "cluster", ":", ":", "param", "environ", ":", ":", "param", "topology", ":", ":", "param", "comp_name", ":", ":", "return", ":" ]
python
valid
33.586957
abilian/abilian-core
abilian/services/vocabularies/models.py
https://github.com/abilian/abilian-core/blob/0a71275bf108c3d51e13ca9e093c0249235351e3/abilian/services/vocabularies/models.py#L23-L29
def by_label(self, label): """Like `.get()`, but by label.""" # don't use .first(), so that MultipleResultsFound can be raised try: return self.filter_by(label=label).one() except sa.orm.exc.NoResultFound: return None
[ "def", "by_label", "(", "self", ",", "label", ")", ":", "# don't use .first(), so that MultipleResultsFound can be raised", "try", ":", "return", "self", ".", "filter_by", "(", "label", "=", "label", ")", ".", "one", "(", ")", "except", "sa", ".", "orm", ".", ...
Like `.get()`, but by label.
[ "Like", ".", "get", "()", "but", "by", "label", "." ]
python
train
38.142857
fake-name/ChromeController
logSetup.py
https://github.com/fake-name/ChromeController/blob/914dd136184e8f1165c7aa6ef30418aaf10c61f0/logSetup.py#L51-L81
def resetLoggingLocks(): ''' This function is a HACK! Basically, if we fork() while a logging lock is held, the lock is /copied/ while in the acquired state. However, since we've forked, the thread that acquired the lock no longer exists, so it can never unlock the lock, and we end up blocking forever. Theref...
[ "def", "resetLoggingLocks", "(", ")", ":", "try", ":", "logging", ".", "_releaseLock", "(", ")", "except", "RuntimeError", ":", "pass", "# The lock is already released", "# Iterate over the root logger hierarchy, and", "# force-free all locks.", "# if logging.Logger.root", "f...
This function is a HACK! Basically, if we fork() while a logging lock is held, the lock is /copied/ while in the acquired state. However, since we've forked, the thread that acquired the lock no longer exists, so it can never unlock the lock, and we end up blocking forever. Therefore, we manually enter the logg...
[ "This", "function", "is", "a", "HACK!" ]
python
train
28.032258
bapakode/OmMongo
ommongo/query_expression.py
https://github.com/bapakode/OmMongo/blob/52b5a5420516dc709f2d2eb065818c7973991ce3/ommongo/query_expression.py#L216-L226
def within_radius_sphere(self, x, y, radius): """ Adapted from the Mongo docs:: session.query(Places).filter(Places.loc.within_radius_sphere(1, 2, 50) """ return QueryExpression({ self : {'$within' : { '$centerSphere' : [[x, y], radius...
[ "def", "within_radius_sphere", "(", "self", ",", "x", ",", "y", ",", "radius", ")", ":", "return", "QueryExpression", "(", "{", "self", ":", "{", "'$within'", ":", "{", "'$centerSphere'", ":", "[", "[", "x", ",", "y", "]", ",", "radius", "]", ",", ...
Adapted from the Mongo docs:: session.query(Places).filter(Places.loc.within_radius_sphere(1, 2, 50)
[ "Adapted", "from", "the", "Mongo", "docs", "::" ]
python
train
31.454545
mitsei/dlkit
dlkit/json_/hierarchy/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/hierarchy/sessions.py#L573-L589
def remove_child(self, id_, child_id): """Removes a childfrom an ``Id``. arg: id (osid.id.Id): the ``Id`` of the node arg: child_id (osid.id.Id): the ``Id`` of the child to remove raise: NotFound - ``id`` or ``child_id`` was not found or ``child_id`` is not a chil...
[ "def", "remove_child", "(", "self", ",", "id_", ",", "child_id", ")", ":", "result", "=", "self", ".", "_rls", ".", "get_relationships_by_genus_type_for_peers", "(", "id_", ",", "child_id", ",", "self", ".", "_relationship_type", ")", "if", "not", "bool", "(...
Removes a childfrom an ``Id``. arg: id (osid.id.Id): the ``Id`` of the node arg: child_id (osid.id.Id): the ``Id`` of the child to remove raise: NotFound - ``id`` or ``child_id`` was not found or ``child_id`` is not a child of ``id`` raise: NullArgument - ``id`` ...
[ "Removes", "a", "childfrom", "an", "Id", "." ]
python
train
49.705882
lreis2415/PyGeoC
pygeoc/TauDEM.py
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L389-L398
def d8flowdir(np, filleddem, flowdir, slope, workingdir=None, mpiexedir=None, exedir=None, log_file=None, runtime_file=None, hostfile=None): """Run D8 flow direction""" fname = TauDEM.func_name('d8flowdir') return TauDEM.run(FileClass.get_executable_fullpath(fname, exedir), ...
[ "def", "d8flowdir", "(", "np", ",", "filleddem", ",", "flowdir", ",", "slope", ",", "workingdir", "=", "None", ",", "mpiexedir", "=", "None", ",", "exedir", "=", "None", ",", "log_file", "=", "None", ",", "runtime_file", "=", "None", ",", "hostfile", "...
Run D8 flow direction
[ "Run", "D8", "flow", "direction" ]
python
train
61.5
tamasgal/km3pipe
km3pipe/io/daq.py
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/daq.py#L567-L573
def _parse_snapshot_hits(self, file_obj): """Parse and store snapshot hits.""" for _ in range(self.n_snapshot_hits): dom_id, pmt_id = unpack('<ib', file_obj.read(5)) tdc_time = unpack('>I', file_obj.read(4))[0] tot = unpack('<b', file_obj.read(1))[0] self....
[ "def", "_parse_snapshot_hits", "(", "self", ",", "file_obj", ")", ":", "for", "_", "in", "range", "(", "self", ".", "n_snapshot_hits", ")", ":", "dom_id", ",", "pmt_id", "=", "unpack", "(", "'<ib'", ",", "file_obj", ".", "read", "(", "5", ")", ")", "...
Parse and store snapshot hits.
[ "Parse", "and", "store", "snapshot", "hits", "." ]
python
train
52.428571
flowersteam/explauto
explauto/models/pydmps/dmp.py
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/models/pydmps/dmp.py#L65-L71
def check_offset(self): """Check to see if initial position and goal are the same if they are, offset slightly so that the forcing term is not 0""" for d in range(self.dmps): if (self.y0[d] == self.goal[d]): self.goal[d] += 1e-4
[ "def", "check_offset", "(", "self", ")", ":", "for", "d", "in", "range", "(", "self", ".", "dmps", ")", ":", "if", "(", "self", ".", "y0", "[", "d", "]", "==", "self", ".", "goal", "[", "d", "]", ")", ":", "self", ".", "goal", "[", "d", "]"...
Check to see if initial position and goal are the same if they are, offset slightly so that the forcing term is not 0
[ "Check", "to", "see", "if", "initial", "position", "and", "goal", "are", "the", "same", "if", "they", "are", "offset", "slightly", "so", "that", "the", "forcing", "term", "is", "not", "0" ]
python
train
39.285714
mozilla-releng/signtool
signtool/util/paths.py
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/paths.py#L11-L17
def cygpath(filename): """Convert a cygwin path into a windows style path""" if sys.platform == 'cygwin': proc = Popen(['cygpath', '-am', filename], stdout=PIPE) return proc.communicate()[0].strip() else: return filename
[ "def", "cygpath", "(", "filename", ")", ":", "if", "sys", ".", "platform", "==", "'cygwin'", ":", "proc", "=", "Popen", "(", "[", "'cygpath'", ",", "'-am'", ",", "filename", "]", ",", "stdout", "=", "PIPE", ")", "return", "proc", ".", "communicate", ...
Convert a cygwin path into a windows style path
[ "Convert", "a", "cygwin", "path", "into", "a", "windows", "style", "path" ]
python
train
35.714286
annoviko/pyclustering
pyclustering/cluster/kmeans.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/kmeans.py#L75-L84
def notify(self, clusters, centers): """! @brief This method is called by K-Means algorithm to notify about changes. @param[in] clusters (array_like): Allocated clusters by K-Means algorithm. @param[in] centers (array_like): Allocated centers by K-Means algorithm. ...
[ "def", "notify", "(", "self", ",", "clusters", ",", "centers", ")", ":", "self", ".", "__evolution_clusters", ".", "append", "(", "clusters", ")", "self", ".", "__evolution_centers", ".", "append", "(", "centers", ")" ]
! @brief This method is called by K-Means algorithm to notify about changes. @param[in] clusters (array_like): Allocated clusters by K-Means algorithm. @param[in] centers (array_like): Allocated centers by K-Means algorithm.
[ "!" ]
python
valid
42.6
hendrix/hendrix
hendrix/facilities/resources.py
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/facilities/resources.py#L48-L57
def getChild(self, name, request): """ Postpath needs to contain all segments of the url, if it is incomplete then that incomplete url will be passed on to the child resource (in this case our wsgi application). """ request.prepath = [] request.postpath.insert(0, ...
[ "def", "getChild", "(", "self", ",", "name", ",", "request", ")", ":", "request", ".", "prepath", "=", "[", "]", "request", ".", "postpath", ".", "insert", "(", "0", ",", "name", ")", "# re-establishes request.postpath so to contain the entire path", "return", ...
Postpath needs to contain all segments of the url, if it is incomplete then that incomplete url will be passed on to the child resource (in this case our wsgi application).
[ "Postpath", "needs", "to", "contain", "all", "segments", "of", "the", "url", "if", "it", "is", "incomplete", "then", "that", "incomplete", "url", "will", "be", "passed", "on", "to", "the", "child", "resource", "(", "in", "this", "case", "our", "wsgi", "a...
python
train
42.2
GeorgeArgyros/symautomata
symautomata/pythonpda.py
https://github.com/GeorgeArgyros/symautomata/blob/f5d66533573b27e155bec3f36b8c00b8e3937cb3/symautomata/pythonpda.py#L96-L102
def printer(self): """Prints PDA states and their attributes""" i = 0 while i < self.n + 1: print "--------- State No --------" + repr(i) self.s[i].printer() i = i + 1
[ "def", "printer", "(", "self", ")", ":", "i", "=", "0", "while", "i", "<", "self", ".", "n", "+", "1", ":", "print", "\"--------- State No --------\"", "+", "repr", "(", "i", ")", "self", ".", "s", "[", "i", "]", ".", "printer", "(", ")", "i", ...
Prints PDA states and their attributes
[ "Prints", "PDA", "states", "and", "their", "attributes" ]
python
train
31.571429
tjvr/kurt
kurt/__init__.py
https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L232-L276
def load(cls, path, format=None): """Load project from file. Use ``format`` to specify the file format to use. Path can be a file-like object, in which case format is required. Otherwise, can guess the appropriate format from the extension. If you pass a file-like object, you'...
[ "def", "load", "(", "cls", ",", "path", ",", "format", "=", "None", ")", ":", "path_was_string", "=", "isinstance", "(", "path", ",", "basestring", ")", "if", "path_was_string", ":", "(", "folder", ",", "filename", ")", "=", "os", ".", "path", ".", "...
Load project from file. Use ``format`` to specify the file format to use. Path can be a file-like object, in which case format is required. Otherwise, can guess the appropriate format from the extension. If you pass a file-like object, you're responsible for closing the file. ...
[ "Load", "project", "from", "file", "." ]
python
train
34.8
vinci1it2000/schedula
schedula/utils/io.py
https://github.com/vinci1it2000/schedula/blob/addb9fd685be81544b796c51383ac00a31543ce9/schedula/utils/io.py#L16-L48
def save_dispatcher(dsp, path): """ Write Dispatcher object in Python pickle format. Pickles are a serialized byte stream of a Python object. This format will preserve Python objects used as nodes or edges. :param dsp: A dispatcher that identifies the model adopted. :type dsp: schedula...
[ "def", "save_dispatcher", "(", "dsp", ",", "path", ")", ":", "import", "dill", "with", "open", "(", "path", ",", "'wb'", ")", "as", "f", ":", "dill", ".", "dump", "(", "dsp", ",", "f", ")" ]
Write Dispatcher object in Python pickle format. Pickles are a serialized byte stream of a Python object. This format will preserve Python objects used as nodes or edges. :param dsp: A dispatcher that identifies the model adopted. :type dsp: schedula.Dispatcher :param path: File o...
[ "Write", "Dispatcher", "object", "in", "Python", "pickle", "format", "." ]
python
train
27.393939
pycontribs/pyrax
pyrax/clouddns.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/clouddns.py#L1437-L1464
def next(self): """ Return the next available item. If there are no more items in the local 'results' list, check if there is a 'next_uri' value. If so, use that to get the next page of results from the API, and return the first item from that query. """ try: ...
[ "def", "next", "(", "self", ")", ":", "try", ":", "return", "self", ".", "results", ".", "pop", "(", "0", ")", "except", "IndexError", ":", "if", "self", ".", "next_uri", "is", "None", ":", "raise", "StopIteration", "(", ")", "else", ":", "if", "no...
Return the next available item. If there are no more items in the local 'results' list, check if there is a 'next_uri' value. If so, use that to get the next page of results from the API, and return the first item from that query.
[ "Return", "the", "next", "available", "item", ".", "If", "there", "are", "no", "more", "items", "in", "the", "local", "results", "list", "check", "if", "there", "is", "a", "next_uri", "value", ".", "If", "so", "use", "that", "to", "get", "the", "next",...
python
train
38.928571
SystemRDL/systemrdl-compiler
systemrdl/core/BaseVisitor.py
https://github.com/SystemRDL/systemrdl-compiler/blob/6ae64f2bb6ecbbe9db356e20e8ac94e85bdeed3a/systemrdl/core/BaseVisitor.py#L29-L54
def datatype_from_token(self, token): """ Given a SystemRDLParser token, lookup the type This only includes types under the "data_type" grammar rule """ if token.type == SystemRDLParser.ID: # Is an identifier for either an enum or struct type typ = self....
[ "def", "datatype_from_token", "(", "self", ",", "token", ")", ":", "if", "token", ".", "type", "==", "SystemRDLParser", ".", "ID", ":", "# Is an identifier for either an enum or struct type", "typ", "=", "self", ".", "compiler", ".", "namespace", ".", "lookup_type...
Given a SystemRDLParser token, lookup the type This only includes types under the "data_type" grammar rule
[ "Given", "a", "SystemRDLParser", "token", "lookup", "the", "type", "This", "only", "includes", "types", "under", "the", "data_type", "grammar", "rule" ]
python
train
34.692308
rocky/python-xdis
xdis/magics.py
https://github.com/rocky/python-xdis/blob/46a2902ae8f5d8eee495eed67ac0690fd545453d/xdis/magics.py#L325-L355
def py_str2float(version): """Convert a Python version into a two-digit 'canonic' floating-point number, e.g. 2.5, 3.6. A runtime error is raised if "version" is not found. Note that there can be several strings that map to a single floating- point number. For example 3.2a1, 3.2.0, 3.2.2, 3.2.6 am...
[ "def", "py_str2float", "(", "version", ")", ":", "if", "version", ".", "endswith", "(", "'pypy'", ")", ":", "version", "=", "version", "[", ":", "-", "len", "(", "'pypy'", ")", "]", "if", "version", "in", "magics", ":", "magic", "=", "magics", "[", ...
Convert a Python version into a two-digit 'canonic' floating-point number, e.g. 2.5, 3.6. A runtime error is raised if "version" is not found. Note that there can be several strings that map to a single floating- point number. For example 3.2a1, 3.2.0, 3.2.2, 3.2.6 among others all map to 3.2.
[ "Convert", "a", "Python", "version", "into", "a", "two", "-", "digit", "canonic", "floating", "-", "point", "number", "e", ".", "g", ".", "2", ".", "5", "3", ".", "6", "." ]
python
train
34.096774
rsinger86/drf-flex-fields
rest_flex_fields/serializers.py
https://github.com/rsinger86/drf-flex-fields/blob/56495f15977d76697972acac571792e8fd67003d/rest_flex_fields/serializers.py#L77-L90
def _import_serializer_class(self, location): """ Resolves a dot-notation string to serializer class. <app>.<SerializerName> will automatically be interpreted as: <app>.serializers.<SerializerName> """ pieces = location.split(".") class_name = pieces.pop() ...
[ "def", "_import_serializer_class", "(", "self", ",", "location", ")", ":", "pieces", "=", "location", ".", "split", "(", "\".\"", ")", "class_name", "=", "pieces", ".", "pop", "(", ")", "if", "pieces", "[", "len", "(", "pieces", ")", "-", "1", "]", "...
Resolves a dot-notation string to serializer class. <app>.<SerializerName> will automatically be interpreted as: <app>.serializers.<SerializerName>
[ "Resolves", "a", "dot", "-", "notation", "string", "to", "serializer", "class", ".", "<app", ">", ".", "<SerializerName", ">", "will", "automatically", "be", "interpreted", "as", ":", "<app", ">", ".", "serializers", ".", "<SerializerName", ">" ]
python
train
35.5
MillionIntegrals/vel
vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/reinforcers/buffered_off_policy_iteration_reinforcer.py#L137-L158
def train_on_replay_memory(self, batch_info): """ Train agent on a memory gotten from replay buffer """ self.model.train() # Algo will aggregate data into this list: batch_info['sub_batch_data'] = [] for i in range(self.settings.training_rounds): sampled_rollout = s...
[ "def", "train_on_replay_memory", "(", "self", ",", "batch_info", ")", ":", "self", ".", "model", ".", "train", "(", ")", "# Algo will aggregate data into this list:", "batch_info", "[", "'sub_batch_data'", "]", "=", "[", "]", "for", "i", "in", "range", "(", "s...
Train agent on a memory gotten from replay buffer
[ "Train", "agent", "on", "a", "memory", "gotten", "from", "replay", "buffer" ]
python
train
37.045455
elmotec/massedit
massedit.py
https://github.com/elmotec/massedit/blob/57e22787354896d63a8850312314b19aa0308906/massedit.py#L66-L90
def get_function(fn_name): """Retrieve the function defined by the function_name. Arguments: fn_name: specification of the type module:function_name. """ module_name, callable_name = fn_name.split(':') current = globals() if not callable_name: callable_name = module_name else...
[ "def", "get_function", "(", "fn_name", ")", ":", "module_name", ",", "callable_name", "=", "fn_name", ".", "split", "(", "':'", ")", "current", "=", "globals", "(", ")", "if", "not", "callable_name", ":", "callable_name", "=", "module_name", "else", ":", "...
Retrieve the function defined by the function_name. Arguments: fn_name: specification of the type module:function_name.
[ "Retrieve", "the", "function", "defined", "by", "the", "function_name", "." ]
python
train
30.52
square/connect-python-sdk
squareconnect/models/money.py
https://github.com/square/connect-python-sdk/blob/adc1d09e817986cdc607391580f71d6b48ed4066/squareconnect/models/money.py#L64-L78
def amount(self, amount): """ Sets the amount of this Money. The amount of money, in the smallest denomination of the currency indicated by `currency`. For example, when `currency` is `USD`, `amount` is in cents. :param amount: The amount of this Money. :type: int """ ...
[ "def", "amount", "(", "self", ",", "amount", ")", ":", "if", "amount", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `amount`, must not be `None`\"", ")", "if", "amount", "<", "0", ":", "raise", "ValueError", "(", "\"Invalid value for `amount...
Sets the amount of this Money. The amount of money, in the smallest denomination of the currency indicated by `currency`. For example, when `currency` is `USD`, `amount` is in cents. :param amount: The amount of this Money. :type: int
[ "Sets", "the", "amount", "of", "this", "Money", ".", "The", "amount", "of", "money", "in", "the", "smallest", "denomination", "of", "the", "currency", "indicated", "by", "currency", ".", "For", "example", "when", "currency", "is", "USD", "amount", "is", "i...
python
train
37.933333
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L10731-L10753
def rotvec(v1, angle, iaxis): """ Transform a vector to a new coordinate system rotated by angle radians about axis iaxis. This transformation rotates v1 by angle radians about the specified axis. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rotvec_c.html :param v1: Vector whose co...
[ "def", "rotvec", "(", "v1", ",", "angle", ",", "iaxis", ")", ":", "v1", "=", "stypes", ".", "toDoubleVector", "(", "v1", ")", "angle", "=", "ctypes", ".", "c_double", "(", "angle", ")", "iaxis", "=", "ctypes", ".", "c_int", "(", "iaxis", ")", "vout...
Transform a vector to a new coordinate system rotated by angle radians about axis iaxis. This transformation rotates v1 by angle radians about the specified axis. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/rotvec_c.html :param v1: Vector whose coordinate system is to be rotated. :typ...
[ "Transform", "a", "vector", "to", "a", "new", "coordinate", "system", "rotated", "by", "angle", "radians", "about", "axis", "iaxis", ".", "This", "transformation", "rotates", "v1", "by", "angle", "radians", "about", "the", "specified", "axis", "." ]
python
train
36.913043
saltstack/salt
salt/loader.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L669-L692
def grain_funcs(opts, proxy=None): ''' Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__) ''' ret = LazyLoader( ...
[ "def", "grain_funcs", "(", "opts", ",", "proxy", "=", "None", ")", ":", "ret", "=", "LazyLoader", "(", "_module_dirs", "(", "opts", ",", "'grains'", ",", "'grain'", ",", "ext_type_dirs", "=", "'grains_dirs'", ",", ")", ",", "opts", ",", "tag", "=", "'g...
Returns the grain functions .. code-block:: python import salt.config import salt.loader __opts__ = salt.config.minion_config('/etc/salt/minion') grainfuncs = salt.loader.grain_funcs(__opts__)
[ "Returns", "the", "grain", "functions" ]
python
train
22.5
MonashBI/arcana
arcana/environment/requirement/base.py
https://github.com/MonashBI/arcana/blob/d6271a29d13733d00422d11417af8d200be62acc/arcana/environment/requirement/base.py#L393-L411
def v(self, version, max_version=None, **kwargs): """ Returns either a single requirement version or a requirement version range depending on whether two arguments are supplied or one Parameters ---------- version : str | Version Either a version of the requi...
[ "def", "v", "(", "self", ",", "version", ",", "max_version", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "version", ",", "Version", ")", ":", "version", "=", "self", ".", "version_cls", "(", "self", ",", "version",...
Returns either a single requirement version or a requirement version range depending on whether two arguments are supplied or one Parameters ---------- version : str | Version Either a version of the requirement, or the first version in a range of acceptable vers...
[ "Returns", "either", "a", "single", "requirement", "version", "or", "a", "requirement", "version", "range", "depending", "on", "whether", "two", "arguments", "are", "supplied", "or", "one" ]
python
train
41.789474
bids-standard/pybids
bids/layout/layout.py
https://github.com/bids-standard/pybids/blob/30d924ce770622bda0e390d613a8da42a2a20c32/bids/layout/layout.py#L444-L598
def get(self, return_type='object', target=None, extensions=None, scope='all', regex_search=False, defined_fields=None, absolute_paths=None, **kwargs): """ Retrieve files and/or metadata from the current Layout. Args: return_type (str): Type of re...
[ "def", "get", "(", "self", ",", "return_type", "=", "'object'", ",", "target", "=", "None", ",", "extensions", "=", "None", ",", "scope", "=", "'all'", ",", "regex_search", "=", "False", ",", "defined_fields", "=", "None", ",", "absolute_paths", "=", "No...
Retrieve files and/or metadata from the current Layout. Args: return_type (str): Type of result to return. Valid values: 'object' (default): return a list of matching BIDSFile objects. 'file': return a list of matching filenames. 'dir': return a list ...
[ "Retrieve", "files", "and", "/", "or", "metadata", "from", "the", "current", "Layout", "." ]
python
train
44.374194
njsmith/colorspacious
colorspacious/basics.py
https://github.com/njsmith/colorspacious/blob/59e0226003fb1b894597c5081e8ca5a3aa4fcefd/colorspacious/basics.py#L44-L55
def XYZ100_to_sRGB1_linear(XYZ100): """Convert XYZ to linear sRGB, where XYZ is normalized so that reference white D65 is X=95.05, Y=100, Z=108.90 and sRGB is on the 0-1 scale. Linear sRGB has a linear relationship to actual light, so it is an appropriate space for simulating light (e.g. for alpha blend...
[ "def", "XYZ100_to_sRGB1_linear", "(", "XYZ100", ")", ":", "XYZ100", "=", "np", ".", "asarray", "(", "XYZ100", ",", "dtype", "=", "float", ")", "# this is broadcasting matrix * array-of-vectors, where the vector is the", "# last dim", "RGB_linear", "=", "np", ".", "ein...
Convert XYZ to linear sRGB, where XYZ is normalized so that reference white D65 is X=95.05, Y=100, Z=108.90 and sRGB is on the 0-1 scale. Linear sRGB has a linear relationship to actual light, so it is an appropriate space for simulating light (e.g. for alpha blending).
[ "Convert", "XYZ", "to", "linear", "sRGB", "where", "XYZ", "is", "normalized", "so", "that", "reference", "white", "D65", "is", "X", "=", "95", ".", "05", "Y", "=", "100", "Z", "=", "108", ".", "90", "and", "sRGB", "is", "on", "the", "0", "-", "1"...
python
train
47.333333
Clinical-Genomics/trailblazer
trailblazer/mip/files.py
https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/files.py#L9-L31
def parse_config(data: dict) -> dict: """Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed data """ return { 'email': data.get('email'), 'family': data['family_id'], 'samples': [{ 'id': s...
[ "def", "parse_config", "(", "data", ":", "dict", ")", "->", "dict", ":", "return", "{", "'email'", ":", "data", ".", "get", "(", "'email'", ")", ",", "'family'", ":", "data", "[", "'family_id'", "]", ",", "'samples'", ":", "[", "{", "'id'", ":", "s...
Parse MIP config file. Args: data (dict): raw YAML input from MIP analysis config file Returns: dict: parsed data
[ "Parse", "MIP", "config", "file", "." ]
python
train
31.434783
isislovecruft/python-gnupg
pretty_bad_protocol/_util.py
https://github.com/isislovecruft/python-gnupg/blob/784571449032e811587249743e183fc5e908a673/pretty_bad_protocol/_util.py#L395-L433
def _find_binary(binary=None): """Find the absolute path to the GnuPG binary. Also run checks that the binary is not a symlink, and check that our process real uid has exec permissions. :param str binary: The path to the GnuPG binary. :raises: :exc:`~exceptions.RuntimeError` if it appears that Gnu...
[ "def", "_find_binary", "(", "binary", "=", "None", ")", ":", "found", "=", "None", "if", "binary", "is", "not", "None", ":", "if", "os", ".", "path", ".", "isabs", "(", "binary", ")", "and", "os", ".", "path", ".", "isfile", "(", "binary", ")", "...
Find the absolute path to the GnuPG binary. Also run checks that the binary is not a symlink, and check that our process real uid has exec permissions. :param str binary: The path to the GnuPG binary. :raises: :exc:`~exceptions.RuntimeError` if it appears that GnuPG is not installed. ...
[ "Find", "the", "absolute", "path", "to", "the", "GnuPG", "binary", "." ]
python
train
37.692308
emirozer/fake2db
fake2db/redis_handler.py
https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/redis_handler.py#L105-L121
def data_filler_user_agent(self, number_of_rows, pipe): '''creates keys with user agent data ''' try: for i in range(number_of_rows): pipe.hmset('user_agent:%s' % i, { 'id': rnd_id_generator(self), 'ip': self.faker.ipv4(), ...
[ "def", "data_filler_user_agent", "(", "self", ",", "number_of_rows", ",", "pipe", ")", ":", "try", ":", "for", "i", "in", "range", "(", "number_of_rows", ")", ":", "pipe", ".", "hmset", "(", "'user_agent:%s'", "%", "i", ",", "{", "'id'", ":", "rnd_id_gen...
creates keys with user agent data
[ "creates", "keys", "with", "user", "agent", "data" ]
python
train
36.647059
Kozea/pygal
pygal/graph/time.py
https://github.com/Kozea/pygal/blob/5e25c98a59a0642eecd9fcc5dbfeeb2190fbb5e7/pygal/graph/time.py#L66-L75
def time_to_seconds(x): """Convert a time in a seconds sum""" if isinstance(x, time): return ((((x.hour * 60) + x.minute) * 60 + x.second) * 10**6 + x.microsecond) / 10**6 if is_str(x): return x # Clamp to valid time return x and max(0, min(x, 24 * 3600 - 10**-6))
[ "def", "time_to_seconds", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "time", ")", ":", "return", "(", "(", "(", "(", "x", ".", "hour", "*", "60", ")", "+", "x", ".", "minute", ")", "*", "60", "+", "x", ".", "second", ")", "*", "...
Convert a time in a seconds sum
[ "Convert", "a", "time", "in", "a", "seconds", "sum" ]
python
train
30.8
ghukill/pyfc4
pyfc4/models.py
https://github.com/ghukill/pyfc4/blob/59011df592f08978c4a901a908862d112a5dcf02/pyfc4/models.py#L945-L983
def move(self, destination, remove_tombstone=True): ''' Method to move resource to another location. Note: by default, this method removes the tombstone at the resource's original URI. Can use optional flag remove_tombstone to keep tombstone on successful move. Note: other resource's triples that are manage...
[ "def", "move", "(", "self", ",", "destination", ",", "remove_tombstone", "=", "True", ")", ":", "# set move headers", "destination_uri", "=", "self", ".", "repo", ".", "parse_uri", "(", "destination", ")", "# http request", "response", "=", "self", ".", "repo"...
Method to move resource to another location. Note: by default, this method removes the tombstone at the resource's original URI. Can use optional flag remove_tombstone to keep tombstone on successful move. Note: other resource's triples that are managed by Fedora that point to this resource, *will* point to th...
[ "Method", "to", "move", "resource", "to", "another", "location", ".", "Note", ":", "by", "default", "this", "method", "removes", "the", "tombstone", "at", "the", "resource", "s", "original", "URI", ".", "Can", "use", "optional", "flag", "remove_tombstone", "...
python
train
32.820513
justquick/django-activity-stream
actstream/templatetags/activity_tags.py
https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/templatetags/activity_tags.py#L226-L241
def actor_url(parser, token): """ Renders the URL for a particular actor instance :: <a href="{% actor_url request.user %}">View your actions</a> <a href="{% actor_url another_user %}">{{ another_user }}'s actions</a> """ bits = token.split_contents() if len(bits) != 2: ...
[ "def", "actor_url", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "!=", "2", ":", "raise", "TemplateSyntaxError", "(", "\"Accepted format \"", "\"{% actor_url [actor_instance] %}\"", ...
Renders the URL for a particular actor instance :: <a href="{% actor_url request.user %}">View your actions</a> <a href="{% actor_url another_user %}">{{ another_user }}'s actions</a>
[ "Renders", "the", "URL", "for", "a", "particular", "actor", "instance" ]
python
train
30.0625
ewels/MultiQC
multiqc/utils/report.py
https://github.com/ewels/MultiQC/blob/2037d6322b2554146a74efbf869156ad20d4c4ec/multiqc/utils/report.py#L189-L256
def search_file (pattern, f): """ Function to searach a single file for a single search pattern. """ fn_matched = False contents_matched = False # Use mimetypes to exclude binary files where possible if not re.match(r'.+_mqc\.(png|jpg|jpeg)', f['fn']): (ftype, encoding) = mimetypes...
[ "def", "search_file", "(", "pattern", ",", "f", ")", ":", "fn_matched", "=", "False", "contents_matched", "=", "False", "# Use mimetypes to exclude binary files where possible", "if", "not", "re", ".", "match", "(", "r'.+_mqc\\.(png|jpg|jpeg)'", ",", "f", "[", "'fn'...
Function to searach a single file for a single search pattern.
[ "Function", "to", "searach", "a", "single", "file", "for", "a", "single", "search", "pattern", "." ]
python
train
43.220588
CiscoTestAutomation/yang
ncdiff/src/yang/ncdiff/model.py
https://github.com/CiscoTestAutomation/yang/blob/c70ec5ac5a91f276c4060009203770ece92e76b4/ncdiff/src/yang/ncdiff/model.py#L123-L150
def get_width(self, element): '''get_width High-level api: Calculate how much indent is needed for a node. Parameters ---------- element : `Element` A node in model tree. Returns ------- int Start position from the left margin....
[ "def", "get_width", "(", "self", ",", "element", ")", ":", "parent", "=", "element", ".", "getparent", "(", ")", "if", "parent", "in", "self", ".", "width", ":", "return", "self", ".", "width", "[", "parent", "]", "ret", "=", "0", "for", "sibling", ...
get_width High-level api: Calculate how much indent is needed for a node. Parameters ---------- element : `Element` A node in model tree. Returns ------- int Start position from the left margin.
[ "get_width" ]
python
train
23.75
azogue/dataweb
dataweb/mergedataweb.py
https://github.com/azogue/dataweb/blob/085035855df7cef0fe7725bbe9a706832344d946/dataweb/mergedataweb.py#L18-L35
def pdmerge_respeta_tz(func_merge, tz_ant=None, *args, **kwargs): """ Programación defensiva por issue: pandas BUG (a veces, el index pierde el tz): - issue #7795: concat of objects with the same timezone get reset to UTC; - issue #10567: DataFrame combine_first() loses timezone information for ...
[ "def", "pdmerge_respeta_tz", "(", "func_merge", ",", "tz_ant", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "df_merged", "=", "func_merge", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "tz_ant", "is", "not", "None", "and...
Programación defensiva por issue: pandas BUG (a veces, el index pierde el tz): - issue #7795: concat of objects with the same timezone get reset to UTC; - issue #10567: DataFrame combine_first() loses timezone information for datetime columns https://github.com/pydata/pandas/issues/10567 ...
[ "Programación", "defensiva", "por", "issue", ":", "pandas", "BUG", "(", "a", "veces", "el", "index", "pierde", "el", "tz", ")", ":", "-", "issue", "#7795", ":", "concat", "of", "objects", "with", "the", "same", "timezone", "get", "reset", "to", "UTC", ...
python
train
59.277778
suds-community/suds
suds/wsdl.py
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/wsdl.py#L261-L282
def add_methods(self, service): """Build method view for service.""" bindings = { "document/literal": Document(self), "rpc/literal": RPC(self), "rpc/encoded": Encoded(self)} for p in service.ports: binding = p.binding ptype = p.binding....
[ "def", "add_methods", "(", "self", ",", "service", ")", ":", "bindings", "=", "{", "\"document/literal\"", ":", "Document", "(", "self", ")", ",", "\"rpc/literal\"", ":", "RPC", "(", "self", ")", ",", "\"rpc/encoded\"", ":", "Encoded", "(", "self", ")", ...
Build method view for service.
[ "Build", "method", "view", "for", "service", "." ]
python
train
42.545455
ambitioninc/django-entity
entity/models.py
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/models.py#L147-L153
def cache_relationships(self, cache_super=True, cache_sub=True): """ Caches the super and sub relationships by doing a prefetch_related. """ relationships_to_cache = compress( ['super_relationships__super_entity', 'sub_relationships__sub_entity'], [cache_super, cache_sub]) ...
[ "def", "cache_relationships", "(", "self", ",", "cache_super", "=", "True", ",", "cache_sub", "=", "True", ")", ":", "relationships_to_cache", "=", "compress", "(", "[", "'super_relationships__super_entity'", ",", "'sub_relationships__sub_entity'", "]", ",", "[", "c...
Caches the super and sub relationships by doing a prefetch_related.
[ "Caches", "the", "super", "and", "sub", "relationships", "by", "doing", "a", "prefetch_related", "." ]
python
train
53.285714
saltstack/salt
salt/modules/dnsmasq.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dnsmasq.py#L163-L194
def _parse_dnamasq(filename): ''' Generic function for parsing dnsmasq files including includes. ''' fileopts = {} if not os.path.isfile(filename): raise CommandExecutionError( 'Error: No such file \'{0}\''.format(filename) ) with salt.utils.files.fopen(filename, 'r...
[ "def", "_parse_dnamasq", "(", "filename", ")", ":", "fileopts", "=", "{", "}", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "raise", "CommandExecutionError", "(", "'Error: No such file \\'{0}\\''", ".", "format", "(", "filename", ...
Generic function for parsing dnsmasq files including includes.
[ "Generic", "function", "for", "parsing", "dnsmasq", "files", "including", "includes", "." ]
python
train
34.75
msmbuilder/msmbuilder
msmbuilder/dataset.py
https://github.com/msmbuilder/msmbuilder/blob/556a93a170782f47be53f4a1e9d740fb1c8272b3/msmbuilder/dataset.py#L174-L204
def transform_with(self, estimator, out_ds, fmt=None): """Call the partial_transform method of the estimator on this dataset Parameters ---------- estimator : object with ``partial_fit`` method This object will be used to transform this dataset into a new dataset...
[ "def", "transform_with", "(", "self", ",", "estimator", ",", "out_ds", ",", "fmt", "=", "None", ")", ":", "if", "isinstance", "(", "out_ds", ",", "str", ")", ":", "out_ds", "=", "self", ".", "create_derived", "(", "out_ds", ",", "fmt", "=", "fmt", ")...
Call the partial_transform method of the estimator on this dataset Parameters ---------- estimator : object with ``partial_fit`` method This object will be used to transform this dataset into a new dataset. The estimator should be fitted prior to calling this...
[ "Call", "the", "partial_transform", "method", "of", "the", "estimator", "on", "this", "dataset" ]
python
train
39.354839
PyCQA/pydocstyle
src/pydocstyle/config.py
https://github.com/PyCQA/pydocstyle/blob/2549847f9efad225789f931e83dfe782418ca13e/src/pydocstyle/config.py#L411-L424
def _get_config_file_in_folder(cls, path): """Look for a configuration file in `path`. If exists return its full path, otherwise None. """ if os.path.isfile(path): path = os.path.dirname(path) for fn in cls.PROJECT_CONFIG_FILES: config = RawConfigParser...
[ "def", "_get_config_file_in_folder", "(", "cls", ",", "path", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "for", "fn", "in", "cls", ".", "PROJECT_CONFIG_FI...
Look for a configuration file in `path`. If exists return its full path, otherwise None.
[ "Look", "for", "a", "configuration", "file", "in", "path", "." ]
python
train
33
monarch-initiative/dipper
dipper/sources/ZFIN.py
https://github.com/monarch-initiative/dipper/blob/24cc80db355bbe15776edc5c7b41e0886959ba41/dipper/sources/ZFIN.py#L2235-L2287
def _process_uniprot_ids(self, limit=None): """ This method processes the mappings from ZFIN gene IDs to UniProtKB IDs. Triples created: <zfin_gene_id> a class <zfin_gene_id> rdfs:label gene_symbol <uniprot_id> is an Individual <uniprot_id> has type <polypeptide...
[ "def", "_process_uniprot_ids", "(", "self", ",", "limit", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"Processing UniProt IDs\"", ")", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", "graph", "=", "self", "...
This method processes the mappings from ZFIN gene IDs to UniProtKB IDs. Triples created: <zfin_gene_id> a class <zfin_gene_id> rdfs:label gene_symbol <uniprot_id> is an Individual <uniprot_id> has type <polypeptide> <zfin_gene_id> has_gene_product <uniprot_id> ...
[ "This", "method", "processes", "the", "mappings", "from", "ZFIN", "gene", "IDs", "to", "UniProtKB", "IDs", "." ]
python
train
32.679245
qualisys/qualisys_python_sdk
qtm/qrt.py
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L175-L181
async def stream_frames_stop(self): """Stop streaming frames.""" self._protocol.set_on_packet(None) cmd = "streamframes stop" await self._protocol.send_command(cmd, callback=False)
[ "async", "def", "stream_frames_stop", "(", "self", ")", ":", "self", ".", "_protocol", ".", "set_on_packet", "(", "None", ")", "cmd", "=", "\"streamframes stop\"", "await", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ",", "callback", "=", "Fal...
Stop streaming frames.
[ "Stop", "streaming", "frames", "." ]
python
valid
29.714286
DavidDoukhan/py_sonicvisualiser
py_sonicvisualiser/SVEnv.py
https://github.com/DavidDoukhan/py_sonicvisualiser/blob/ebe83bd7dffb0275393255dcbcc6671cf0ade4a5/py_sonicvisualiser/SVEnv.py#L145-L212
def add_continuous_annotations(self, x, y, colourName='Purple', colour='#c832ff', name='', view=None, vscale=None, presentationName=None): """ add a continous annotation layer Args: x (float iterable): temporal indices of the dataset y (float iterable): values of the dataset...
[ "def", "add_continuous_annotations", "(", "self", ",", "x", ",", "y", ",", "colourName", "=", "'Purple'", ",", "colour", "=", "'#c832ff'", ",", "name", "=", "''", ",", "view", "=", "None", ",", "vscale", "=", "None", ",", "presentationName", "=", "None",...
add a continous annotation layer Args: x (float iterable): temporal indices of the dataset y (float iterable): values of the dataset Kwargs: view (<DOM Element: view>): environment view used to display the spectrogram, if set to None, a new view is created Return...
[ "add", "a", "continous", "annotation", "layer" ]
python
train
43.485294
changhiskhan/poseidon
poseidon/droplet.py
https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L485-L496
def ip_address(self): """ Public ip_address """ ip = None for eth in self.networks['v4']: if eth['type'] == 'public': ip = eth['ip_address'] break if ip is None: raise ValueError("No public IP found") return ...
[ "def", "ip_address", "(", "self", ")", ":", "ip", "=", "None", "for", "eth", "in", "self", ".", "networks", "[", "'v4'", "]", ":", "if", "eth", "[", "'type'", "]", "==", "'public'", ":", "ip", "=", "eth", "[", "'ip_address'", "]", "break", "if", ...
Public ip_address
[ "Public", "ip_address" ]
python
valid
25.916667
Alignak-monitoring/alignak
alignak/daemon.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemon.py#L1803-L1851
def make_a_pause(self, timeout=0.0001, check_time_change=True): """ Wait up to timeout and check for system time change. This function checks if the system time changed since the last call. If so, the difference is returned to the caller. The duration of this call is removed from the ti...
[ "def", "make_a_pause", "(", "self", ",", "timeout", "=", "0.0001", ",", "check_time_change", "=", "True", ")", ":", "if", "timeout", "==", "0", ":", "timeout", "=", "0.0001", "if", "not", "check_time_change", ":", "# Time to sleep", "time", ".", "sleep", "...
Wait up to timeout and check for system time change. This function checks if the system time changed since the last call. If so, the difference is returned to the caller. The duration of this call is removed from the timeout. If this duration is greater than the required timeout, no sle...
[ "Wait", "up", "to", "timeout", "and", "check", "for", "system", "time", "change", "." ]
python
train
36.571429
xoolive/traffic
traffic/data/adsb/opensky.py
https://github.com/xoolive/traffic/blob/d1a8878098f16759f6b6e0e8d8b8f32e34a680a8/traffic/data/adsb/opensky.py#L76-L89
def plot(self, ax: GeoAxesSubplot, **kwargs) -> Artist: """Plotting function. All arguments are passed to the geometry""" if "facecolor" not in kwargs: kwargs["facecolor"] = "None" if "edgecolor" not in kwargs: kwargs["edgecolor"] = ax._get_lines.get_next_color() ...
[ "def", "plot", "(", "self", ",", "ax", ":", "GeoAxesSubplot", ",", "*", "*", "kwargs", ")", "->", "Artist", ":", "if", "\"facecolor\"", "not", "in", "kwargs", ":", "kwargs", "[", "\"facecolor\"", "]", "=", "\"None\"", "if", "\"edgecolor\"", "not", "in", ...
Plotting function. All arguments are passed to the geometry
[ "Plotting", "function", ".", "All", "arguments", "are", "passed", "to", "the", "geometry" ]
python
train
39.428571
softwarefactory-project/rdopkg
features/environment.py
https://github.com/softwarefactory-project/rdopkg/blob/2d2bed4e7cd329558a36d0dd404ec4ac8f9f254c/features/environment.py#L6-L16
def clean_tempdir(context, scenario): """ Clean up temporary test dirs for passed tests. Leave failed test dirs for manual inspection. """ tempdir = getattr(context, 'tempdir', None) if tempdir and scenario.status == 'passed': shutil.rmtree(tempdir) del(context.tempdir)
[ "def", "clean_tempdir", "(", "context", ",", "scenario", ")", ":", "tempdir", "=", "getattr", "(", "context", ",", "'tempdir'", ",", "None", ")", "if", "tempdir", "and", "scenario", ".", "status", "==", "'passed'", ":", "shutil", ".", "rmtree", "(", "tem...
Clean up temporary test dirs for passed tests. Leave failed test dirs for manual inspection.
[ "Clean", "up", "temporary", "test", "dirs", "for", "passed", "tests", "." ]
python
train
27.454545
cltk/cltk
cltk/stem/french/stem.py
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/stem/french/stem.py#L27-L51
def matchremove_noun_endings(word): """Remove the noun and adverb word endings""" was_stemmed = False """common and proper noun and adjective word endings sorted by charlen, then alph""" noun_endings = ['arons', 'ains', 'aron', 'ment', 'ain', 'age', 'on', 'es', 'ée', 'ee', 'ie', 's'] for ending i...
[ "def", "matchremove_noun_endings", "(", "word", ")", ":", "was_stemmed", "=", "False", "\"\"\"common and proper noun and adjective word endings sorted by charlen, then alph\"\"\"", "noun_endings", "=", "[", "'arons'", ",", "'ains'", ",", "'aron'", ",", "'ment'", ",", "'ain'...
Remove the noun and adverb word endings
[ "Remove", "the", "noun", "and", "adverb", "word", "endings" ]
python
train
30.2
biolink/ontobio
ontobio/golr/golr_query.py
https://github.com/biolink/ontobio/blob/4e512a7831cfe6bc1b32f2c3be2ba41bc5cf7345/ontobio/golr/golr_query.py#L1696-L1705
def mergeWithLabels(json, firstField, firstFieldLabel, secondField, secondFieldLabel): """ merge two fields of a json into an array of { firstFieldLabel : firstFieldLabel, secondFieldLabel : secondField } """ merged = [] for i in range(0, len(json[firstField])): merged.append({ firstFieldLa...
[ "def", "mergeWithLabels", "(", "json", ",", "firstField", ",", "firstFieldLabel", ",", "secondField", ",", "secondFieldLabel", ")", ":", "merged", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "json", "[", "firstField", "]", ")", ...
merge two fields of a json into an array of { firstFieldLabel : firstFieldLabel, secondFieldLabel : secondField }
[ "merge", "two", "fields", "of", "a", "json", "into", "an", "array", "of", "{", "firstFieldLabel", ":", "firstFieldLabel", "secondFieldLabel", ":", "secondField", "}" ]
python
train
42.2
zetaops/pyoko
pyoko/manage.py
https://github.com/zetaops/pyoko/blob/236c509ad85640933ac0f89ad8f7ed95f62adf07/pyoko/manage.py#L925-L932
def _get_model_nodes(self, model): """ Find all the non-auto created nodes of the model. """ nodes = [(name, node) for name, node in model._nodes.items() if node._is_auto_created is False] nodes.sort(key=lambda n: n[0]) return nodes
[ "def", "_get_model_nodes", "(", "self", ",", "model", ")", ":", "nodes", "=", "[", "(", "name", ",", "node", ")", "for", "name", ",", "node", "in", "model", ".", "_nodes", ".", "items", "(", ")", "if", "node", ".", "_is_auto_created", "is", "False", ...
Find all the non-auto created nodes of the model.
[ "Find", "all", "the", "non", "-", "auto", "created", "nodes", "of", "the", "model", "." ]
python
train
36.125
calmjs/calmjs
src/calmjs/vlqsm.py
https://github.com/calmjs/calmjs/blob/b9b407c2b6a7662da64bccba93bb8d92e7a5fafd/src/calmjs/vlqsm.py#L110-L122
def write_padding(self, s): """ Write string that are not part of the original file. """ lines = s.splitlines(True) for line in lines: self.stream.write(line) if line[-1] in '\r\n': self._newline() else: # this ...
[ "def", "write_padding", "(", "self", ",", "s", ")", ":", "lines", "=", "s", ".", "splitlines", "(", "True", ")", "for", "line", "in", "lines", ":", "self", ".", "stream", ".", "write", "(", "line", ")", "if", "line", "[", "-", "1", "]", "in", "...
Write string that are not part of the original file.
[ "Write", "string", "that", "are", "not", "part", "of", "the", "original", "file", "." ]
python
train
28.615385
cloudtools/stacker
stacker/actions/base.py
https://github.com/cloudtools/stacker/blob/ad6013a03a560c46ba3c63c4d153336273e6da5d/stacker/actions/base.py#L38-L61
def build_walker(concurrency): """This will return a function suitable for passing to :class:`stacker.plan.Plan` for walking the graph. If concurrency is 1 (no parallelism) this will return a simple topological walker that doesn't use any multithreading. If concurrency is 0, this will return a wal...
[ "def", "build_walker", "(", "concurrency", ")", ":", "if", "concurrency", "==", "1", ":", "return", "walk", "semaphore", "=", "UnlimitedSemaphore", "(", ")", "if", "concurrency", ">", "1", ":", "semaphore", "=", "threading", ".", "Semaphore", "(", "concurren...
This will return a function suitable for passing to :class:`stacker.plan.Plan` for walking the graph. If concurrency is 1 (no parallelism) this will return a simple topological walker that doesn't use any multithreading. If concurrency is 0, this will return a walker that will walk the graph as fa...
[ "This", "will", "return", "a", "function", "suitable", "for", "passing", "to", ":", "class", ":", "stacker", ".", "plan", ".", "Plan", "for", "walking", "the", "graph", "." ]
python
train
33.375
yunpian/yunpian-python-sdk
yunpian_python_sdk/model/result.py
https://github.com/yunpian/yunpian-python-sdk/blob/405a1196ec83fdf29ff454f74ef036974be11970/yunpian_python_sdk/model/result.py#L46-L51
def msg(self, msg=None, ret_r=False): '''code's message''' if msg or ret_r: self._msg = msg return self return self._msg
[ "def", "msg", "(", "self", ",", "msg", "=", "None", ",", "ret_r", "=", "False", ")", ":", "if", "msg", "or", "ret_r", ":", "self", ".", "_msg", "=", "msg", "return", "self", "return", "self", ".", "_msg" ]
code's message
[ "code", "s", "message" ]
python
train
27.166667
saltstack/salt
salt/modules/influxdb08mod.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L159-L189
def db_remove(name, user=None, password=None, host=None, port=None): ''' Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI ...
[ "def", "db_remove", "(", "name", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ")", ":", "if", "not", "db_exists", "(", "name", ",", "user", ",", "password", ",", "host", ",", "port", ...
Remove a database name Database name to remove user The user to connect as password The password of the user host The host to connect to port The port to connect to CLI Example: .. code-block:: bash salt '*' influxdb08.db_remove <name> ...
[ "Remove", "a", "database" ]
python
train
22.451613
Danielhiversen/pyTibber
tibber/__init__.py
https://github.com/Danielhiversen/pyTibber/blob/114ebc3dd49f6affd93665b0862d4cbdea03e9ef/tibber/__init__.py#L317-L352
async def update_current_price_info(self): """Update current price info async.""" query = gql( """ { viewer { home(id: "%s") { currentSubscription { priceInfo { current { energy ...
[ "async", "def", "update_current_price_info", "(", "self", ")", ":", "query", "=", "gql", "(", "\"\"\"\n {\n viewer {\n home(id: \"%s\") {\n currentSubscription {\n priceInfo {\n current {\n energy\n ...
Update current price info async.
[ "Update", "current", "price", "info", "async", "." ]
python
valid
29.5
appknox/pyaxmlparser
pyaxmlparser/axmlparser.py
https://github.com/appknox/pyaxmlparser/blob/8ffe43e81a534f42c3620f3c1e3c6c0181a066bd/pyaxmlparser/axmlparser.py#L408-L419
def namespace(self): """ Return the Namespace URI (if any) as a String for the current tag """ if self.m_name == -1 or (self.m_event != const.START_TAG and self.m_event != const.END_TAG): return u'' # No Namespace if self.m_namespaceUri == 0xFFFFFFFF: ...
[ "def", "namespace", "(", "self", ")", ":", "if", "self", ".", "m_name", "==", "-", "1", "or", "(", "self", ".", "m_event", "!=", "const", ".", "START_TAG", "and", "self", ".", "m_event", "!=", "const", ".", "END_TAG", ")", ":", "return", "u''", "# ...
Return the Namespace URI (if any) as a String for the current tag
[ "Return", "the", "Namespace", "URI", "(", "if", "any", ")", "as", "a", "String", "for", "the", "current", "tag" ]
python
train
30.75
metagriffin/pysyncml
pysyncml/items/note.py
https://github.com/metagriffin/pysyncml/blob/a583fe0dbffa8b24e5a3e151524f84868b2382bb/pysyncml/items/note.py#L66-L89
def dump(self, stream, contentType=None, version=None): ''' Serializes this NoteItem to a byte-stream and writes it to the file-like object `stream`. `contentType` and `version` must be one of the supported content-types, and if not specified, will default to ``text/plain``. ''' if contentTy...
[ "def", "dump", "(", "self", ",", "stream", ",", "contentType", "=", "None", ",", "version", "=", "None", ")", ":", "if", "contentType", "is", "None", "or", "contentType", "==", "constants", ".", "TYPE_TEXT_PLAIN", ":", "stream", ".", "write", "(", "self"...
Serializes this NoteItem to a byte-stream and writes it to the file-like object `stream`. `contentType` and `version` must be one of the supported content-types, and if not specified, will default to ``text/plain``.
[ "Serializes", "this", "NoteItem", "to", "a", "byte", "-", "stream", "and", "writes", "it", "to", "the", "file", "-", "like", "object", "stream", ".", "contentType", "and", "version", "must", "be", "one", "of", "the", "supported", "content", "-", "types", ...
python
valid
41.916667
onicagroup/runway
runway/hooks/staticsite/build_staticsite.py
https://github.com/onicagroup/runway/blob/3f3549ec3bf6e39b9f27d9738a1847f3a4369e7f/runway/hooks/staticsite/build_staticsite.py#L37-L54
def download_and_extract_to_mkdtemp(bucket, key, session=None): """Download zip archive and extract it to temporary directory.""" if session: s3_client = session.client('s3') else: s3_client = boto3.client('s3') transfer = S3Transfer(s3_client) filedes, temp_file = tempfile.mkstemp(...
[ "def", "download_and_extract_to_mkdtemp", "(", "bucket", ",", "key", ",", "session", "=", "None", ")", ":", "if", "session", ":", "s3_client", "=", "session", ".", "client", "(", "'s3'", ")", "else", ":", "s3_client", "=", "boto3", ".", "client", "(", "'...
Download zip archive and extract it to temporary directory.
[ "Download", "zip", "archive", "and", "extract", "it", "to", "temporary", "directory", "." ]
python
train
31.222222
internetarchive/warc
warc/warc.py
https://github.com/internetarchive/warc/blob/8f05a000a23bbd6501217e37cfd862ffdf19da7f/warc/warc.py#L306-L313
def tell(self): """Returns the file offset. If this is a compressed file, then the offset in the compressed file is returned. """ if isinstance(self.fileobj, gzip2.GzipFile): return self.fileobj.fileobj.tell() else: return self.fileobj.tell()
[ "def", "tell", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "fileobj", ",", "gzip2", ".", "GzipFile", ")", ":", "return", "self", ".", "fileobj", ".", "fileobj", ".", "tell", "(", ")", "else", ":", "return", "self", ".", "fileobj", ...
Returns the file offset. If this is a compressed file, then the offset in the compressed file is returned.
[ "Returns", "the", "file", "offset", ".", "If", "this", "is", "a", "compressed", "file", "then", "the", "offset", "in", "the", "compressed", "file", "is", "returned", "." ]
python
train
37.5
AtteqCom/zsl
src/zsl/utils/deploy/apiari_doc_generator.py
https://github.com/AtteqCom/zsl/blob/ab51a96da1780ff642912396d4b85bdcb72560c1/src/zsl/utils/deploy/apiari_doc_generator.py#L120-L136
def generate_apiary_doc(task_router): """Generate apiary documentation. Create a Apiary generator and add application packages to it. :param task_router: task router, injected :type task_router: TaskRouter :return: apiary generator :rtype: ApiaryDoc """ generator = ApiaryDoc() for...
[ "def", "generate_apiary_doc", "(", "task_router", ")", ":", "generator", "=", "ApiaryDoc", "(", ")", "for", "m", "in", "task_router", ".", "get_task_packages", "(", ")", "+", "get_method_packages", "(", ")", ":", "m", "=", "importlib", ".", "import_module", ...
Generate apiary documentation. Create a Apiary generator and add application packages to it. :param task_router: task router, injected :type task_router: TaskRouter :return: apiary generator :rtype: ApiaryDoc
[ "Generate", "apiary", "documentation", "." ]
python
train
26.941176