repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
KimiNewt/pyshark
src/pyshark/packet/fields.py
https://github.com/KimiNewt/pyshark/blob/089ea6208c4321f03bc548f491e00a053285918f/src/pyshark/packet/fields.py#L56-L64
def binary_value(self): """ Converts this field to binary (assuming it's a binary string) """ str_raw_value = str(self.raw_value) if len(str_raw_value) % 2 == 1: str_raw_value = '0' + str_raw_value return binascii.unhexlify(str_raw_value)
[ "def", "binary_value", "(", "self", ")", ":", "str_raw_value", "=", "str", "(", "self", ".", "raw_value", ")", "if", "len", "(", "str_raw_value", ")", "%", "2", "==", "1", ":", "str_raw_value", "=", "'0'", "+", "str_raw_value", "return", "binascii", ".",...
Converts this field to binary (assuming it's a binary string)
[ "Converts", "this", "field", "to", "binary", "(", "assuming", "it", "s", "a", "binary", "string", ")" ]
python
train
ZELLMECHANIK-DRESDEN/dclab
dclab/features/bright.py
https://github.com/ZELLMECHANIK-DRESDEN/dclab/blob/79002c4356e7020c2ba73ab0a3819c9abd4affec/dclab/features/bright.py#L12-L85
def get_bright(mask, image, ret_data="avg,sd"): """Compute avg and/or std of the event brightness The event brightness is defined by the gray-scale values of the image data within the event mask area. Parameters ---------- mask: ndarray or list of ndarrays of shape (M,N) and dtype bool ...
[ "def", "get_bright", "(", "mask", ",", "image", ",", "ret_data", "=", "\"avg,sd\"", ")", ":", "# This method is based on a pull request by Maik Herbig.", "ret_avg", "=", "\"avg\"", "in", "ret_data", "ret_std", "=", "\"sd\"", "in", "ret_data", "if", "ret_avg", "+", ...
Compute avg and/or std of the event brightness The event brightness is defined by the gray-scale values of the image data within the event mask area. Parameters ---------- mask: ndarray or list of ndarrays of shape (M,N) and dtype bool The mask values, True where the event is located in `i...
[ "Compute", "avg", "and", "/", "or", "std", "of", "the", "event", "brightness" ]
python
train
tensorflow/probability
tensorflow_probability/python/math/root_search.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/root_search.py#L44-L321
def secant_root(objective_fn, initial_position, next_position=None, value_at_position=None, position_tolerance=1e-8, value_tolerance=1e-8, max_iterations=50, stopping_policy_fn=tf.reduce_all, ...
[ "def", "secant_root", "(", "objective_fn", ",", "initial_position", ",", "next_position", "=", "None", ",", "value_at_position", "=", "None", ",", "position_tolerance", "=", "1e-8", ",", "value_tolerance", "=", "1e-8", ",", "max_iterations", "=", "50", ",", "sto...
r"""Finds root(s) of a function of single variable using the secant method. The [secant method](https://en.wikipedia.org/wiki/Secant_method) is a root-finding algorithm that uses a succession of roots of secant lines to better approximate a root of a function. The secant method can be thought of as a finite-di...
[ "r", "Finds", "root", "(", "s", ")", "of", "a", "function", "of", "single", "variable", "using", "the", "secant", "method", "." ]
python
test
marrow/WebCore
web/server/eventlet_.py
https://github.com/marrow/WebCore/blob/38d50f8022ca62976a1e5ff23f7714bd647b6532/web/server/eventlet_.py#L15-L22
def serve(application, host='127.0.0.1', port=8080): """Eventlet-based WSGI-HTTP server. For a more fully-featured Eventlet-capable interface, see also [Spawning](http://pypi.python.org/pypi/Spawning/). """ # Instantiate the server with a bound port and with our application. server(listen(host, int(port)), app...
[ "def", "serve", "(", "application", ",", "host", "=", "'127.0.0.1'", ",", "port", "=", "8080", ")", ":", "# Instantiate the server with a bound port and with our application.", "server", "(", "listen", "(", "host", ",", "int", "(", "port", ")", ")", ",", "applic...
Eventlet-based WSGI-HTTP server. For a more fully-featured Eventlet-capable interface, see also [Spawning](http://pypi.python.org/pypi/Spawning/).
[ "Eventlet", "-", "based", "WSGI", "-", "HTTP", "server", ".", "For", "a", "more", "fully", "-", "featured", "Eventlet", "-", "capable", "interface", "see", "also", "[", "Spawning", "]", "(", "http", ":", "//", "pypi", ".", "python", ".", "org", "/", ...
python
train
nccgroup/opinel
opinel/utils/aws.py
https://github.com/nccgroup/opinel/blob/2d4f5b96e0a1f9cb0356629f4f87e4ed99ce2606/opinel/utils/aws.py#L108-L139
def handle_truncated_response(callback, params, entities): """ Handle truncated responses :param callback: :param params: :param entities: :return: """ results = {} for entity in entities: results[entity] = [] while True: try: marker_found = False ...
[ "def", "handle_truncated_response", "(", "callback", ",", "params", ",", "entities", ")", ":", "results", "=", "{", "}", "for", "entity", "in", "entities", ":", "results", "[", "entity", "]", "=", "[", "]", "while", "True", ":", "try", ":", "marker_found...
Handle truncated responses :param callback: :param params: :param entities: :return:
[ "Handle", "truncated", "responses" ]
python
train
fkarb/xltable
xltable/workbook.py
https://github.com/fkarb/xltable/blob/7a592642d27ad5ee90d2aa8c26338abaa9d84bea/xltable/workbook.py#L62-L80
def to_xlsx(self, **kwargs): """ Write workbook to a .xlsx file using xlsxwriter. Return a xlsxwriter.workbook.Workbook. :param kwargs: Extra arguments passed to the xlsxwriter.Workbook constructor. """ from xlsxwriter.workbook import Workbook as _Workbook ...
[ "def", "to_xlsx", "(", "self", ",", "*", "*", "kwargs", ")", ":", "from", "xlsxwriter", ".", "workbook", "import", "Workbook", "as", "_Workbook", "self", ".", "workbook_obj", "=", "_Workbook", "(", "*", "*", "kwargs", ")", "self", ".", "workbook_obj", "....
Write workbook to a .xlsx file using xlsxwriter. Return a xlsxwriter.workbook.Workbook. :param kwargs: Extra arguments passed to the xlsxwriter.Workbook constructor.
[ "Write", "workbook", "to", "a", ".", "xlsx", "file", "using", "xlsxwriter", ".", "Return", "a", "xlsxwriter", ".", "workbook", ".", "Workbook", "." ]
python
train
quantmind/dynts
dynts/lib/fallback/maths.py
https://github.com/quantmind/dynts/blob/21ac57c648bfec402fa6b1fe569496cf098fb5e8/dynts/lib/fallback/maths.py#L3-L33
def bindata(data, maxbins = 30, reduction = 0.1): ''' data must be numeric list with a len above 20 This function counts the number of data points in a reduced array ''' tole = 0.01 N = len(data) assert N > 20 vmin = min(data) vmax = max(data) DV = vmax - vmin tol = tole*DV vmax += t...
[ "def", "bindata", "(", "data", ",", "maxbins", "=", "30", ",", "reduction", "=", "0.1", ")", ":", "tole", "=", "0.01", "N", "=", "len", "(", "data", ")", "assert", "N", ">", "20", "vmin", "=", "min", "(", "data", ")", "vmax", "=", "max", "(", ...
data must be numeric list with a len above 20 This function counts the number of data points in a reduced array
[ "data", "must", "be", "numeric", "list", "with", "a", "len", "above", "20", "This", "function", "counts", "the", "number", "of", "data", "points", "in", "a", "reduced", "array" ]
python
train
biocore/burrito-fillings
bfillings/mafft.py
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/mafft.py#L411-L470
def align_two_alignments(aln1, aln2, moltype, params=None): """Returns an Alignment object from two existing Alignments. aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be used to build them. - Mafft profile alignment only works with aligned sequences. Alignment object...
[ "def", "align_two_alignments", "(", "aln1", ",", "aln2", ",", "moltype", ",", "params", "=", "None", ")", ":", "#create SequenceCollection object from seqs", "aln1", "=", "Alignment", "(", "aln1", ",", "MolType", "=", "moltype", ")", "#Create mapping between abbrevi...
Returns an Alignment object from two existing Alignments. aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be used to build them. - Mafft profile alignment only works with aligned sequences. Alignment object used to handle unaligned sequences. params: dict of parameter...
[ "Returns", "an", "Alignment", "object", "from", "two", "existing", "Alignments", "." ]
python
train
plivo/plivohelper-python
plivohelper.py
https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L181-L186
def hangup_all_calls(self): """REST Hangup All Live Calls Helper """ path = '/' + self.api_version + '/HangupAllCalls/' method = 'POST' return self.request(path, method)
[ "def", "hangup_all_calls", "(", "self", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/HangupAllCalls/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ")" ]
REST Hangup All Live Calls Helper
[ "REST", "Hangup", "All", "Live", "Calls", "Helper" ]
python
valid
opencobra/cobrapy
cobra/io/sbml.py
https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/io/sbml.py#L100-L102
def _clip(sid, prefix): """Clips a prefix from the beginning of a string if it exists.""" return sid[len(prefix):] if sid.startswith(prefix) else sid
[ "def", "_clip", "(", "sid", ",", "prefix", ")", ":", "return", "sid", "[", "len", "(", "prefix", ")", ":", "]", "if", "sid", ".", "startswith", "(", "prefix", ")", "else", "sid" ]
Clips a prefix from the beginning of a string if it exists.
[ "Clips", "a", "prefix", "from", "the", "beginning", "of", "a", "string", "if", "it", "exists", "." ]
python
valid
Qiskit/qiskit-terra
qiskit/pulse/samplers/decorators.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/samplers/decorators.py#L184-L227
def sampler(sample_function: Callable) -> Callable: """Sampler decorator base method. Samplers are used for converting an continuous function to a discretized pulse. They operate on a function with the signature: `def f(times: np.ndarray, *args, **kwargs) -> np.ndarray` Where `times` is a nump...
[ "def", "sampler", "(", "sample_function", ":", "Callable", ")", "->", "Callable", ":", "def", "generate_sampler", "(", "continuous_pulse", ":", "Callable", ")", "->", "Callable", ":", "\"\"\"Return a decorated sampler function.\"\"\"", "@", "functools", ".", "wraps", ...
Sampler decorator base method. Samplers are used for converting an continuous function to a discretized pulse. They operate on a function with the signature: `def f(times: np.ndarray, *args, **kwargs) -> np.ndarray` Where `times` is a numpy array of floats with length n_times and the output array ...
[ "Sampler", "decorator", "base", "method", "." ]
python
test
python-xlib/python-xlib
Xlib/display.py
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L637-L643
def list_fonts(self, pattern, max_names): """Return a list of font names matching pattern. No more than max_names will be returned.""" r = request.ListFonts(display = self.display, max_names = max_names, pattern = pattern) retur...
[ "def", "list_fonts", "(", "self", ",", "pattern", ",", "max_names", ")", ":", "r", "=", "request", ".", "ListFonts", "(", "display", "=", "self", ".", "display", ",", "max_names", "=", "max_names", ",", "pattern", "=", "pattern", ")", "return", "r", "....
Return a list of font names matching pattern. No more than max_names will be returned.
[ "Return", "a", "list", "of", "font", "names", "matching", "pattern", ".", "No", "more", "than", "max_names", "will", "be", "returned", "." ]
python
train
phoebe-project/phoebe2
phoebe/utils/__init__.py
https://github.com/phoebe-project/phoebe2/blob/e64b8be683977064e2d55dd1b3ac400f64c3e379/phoebe/utils/__init__.py#L3-L97
def get_basic_logger(clevel='WARNING',flevel='DEBUG', style="default",filename=None,filemode='w'): """ Return a basic logger via a log file and/or terminal. Example 1: log only to the console, accepting levels "INFO" and above >>> logger = utils.get_basic_logger() Example 2: ...
[ "def", "get_basic_logger", "(", "clevel", "=", "'WARNING'", ",", "flevel", "=", "'DEBUG'", ",", "style", "=", "\"default\"", ",", "filename", "=", "None", ",", "filemode", "=", "'w'", ")", ":", "name", "=", "\"\"", "#-- define formats", "if", "style", "=="...
Return a basic logger via a log file and/or terminal. Example 1: log only to the console, accepting levels "INFO" and above >>> logger = utils.get_basic_logger() Example 2: log only to the console, accepting levels "DEBUG" and above >>> logger = utils.get_basic_logger(clevel='DEBUG') Example 3:...
[ "Return", "a", "basic", "logger", "via", "a", "log", "file", "and", "/", "or", "terminal", "." ]
python
train
icgood/pymap
pymap/flags.py
https://github.com/icgood/pymap/blob/e77d9a54d760e3cbe044a548883bb4299ed61dc2/pymap/flags.py#L149-L158
def remove(self, uids: Iterable[int]) -> None: """Remove any session flags for the given message. Args: uids: The message UID values. """ for uid in uids: self._recent.discard(uid) self._flags.pop(uid, None)
[ "def", "remove", "(", "self", ",", "uids", ":", "Iterable", "[", "int", "]", ")", "->", "None", ":", "for", "uid", "in", "uids", ":", "self", ".", "_recent", ".", "discard", "(", "uid", ")", "self", ".", "_flags", ".", "pop", "(", "uid", ",", "...
Remove any session flags for the given message. Args: uids: The message UID values.
[ "Remove", "any", "session", "flags", "for", "the", "given", "message", "." ]
python
train
fitnr/convertdate
convertdate/gregorian.py
https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/gregorian.py#L80-L118
def from_jd(jd): '''Return Gregorian date in a (Y, M, D) tuple''' wjd = floor(jd - 0.5) + 0.5 depoch = wjd - EPOCH quadricent = floor(depoch / INTERCALATION_CYCLE_DAYS) dqc = depoch % INTERCALATION_CYCLE_DAYS cent = floor(dqc / LEAP_SUPPRESSION_DAYS) dcent = dqc % LEAP_SUPPRESSION_DAYS ...
[ "def", "from_jd", "(", "jd", ")", ":", "wjd", "=", "floor", "(", "jd", "-", "0.5", ")", "+", "0.5", "depoch", "=", "wjd", "-", "EPOCH", "quadricent", "=", "floor", "(", "depoch", "/", "INTERCALATION_CYCLE_DAYS", ")", "dqc", "=", "depoch", "%", "INTER...
Return Gregorian date in a (Y, M, D) tuple
[ "Return", "Gregorian", "date", "in", "a", "(", "Y", "M", "D", ")", "tuple" ]
python
train
Chilipp/psy-simple
psy_simple/plotters.py
https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/plotters.py#L3350-L3352
def ycoord(self): """The y coordinate :class:`xarray.Variable`""" return self.decoder.get_y(self.data, coords=self.data.coords)
[ "def", "ycoord", "(", "self", ")", ":", "return", "self", ".", "decoder", ".", "get_y", "(", "self", ".", "data", ",", "coords", "=", "self", ".", "data", ".", "coords", ")" ]
The y coordinate :class:`xarray.Variable`
[ "The", "y", "coordinate", ":", "class", ":", "xarray", ".", "Variable" ]
python
train
pgmpy/pgmpy
pgmpy/factors/discrete/DiscreteFactor.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/factors/discrete/DiscreteFactor.py#L682-L711
def copy(self): """ Returns a copy of the factor. Returns ------- DiscreteFactor: copy of the factor Examples -------- >>> import numpy as np >>> from pgmpy.factors.discrete import DiscreteFactor >>> phi = DiscreteFactor(['x1', 'x2', 'x3'...
[ "def", "copy", "(", "self", ")", ":", "# not creating a new copy of self.values and self.cardinality", "# because __init__ methods does that.", "return", "DiscreteFactor", "(", "self", ".", "scope", "(", ")", ",", "self", ".", "cardinality", ",", "self", ".", "values", ...
Returns a copy of the factor. Returns ------- DiscreteFactor: copy of the factor Examples -------- >>> import numpy as np >>> from pgmpy.factors.discrete import DiscreteFactor >>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 3], np.arange(18)) ...
[ "Returns", "a", "copy", "of", "the", "factor", "." ]
python
train
nccgroup/Scout2
AWSScout2/services/emr.py
https://github.com/nccgroup/Scout2/blob/5d86d46d7ed91a92000496189e9cfa6b98243937/AWSScout2/services/emr.py#L19-L33
def parse_cluster(self, global_params, region, cluster): """ Parse a single EMR cluster :param global_params: Parameters shared for all regions :param region: Name of the AWS region :param cluster: EMR cluster """ cluste...
[ "def", "parse_cluster", "(", "self", ",", "global_params", ",", "region", ",", "cluster", ")", ":", "cluster_id", "=", "cluster", "[", "'Id'", "]", "cluster", "=", "api_clients", "[", "region", "]", ".", "describe_cluster", "(", "ClusterId", "=", "cluster_id...
Parse a single EMR cluster :param global_params: Parameters shared for all regions :param region: Name of the AWS region :param cluster: EMR cluster
[ "Parse", "a", "single", "EMR", "cluster" ]
python
train
tornadoweb/tornado
tornado/http1connection.py
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/http1connection.py#L376-L465
def write_headers( self, start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine], headers: httputil.HTTPHeaders, chunk: bytes = None, ) -> "Future[None]": """Implements `.HTTPConnection.write_headers`.""" lines = [] if self.is_client: ...
[ "def", "write_headers", "(", "self", ",", "start_line", ":", "Union", "[", "httputil", ".", "RequestStartLine", ",", "httputil", ".", "ResponseStartLine", "]", ",", "headers", ":", "httputil", ".", "HTTPHeaders", ",", "chunk", ":", "bytes", "=", "None", ",",...
Implements `.HTTPConnection.write_headers`.
[ "Implements", ".", "HTTPConnection", ".", "write_headers", "." ]
python
train
tcalmant/ipopo
pelix/ipopo/decorators.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/decorators.py#L260-L317
def _ipopo_setup_field_callback(cls, context): # type: (type, FactoryContext) -> None """ Sets up the class _field_callback dictionary :param cls: The class to handle :param context: The factory class context """ assert inspect.isclass(cls) assert isinstance(context, FactoryContext) ...
[ "def", "_ipopo_setup_field_callback", "(", "cls", ",", "context", ")", ":", "# type: (type, FactoryContext) -> None", "assert", "inspect", ".", "isclass", "(", "cls", ")", "assert", "isinstance", "(", "context", ",", "FactoryContext", ")", "if", "context", ".", "f...
Sets up the class _field_callback dictionary :param cls: The class to handle :param context: The factory class context
[ "Sets", "up", "the", "class", "_field_callback", "dictionary" ]
python
train
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/_backends/device_directory/apis/default_api.py
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/_backends/device_directory/apis/default_api.py#L36-L56
def device_create(self, device, **kwargs): # noqa: E501 """Create a device # noqa: E501 Create a new device. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.device_creat...
[ "def", "device_create", "(", "self", ",", "device", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ".", "device_...
Create a device # noqa: E501 Create a new device. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.device_create(device, asynchronous=True) >>> result = thread.get() ...
[ "Create", "a", "device", "#", "noqa", ":", "E501" ]
python
train
cloudbase/python-hnvclient
hnv/client.py
https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/client.py#L2023-L2045
def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data.get("properties", {}) backend_ip_configurations = [] for raw_content in properties.get("backendIPConfigurations", []): resource = Resource.from_raw_data(raw_content) ...
[ "def", "process_raw_data", "(", "cls", ",", "raw_data", ")", ":", "properties", "=", "raw_data", ".", "get", "(", "\"properties\"", ",", "{", "}", ")", "backend_ip_configurations", "=", "[", "]", "for", "raw_content", "in", "properties", ".", "get", "(", "...
Create a new model using raw API response.
[ "Create", "a", "new", "model", "using", "raw", "API", "response", "." ]
python
train
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sgilink.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/sgilink.py#L42-L53
def generate(env): """Add Builders and construction variables for MIPSPro to an Environment.""" link.generate(env) env['LINK'] = env.Detect(linkers) or 'cc' env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared') # __RPATH is set to $_RPATH in the platform specification if that # platf...
[ "def", "generate", "(", "env", ")", ":", "link", ".", "generate", "(", "env", ")", "env", "[", "'LINK'", "]", "=", "env", ".", "Detect", "(", "linkers", ")", "or", "'cc'", "env", "[", "'SHLINKFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", ...
Add Builders and construction variables for MIPSPro to an Environment.
[ "Add", "Builders", "and", "construction", "variables", "for", "MIPSPro", "to", "an", "Environment", "." ]
python
train
tango-controls/pytango
tango/utils.py
https://github.com/tango-controls/pytango/blob/9cf78c517c9cdc1081ff6d080a9646a740cc1d36/tango/utils.py#L1578-L1596
def _get_value(self, evt): """Internal usage only""" if evt.err: e = evt.errors[0] return "[%s] %s" % (e.reason, e.desc) if isinstance(evt, EventData): return "[%s] %s" % ( evt.attr_value.quality, str(evt.attr_value.value)) elif isinst...
[ "def", "_get_value", "(", "self", ",", "evt", ")", ":", "if", "evt", ".", "err", ":", "e", "=", "evt", ".", "errors", "[", "0", "]", "return", "\"[%s] %s\"", "%", "(", "e", ".", "reason", ",", "e", ".", "desc", ")", "if", "isinstance", "(", "ev...
Internal usage only
[ "Internal", "usage", "only" ]
python
train
horazont/aioxmpp
aioxmpp/service.py
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1073-L1080
def presence_handler(type_, from_): """ Deprecated alias of :func:`.dispatcher.presence_handler`. .. deprecated:: 0.9 """ import aioxmpp.dispatcher return aioxmpp.dispatcher.presence_handler(type_, from_)
[ "def", "presence_handler", "(", "type_", ",", "from_", ")", ":", "import", "aioxmpp", ".", "dispatcher", "return", "aioxmpp", ".", "dispatcher", ".", "presence_handler", "(", "type_", ",", "from_", ")" ]
Deprecated alias of :func:`.dispatcher.presence_handler`. .. deprecated:: 0.9
[ "Deprecated", "alias", "of", ":", "func", ":", ".", "dispatcher", ".", "presence_handler", "." ]
python
train
GPflow/GPflow
gpflow/expectations.py
https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/expectations.py#L237-L245
def _expectation(p, kern, none1, none2, none3, nghp=None): """ Compute the expectation: <diag(K_{X, X})>_p(X) - K_{.,.} :: RBF kernel :return: N """ return kern.Kdiag(p.mu)
[ "def", "_expectation", "(", "p", ",", "kern", ",", "none1", ",", "none2", ",", "none3", ",", "nghp", "=", "None", ")", ":", "return", "kern", ".", "Kdiag", "(", "p", ".", "mu", ")" ]
Compute the expectation: <diag(K_{X, X})>_p(X) - K_{.,.} :: RBF kernel :return: N
[ "Compute", "the", "expectation", ":", "<diag", "(", "K_", "{", "X", "X", "}", ")", ">", "_p", "(", "X", ")", "-", "K_", "{", ".", ".", "}", "::", "RBF", "kernel" ]
python
train
mieubrisse/wunderpy2
wunderpy2/wunderclient.py
https://github.com/mieubrisse/wunderpy2/blob/7106b6c13ca45ef4d56f805753c93258d5b822c2/wunderpy2/wunderclient.py#L79-L85
def update_task(self, task_id, revision, title=None, assignee_id=None, completed=None, recurrence_type=None, recurrence_count=None, due_date=None, starred=None, remove=None): ''' Updates the task with the given ID to have the given information NOTE: The 'remove' parameter is an option...
[ "def", "update_task", "(", "self", ",", "task_id", ",", "revision", ",", "title", "=", "None", ",", "assignee_id", "=", "None", ",", "completed", "=", "None", ",", "recurrence_type", "=", "None", ",", "recurrence_count", "=", "None", ",", "due_date", "=", ...
Updates the task with the given ID to have the given information NOTE: The 'remove' parameter is an optional list of parameters to remove from the given task, e.g. ['due_date']
[ "Updates", "the", "task", "with", "the", "given", "ID", "to", "have", "the", "given", "information", "NOTE", ":", "The", "remove", "parameter", "is", "an", "optional", "list", "of", "parameters", "to", "remove", "from", "the", "given", "task", "e", ".", ...
python
train
CloudGenix/sdk-python
cloudgenix/interactive.py
https://github.com/CloudGenix/sdk-python/blob/1b2f92582b6a19769134914793bfd00e4caa074b/cloudgenix/interactive.py#L634-L666
def quick_confirm(prompt, default_value): """ Function to display a quick confirmation for user input **Parameters:** - **prompt:** Text to display before confirm - **default_value:** Default value for no entry **Returns:** 'y', 'n', or Default value. """ ...
[ "def", "quick_confirm", "(", "prompt", ",", "default_value", ")", ":", "valid", "=", "False", "value", "=", "default_value", ".", "lower", "(", ")", "while", "not", "valid", ":", "input_val", "=", "compat_input", "(", "prompt", "+", "\"[{0}]: \"", ".", "fo...
Function to display a quick confirmation for user input **Parameters:** - **prompt:** Text to display before confirm - **default_value:** Default value for no entry **Returns:** 'y', 'n', or Default value.
[ "Function", "to", "display", "a", "quick", "confirmation", "for", "user", "input" ]
python
train
eng-tools/sfsimodels
sfsimodels/loader.py
https://github.com/eng-tools/sfsimodels/blob/65a690ca440d61307f5a9b8478e4704f203a5925/sfsimodels/loader.py#L114-L138
def load_frame_building_sample_data(): """ Sample data for the BuildingFrame object :return: """ number_of_storeys = 6 interstorey_height = 3.4 # m masses = 40.0e3 # kg n_bays = 3 fb = models.BuildingFrame(number_of_storeys, n_bays) fb.interstorey_heights = interstorey_height...
[ "def", "load_frame_building_sample_data", "(", ")", ":", "number_of_storeys", "=", "6", "interstorey_height", "=", "3.4", "# m", "masses", "=", "40.0e3", "# kg", "n_bays", "=", "3", "fb", "=", "models", ".", "BuildingFrame", "(", "number_of_storeys", ",", "n_bay...
Sample data for the BuildingFrame object :return:
[ "Sample", "data", "for", "the", "BuildingFrame", "object" ]
python
train
quantumlib/Cirq
cirq/_compat.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/_compat.py#L22-L40
def proper_repr(value: Any) -> str: """Overrides sympy and numpy returning repr strings that don't parse.""" if isinstance(value, sympy.Basic): result = sympy.srepr(value) # HACK: work around https://github.com/sympy/sympy/issues/16074 # (only handles a few cases) fixed_tokens ...
[ "def", "proper_repr", "(", "value", ":", "Any", ")", "->", "str", ":", "if", "isinstance", "(", "value", ",", "sympy", ".", "Basic", ")", ":", "result", "=", "sympy", ".", "srepr", "(", "value", ")", "# HACK: work around https://github.com/sympy/sympy/issues/1...
Overrides sympy and numpy returning repr strings that don't parse.
[ "Overrides", "sympy", "and", "numpy", "returning", "repr", "strings", "that", "don", "t", "parse", "." ]
python
train
Midnighter/dependency-info
src/depinfo/info.py
https://github.com/Midnighter/dependency-info/blob/15bcada0a1d6c047cbe10b844d5bd909ea8cc752/src/depinfo/info.py#L47-L65
def get_pkg_info( package_name, additional=("pip", "flit", "pbr", "setuptools", "wheel") ): """Return build and package dependencies as a dict.""" dist_index = build_dist_index(pkg_resources.working_set) root = dist_index[package_name] tree = construct_tree(dist_index) dependencies = {pkg.name: ...
[ "def", "get_pkg_info", "(", "package_name", ",", "additional", "=", "(", "\"pip\"", ",", "\"flit\"", ",", "\"pbr\"", ",", "\"setuptools\"", ",", "\"wheel\"", ")", ")", ":", "dist_index", "=", "build_dist_index", "(", "pkg_resources", ".", "working_set", ")", "...
Return build and package dependencies as a dict.
[ "Return", "build", "and", "package", "dependencies", "as", "a", "dict", "." ]
python
train
dcramer/mock-django
mock_django/query.py
https://github.com/dcramer/mock-django/blob/1168d3255e0d67fbf74a9c71feaccbdafef59d21/mock_django/query.py#L21-L109
def QuerySetMock(model, *return_value): """ Get a SharedMock that returns self for most attributes and a new copy of itself for any method that ordinarily generates QuerySets. Set the results to two items: >>> class Post(object): pass >>> objects = QuerySetMock(Post, 'return', 'values') >>...
[ "def", "QuerySetMock", "(", "model", ",", "*", "return_value", ")", ":", "def", "make_get", "(", "self", ",", "model", ")", ":", "def", "_get", "(", "*", "a", ",", "*", "*", "k", ")", ":", "results", "=", "list", "(", "self", ")", "if", "len", ...
Get a SharedMock that returns self for most attributes and a new copy of itself for any method that ordinarily generates QuerySets. Set the results to two items: >>> class Post(object): pass >>> objects = QuerySetMock(Post, 'return', 'values') >>> assert list(objects.filter()) == list(objects.all(...
[ "Get", "a", "SharedMock", "that", "returns", "self", "for", "most", "attributes", "and", "a", "new", "copy", "of", "itself", "for", "any", "method", "that", "ordinarily", "generates", "QuerySets", "." ]
python
train
miyakogi/wdom
wdom/element.py
https://github.com/miyakogi/wdom/blob/a21bcd23e94baceee71161829f6897bee3fd39c1/wdom/element.py#L212-L218
def html(self) -> str: """Return html representation.""" if isinstance(self.value, bool): val = 'true' if self.value else 'false' else: val = str(self.value) return 'draggable="{}"'.format(val)
[ "def", "html", "(", "self", ")", "->", "str", ":", "if", "isinstance", "(", "self", ".", "value", ",", "bool", ")", ":", "val", "=", "'true'", "if", "self", ".", "value", "else", "'false'", "else", ":", "val", "=", "str", "(", "self", ".", "value...
Return html representation.
[ "Return", "html", "representation", "." ]
python
train
edelbluth/blackred
src/blackred/blackred.py
https://github.com/edelbluth/blackred/blob/57a655e4d4eca60ce16e7b338079355049a87b49/src/blackred/blackred.py#L289-L299
def get_watchlist_ttl(self, item: str) -> int: """ Get the amount of time a specific item will remain on the watchlist. :param str item: The item to get the TTL for on the watchlist :return: Time in seconds. Returns None for a non-existing element :rtype: int """ ...
[ "def", "get_watchlist_ttl", "(", "self", ",", "item", ":", "str", ")", "->", "int", ":", "assert", "item", "is", "not", "None", "item", "=", "self", ".", "_encode_item", "(", "item", ")", "return", "self", ".", "__get_ttl", "(", "self", ".", "__redis_c...
Get the amount of time a specific item will remain on the watchlist. :param str item: The item to get the TTL for on the watchlist :return: Time in seconds. Returns None for a non-existing element :rtype: int
[ "Get", "the", "amount", "of", "time", "a", "specific", "item", "will", "remain", "on", "the", "watchlist", "." ]
python
train
atztogo/phonopy
phonopy/harmonic/dynmat_to_fc.py
https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/harmonic/dynmat_to_fc.py#L42-L62
def get_commensurate_points(supercell_matrix): # wrt primitive cell """Commensurate q-points are returned. Parameters ---------- supercell_matrix : array_like Supercell matrix with respect to primitive cell basis vectors. shape=(3, 3) dtype=intc """ smat = np.array(su...
[ "def", "get_commensurate_points", "(", "supercell_matrix", ")", ":", "# wrt primitive cell", "smat", "=", "np", ".", "array", "(", "supercell_matrix", ",", "dtype", "=", "int", ")", "rec_primitive", "=", "PhonopyAtoms", "(", "numbers", "=", "[", "1", "]", ",",...
Commensurate q-points are returned. Parameters ---------- supercell_matrix : array_like Supercell matrix with respect to primitive cell basis vectors. shape=(3, 3) dtype=intc
[ "Commensurate", "q", "-", "points", "are", "returned", "." ]
python
train
spyder-ide/spyder
spyder/plugins/variableexplorer/widgets/dataframeeditor.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/variableexplorer/widgets/dataframeeditor.py#L655-L663
def columnCount(self, index=QModelIndex()): """DataFrame column number""" if self.axis == 0: if self.total_cols <= self.cols_loaded: return self.total_cols else: return self.cols_loaded else: return max(1, self._shape[1]...
[ "def", "columnCount", "(", "self", ",", "index", "=", "QModelIndex", "(", ")", ")", ":", "if", "self", ".", "axis", "==", "0", ":", "if", "self", ".", "total_cols", "<=", "self", ".", "cols_loaded", ":", "return", "self", ".", "total_cols", "else", "...
DataFrame column number
[ "DataFrame", "column", "number" ]
python
train
OpenGov/python_data_wrap
datawrap/tableloader.py
https://github.com/OpenGov/python_data_wrap/blob/7de38bb30d7a500adc336a4a7999528d753e5600/datawrap/tableloader.py#L16-L51
def read(file_name, file_contents=None, on_demand=False): ''' Loads an arbitrary file type (xlsx, xls, or csv like) and returns a list of 2D tables. For csv files this will be a list of one table, but excel formats can have many tables/worksheets. TODO: Add wrapper which can be closed/exite...
[ "def", "read", "(", "file_name", ",", "file_contents", "=", "None", ",", "on_demand", "=", "False", ")", ":", "try", ":", "if", "re", ".", "search", "(", "XML_EXT_REGEX", ",", "file_name", ")", ":", "return", "get_data_excel_xml", "(", "file_name", ",", ...
Loads an arbitrary file type (xlsx, xls, or csv like) and returns a list of 2D tables. For csv files this will be a list of one table, but excel formats can have many tables/worksheets. TODO: Add wrapper which can be closed/exited on each file type which cleans up the file handler. Arg...
[ "Loads", "an", "arbitrary", "file", "type", "(", "xlsx", "xls", "or", "csv", "like", ")", "and", "returns", "a", "list", "of", "2D", "tables", ".", "For", "csv", "files", "this", "will", "be", "a", "list", "of", "one", "table", "but", "excel", "forma...
python
train
fastai/fastai
fastai/callbacks/tensorboard.py
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/callbacks/tensorboard.py#L120-L124
def _write_gen_model_stats(self, iteration:int)->None: "Writes gradient statistics for generator to Tensorboard." generator = self.learn.gan_trainer.generator self.stats_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='gen_model_stats') self.gen_stats_upda...
[ "def", "_write_gen_model_stats", "(", "self", ",", "iteration", ":", "int", ")", "->", "None", ":", "generator", "=", "self", ".", "learn", ".", "gan_trainer", ".", "generator", "self", ".", "stats_writer", ".", "write", "(", "model", "=", "generator", ","...
Writes gradient statistics for generator to Tensorboard.
[ "Writes", "gradient", "statistics", "for", "generator", "to", "Tensorboard", "." ]
python
train
UDST/orca
orca/orca.py
https://github.com/UDST/orca/blob/07b34aeef13cc87c966b2e30cbe7e76cc9d3622c/orca/orca.py#L1908-L2007
def run(steps, iter_vars=None, data_out=None, out_interval=1, out_base_tables=None, out_run_tables=None, compress=False, out_base_local=True, out_run_local=True): """ Run steps in series, optionally repeatedly over some sequence. The current iteration variable is set as a global injectable ...
[ "def", "run", "(", "steps", ",", "iter_vars", "=", "None", ",", "data_out", "=", "None", ",", "out_interval", "=", "1", ",", "out_base_tables", "=", "None", ",", "out_run_tables", "=", "None", ",", "compress", "=", "False", ",", "out_base_local", "=", "T...
Run steps in series, optionally repeatedly over some sequence. The current iteration variable is set as a global injectable called ``iter_var``. Parameters ---------- steps : list of str List of steps to run identified by their name. iter_vars : iterable, optional The values of ...
[ "Run", "steps", "in", "series", "optionally", "repeatedly", "over", "some", "sequence", ".", "The", "current", "iteration", "variable", "is", "set", "as", "a", "global", "injectable", "called", "iter_var", "." ]
python
train
quantmind/pulsar
pulsar/apps/data/channels.py
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/channels.py#L329-L341
def register(self, event, callback): """Register a ``callback`` for ``event`` """ pattern = self.channels.event_pattern(event) entry = self.callbacks.get(pattern) if not entry: entry = event_callbacks(event, pattern, re.compile(pattern), []) self.callbacks...
[ "def", "register", "(", "self", ",", "event", ",", "callback", ")", ":", "pattern", "=", "self", ".", "channels", ".", "event_pattern", "(", "event", ")", "entry", "=", "self", ".", "callbacks", ".", "get", "(", "pattern", ")", "if", "not", "entry", ...
Register a ``callback`` for ``event``
[ "Register", "a", "callback", "for", "event" ]
python
train
librosa/librosa
librosa/effects.py
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/effects.py#L310-L387
def remix(y, intervals, align_zeros=True): '''Remix an audio signal by re-ordering time intervals. Parameters ---------- y : np.ndarray [shape=(t,) or (2, t)] Audio time series intervals : iterable of tuples (start, end) An iterable (list-like or generator) where the `i`th item ...
[ "def", "remix", "(", "y", ",", "intervals", ",", "align_zeros", "=", "True", ")", ":", "# Validate the audio buffer", "util", ".", "valid_audio", "(", "y", ",", "mono", "=", "False", ")", "y_out", "=", "[", "]", "if", "align_zeros", ":", "y_mono", "=", ...
Remix an audio signal by re-ordering time intervals. Parameters ---------- y : np.ndarray [shape=(t,) or (2, t)] Audio time series intervals : iterable of tuples (start, end) An iterable (list-like or generator) where the `i`th item `intervals[i]` indicates the start and end (...
[ "Remix", "an", "audio", "signal", "by", "re", "-", "ordering", "time", "intervals", "." ]
python
test
Nike-Inc/cerberus-python-client
cerberus/client.py
https://github.com/Nike-Inc/cerberus-python-client/blob/ef38356822e722fcb6a6ed4a1b38a5b493e753ae/cerberus/client.py#L95-L104
def get_roles(self): """Return all the roles (IAM or User Groups) that can be granted to a safe deposit box. Roles are permission levels that are granted to IAM or User Groups. Associating the id for the write role would allow that IAM or User Group to write in the safe deposit box.""" ...
[ "def", "get_roles", "(", "self", ")", ":", "roles_resp", "=", "get_with_retry", "(", "self", ".", "cerberus_url", "+", "'/v1/role'", ",", "headers", "=", "self", ".", "HEADERS", ")", "throw_if_bad_response", "(", "roles_resp", ")", "return", "roles_resp", ".",...
Return all the roles (IAM or User Groups) that can be granted to a safe deposit box. Roles are permission levels that are granted to IAM or User Groups. Associating the id for the write role would allow that IAM or User Group to write in the safe deposit box.
[ "Return", "all", "the", "roles", "(", "IAM", "or", "User", "Groups", ")", "that", "can", "be", "granted", "to", "a", "safe", "deposit", "box", "." ]
python
train
linkhub-sdk/popbill.py
popbill/statementService.py
https://github.com/linkhub-sdk/popbill.py/blob/68a0dd7f7a937603318e93be321fde73c50b96cc/popbill/statementService.py#L237-L263
def cancel(self, CorpNum, ItemCode, MgtKey, Memo=None, UserID=None): """ 발행취소 args CorpNum : 팝빌회원 사업자번호 ItemCode : 명세서 종류 코드 [121 - 거래명세서], [122 - 청구서], [123 - 견적서], [124 - 발주서], [125 - 입금표], [126 - 영수증] M...
[ "def", "cancel", "(", "self", ",", "CorpNum", ",", "ItemCode", ",", "MgtKey", ",", "Memo", "=", "None", ",", "UserID", "=", "None", ")", ":", "if", "MgtKey", "==", "None", "or", "MgtKey", "==", "\"\"", ":", "raise", "PopbillException", "(", "-", "999...
발행취소 args CorpNum : 팝빌회원 사업자번호 ItemCode : 명세서 종류 코드 [121 - 거래명세서], [122 - 청구서], [123 - 견적서], [124 - 발주서], [125 - 입금표], [126 - 영수증] MgtKey : 파트너 문서관리번호 Memo : 처리메모 UserID : 팝빌회원 아이디...
[ "발행취소", "args", "CorpNum", ":", "팝빌회원", "사업자번호", "ItemCode", ":", "명세서", "종류", "코드", "[", "121", "-", "거래명세서", "]", "[", "122", "-", "청구서", "]", "[", "123", "-", "견적서", "]", "[", "124", "-", "발주서", "]", "[", "125", "-", "입금표", "]", "[", "126"...
python
train
chaoss/grimoirelab-perceval
perceval/backends/core/github.py
https://github.com/chaoss/grimoirelab-perceval/blob/41c908605e88b7ebc3a536c643fa0f212eaf9e0e/perceval/backends/core/github.py#L367-L374
def __get_issue_assignees(self, raw_assignees): """Get issue assignees""" assignees = [] for ra in raw_assignees: assignees.append(self.__get_user(ra['login'])) return assignees
[ "def", "__get_issue_assignees", "(", "self", ",", "raw_assignees", ")", ":", "assignees", "=", "[", "]", "for", "ra", "in", "raw_assignees", ":", "assignees", ".", "append", "(", "self", ".", "__get_user", "(", "ra", "[", "'login'", "]", ")", ")", "retur...
Get issue assignees
[ "Get", "issue", "assignees" ]
python
test
MacHu-GWU/angora-project
angora/filesystem/filesystem.py
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/filesystem/filesystem.py#L852-L878
def from_path_by_size(dir_path, min_size=0, max_size=1 << 40): """Create a new FileCollection, and select all files that size in a range:: dir_path = "your/path" # select by file size larger than 100MB fc = FileCollection.from_path_by_size( ...
[ "def", "from_path_by_size", "(", "dir_path", ",", "min_size", "=", "0", ",", "max_size", "=", "1", "<<", "40", ")", ":", "def", "filter", "(", "winfile", ")", ":", "if", "(", "winfile", ".", "size_on_disk", ">=", "min_size", ")", "and", "(", "winfile",...
Create a new FileCollection, and select all files that size in a range:: dir_path = "your/path" # select by file size larger than 100MB fc = FileCollection.from_path_by_size( dir_path, min_size=100*1024*1024) ...
[ "Create", "a", "new", "FileCollection", "and", "select", "all", "files", "that", "size", "in", "a", "range", "::", "dir_path", "=", "your", "/", "path", "#", "select", "by", "file", "size", "larger", "than", "100MB", "fc", "=", "FileCollection", ".", "fr...
python
train
rollbar/pyrollbar
rollbar/__init__.py
https://github.com/rollbar/pyrollbar/blob/33ef2e723a33d09dd6302f978f4a3908be95b9d2/rollbar/__init__.py#L140-L161
def get_request(): """ Get the current request object. Implementation varies on library support. Modified below when we know which framework is being used. """ # TODO(cory): add in a generic _get_locals_request() which # will iterate up through the call stack and look for a variable # t...
[ "def", "get_request", "(", ")", ":", "# TODO(cory): add in a generic _get_locals_request() which", "# will iterate up through the call stack and look for a variable", "# that appears to be valid request object.", "for", "fn", "in", "(", "_get_bottle_request", ",", "_get_flask_request", ...
Get the current request object. Implementation varies on library support. Modified below when we know which framework is being used.
[ "Get", "the", "current", "request", "object", ".", "Implementation", "varies", "on", "library", "support", ".", "Modified", "below", "when", "we", "know", "which", "framework", "is", "being", "used", "." ]
python
test
cisco-sas/kitty
kitty/model/low_level/aliases.py
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/model/low_level/aliases.py#L144-L146
def BE8(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False): '''8-bit field, Big endian encoded''' return UInt8(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range)
[ "def", "BE8", "(", "value", ",", "min_value", "=", "None", ",", "max_value", "=", "None", ",", "fuzzable", "=", "True", ",", "name", "=", "None", ",", "full_range", "=", "False", ")", ":", "return", "UInt8", "(", "value", ",", "min_value", "=", "min_...
8-bit field, Big endian encoded
[ "8", "-", "bit", "field", "Big", "endian", "encoded" ]
python
train
rndusr/torf
torf/_torrent.py
https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L593-L641
def generate(self, callback=None, interval=0): """ Hash pieces and report progress to `callback` This method sets ``pieces`` in :attr:`metainfo`\ ``['info']`` when all pieces are hashed successfully. :param callable callback: Callable with signature ``(torrent, filepath, ...
[ "def", "generate", "(", "self", ",", "callback", "=", "None", ",", "interval", "=", "0", ")", ":", "if", "self", ".", "path", "is", "None", ":", "raise", "RuntimeError", "(", "'generate() called with no path specified'", ")", "elif", "self", ".", "size", "...
Hash pieces and report progress to `callback` This method sets ``pieces`` in :attr:`metainfo`\ ``['info']`` when all pieces are hashed successfully. :param callable callback: Callable with signature ``(torrent, filepath, pieces_done, pieces_total)``; if `callback` returns anything ...
[ "Hash", "pieces", "and", "report", "progress", "to", "callback" ]
python
train
tk0miya/tk.phpautodoc
src/phply/phpparse.py
https://github.com/tk0miya/tk.phpautodoc/blob/cf789f64abaf76351485cee231a075227e665fb6/src/phply/phpparse.py#L378-L384
def p_foreach_statement(p): '''foreach_statement : statement | COLON inner_statement_list ENDFOREACH SEMI''' if len(p) == 2: p[0] = p[1] else: p[0] = ast.Block(p[2], lineno=p.lineno(1))
[ "def", "p_foreach_statement", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "else", ":", "p", "[", "0", "]", "=", "ast", ".", "Block", "(", "p", "[", "2", "]", ",", "lineno", ...
foreach_statement : statement | COLON inner_statement_list ENDFOREACH SEMI
[ "foreach_statement", ":", "statement", "|", "COLON", "inner_statement_list", "ENDFOREACH", "SEMI" ]
python
train
mitsei/dlkit
dlkit/services/relationship.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/relationship.py#L1129-L1136
def save_relationship(self, relationship_form, *args, **kwargs): """Pass through to provider RelationshipAdminSession.update_relationship""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if relationship_form.is_for_update(): re...
[ "def", "save_relationship", "(", "self", ",", "relationship_form", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.ResourceAdminSession.update_resource", "if", "relationship_form", ".", "is_for_update", "(",...
Pass through to provider RelationshipAdminSession.update_relationship
[ "Pass", "through", "to", "provider", "RelationshipAdminSession", ".", "update_relationship" ]
python
train
biolink/biolink-model
metamodel/utils/generator.py
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/generator.py#L230-L238
def aliased_slot_name(self, slot: SLOT_OR_SLOTNAME) -> str: """ Return the overloaded slot name -- the alias if one exists otherwise the actual name @param slot: either a slot name or a definition @return: overloaded name """ if isinstance(slot, str): slot = self.sch...
[ "def", "aliased_slot_name", "(", "self", ",", "slot", ":", "SLOT_OR_SLOTNAME", ")", "->", "str", ":", "if", "isinstance", "(", "slot", ",", "str", ")", ":", "slot", "=", "self", ".", "schema", ".", "slots", "[", "slot", "]", "return", "slot", ".", "a...
Return the overloaded slot name -- the alias if one exists otherwise the actual name @param slot: either a slot name or a definition @return: overloaded name
[ "Return", "the", "overloaded", "slot", "name", "--", "the", "alias", "if", "one", "exists", "otherwise", "the", "actual", "name" ]
python
train
googleapis/gax-python
google/gax/utils/protobuf.py
https://github.com/googleapis/gax-python/blob/309aedfcfd48e4c8fa22dd60e9c84c3cc71bb20e/google/gax/utils/protobuf.py#L42-L91
def get(pb_or_dict, key, default=_SENTINEL): """Retrieve the given key off of the object. If a default is specified, return it if the key is not found, otherwise raise KeyError. Args: pb_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The ...
[ "def", "get", "(", "pb_or_dict", ",", "key", ",", "default", "=", "_SENTINEL", ")", ":", "# We may need to get a nested key. Resolve this.", "key", ",", "subkey", "=", "_resolve_subkeys", "(", "key", ")", "# Attempt to get the value from the two types of objects we know bao...
Retrieve the given key off of the object. If a default is specified, return it if the key is not found, otherwise raise KeyError. Args: pb_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str): The key to retrieve from the object in question. ...
[ "Retrieve", "the", "given", "key", "off", "of", "the", "object", "." ]
python
train
msikma/kanaconv
kanaconv/converter.py
https://github.com/msikma/kanaconv/blob/194f142e616ab5dd6d13a687b96b9f8abd1b4ea8/kanaconv/converter.py#L435-L445
def _add_unknown_char(self, string): ''' Adds an unknown character to the stack. ''' if self.has_xvowel: # Ensure an xvowel gets printed if we've got an active # one right now. self._promote_solitary_xvowel() self.unknown_char = string ...
[ "def", "_add_unknown_char", "(", "self", ",", "string", ")", ":", "if", "self", ".", "has_xvowel", ":", "# Ensure an xvowel gets printed if we've got an active", "# one right now.", "self", ".", "_promote_solitary_xvowel", "(", ")", "self", ".", "unknown_char", "=", "...
Adds an unknown character to the stack.
[ "Adds", "an", "unknown", "character", "to", "the", "stack", "." ]
python
train
pydata/xarray
xarray/core/rolling.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/rolling.py#L249-L301
def _bottleneck_reduce(cls, func): """ Methods to return a wrapped function for any function `func` for bottoleneck method, except for `median`. """ def wrapped_func(self, **kwargs): from .dataarray import DataArray # bottleneck doesn't allow min_count t...
[ "def", "_bottleneck_reduce", "(", "cls", ",", "func", ")", ":", "def", "wrapped_func", "(", "self", ",", "*", "*", "kwargs", ")", ":", "from", ".", "dataarray", "import", "DataArray", "# bottleneck doesn't allow min_count to be 0, although it should", "# work the same...
Methods to return a wrapped function for any function `func` for bottoleneck method, except for `median`.
[ "Methods", "to", "return", "a", "wrapped", "function", "for", "any", "function", "func", "for", "bottoleneck", "method", "except", "for", "median", "." ]
python
train
RPi-Distro/python-gpiozero
gpiozero/boards.py
https://github.com/RPi-Distro/python-gpiozero/blob/7b67374fd0c8c4fde5586d9bad9531f076db9c0c/gpiozero/boards.py#L110-L116
def on(self): """ Turn all the output devices on. """ for device in self: if isinstance(device, (OutputDevice, CompositeOutputDevice)): device.on()
[ "def", "on", "(", "self", ")", ":", "for", "device", "in", "self", ":", "if", "isinstance", "(", "device", ",", "(", "OutputDevice", ",", "CompositeOutputDevice", ")", ")", ":", "device", ".", "on", "(", ")" ]
Turn all the output devices on.
[ "Turn", "all", "the", "output", "devices", "on", "." ]
python
train
radjkarl/imgProcessor
imgProcessor/measure/linePlot.py
https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/measure/linePlot.py#L10-L28
def linePlot(img, x0, y0, x1, y1, resolution=None, order=3): ''' returns [img] intensity values along line defined by [x0, y0, x1, y1] resolution ... number or data points to evaluate order ... interpolation precision ''' if resolution is None: resolution = int( ((x1-x0...
[ "def", "linePlot", "(", "img", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ",", "resolution", "=", "None", ",", "order", "=", "3", ")", ":", "if", "resolution", "is", "None", ":", "resolution", "=", "int", "(", "(", "(", "x1", "-", "x0", ")", ...
returns [img] intensity values along line defined by [x0, y0, x1, y1] resolution ... number or data points to evaluate order ... interpolation precision
[ "returns", "[", "img", "]", "intensity", "values", "along", "line", "defined", "by", "[", "x0", "y0", "x1", "y1", "]", "resolution", "...", "number", "or", "data", "points", "to", "evaluate", "order", "...", "interpolation", "precision" ]
python
train
hollenstein/maspy
maspy/sil.py
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/sil.py#L235-L250
def modSymbolsFromLabelInfo(labelDescriptor): """Returns a set of all modiciation symbols which were used in the labelDescriptor :param labelDescriptor: :class:`LabelDescriptor` describes the label setup of an experiment :returns: #TODO: docstring """ modSymbols = set() for labelSt...
[ "def", "modSymbolsFromLabelInfo", "(", "labelDescriptor", ")", ":", "modSymbols", "=", "set", "(", ")", "for", "labelStateEntry", "in", "viewvalues", "(", "labelDescriptor", ".", "labels", ")", ":", "for", "labelPositionEntry", "in", "viewvalues", "(", "labelState...
Returns a set of all modiciation symbols which were used in the labelDescriptor :param labelDescriptor: :class:`LabelDescriptor` describes the label setup of an experiment :returns: #TODO: docstring
[ "Returns", "a", "set", "of", "all", "modiciation", "symbols", "which", "were", "used", "in", "the", "labelDescriptor" ]
python
train
FNNDSC/med2image
med2image/systemMisc.py
https://github.com/FNNDSC/med2image/blob/638d5d230de47608af20f9764acf8e382c2bf2ff/med2image/systemMisc.py#L160-L181
def com_find(ar_grid): """ Find the center of mass in array grid <ar_grid>. Mass elements are grid index values. Return an array, in format (x, y), i.e. col, row! """ f_x = 0 f_y = 0 f_m = 0 for i in range(len(ar_grid)): for j in range(len(ar_grid[i])): if ar_grid[i...
[ "def", "com_find", "(", "ar_grid", ")", ":", "f_x", "=", "0", "f_y", "=", "0", "f_m", "=", "0", "for", "i", "in", "range", "(", "len", "(", "ar_grid", ")", ")", ":", "for", "j", "in", "range", "(", "len", "(", "ar_grid", "[", "i", "]", ")", ...
Find the center of mass in array grid <ar_grid>. Mass elements are grid index values. Return an array, in format (x, y), i.e. col, row!
[ "Find", "the", "center", "of", "mass", "in", "array", "grid", "<ar_grid", ">", ".", "Mass", "elements", "are", "grid", "index", "values", "." ]
python
train
Chilipp/psyplot
psyplot/data.py
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L52-L74
def _no_auto_update_getter(self): """:class:`bool`. Boolean controlling whether the :meth:`start_update` method is automatically called by the :meth:`update` method Examples -------- You can disable the automatic update via >>> with data.no_auto_update: ... data.update(time=1)...
[ "def", "_no_auto_update_getter", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_no_auto_update'", ",", "None", ")", "is", "not", "None", ":", "return", "self", ".", "_no_auto_update", "else", ":", "self", ".", "_no_auto_update", "=", "utils", ...
:class:`bool`. Boolean controlling whether the :meth:`start_update` method is automatically called by the :meth:`update` method Examples -------- You can disable the automatic update via >>> with data.no_auto_update: ... data.update(time=1) ... data.start_update() ...
[ ":", "class", ":", "bool", ".", "Boolean", "controlling", "whether", "the", ":", "meth", ":", "start_update", "method", "is", "automatically", "called", "by", "the", ":", "meth", ":", "update", "method" ]
python
train
crs4/pydoop
pydoop/hdfs/__init__.py
https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/hdfs/__init__.py#L129-L143
def dump(data, hdfs_path, **kwargs): """\ Write ``data`` to ``hdfs_path``. Keyword arguments are passed to :func:`open`, except for ``mode``, which is forced to ``"w"`` (or ``"wt"`` for text data). """ kwargs["mode"] = "w" if isinstance(data, bintype) else "wt" with open(hdfs_path, **kwargs...
[ "def", "dump", "(", "data", ",", "hdfs_path", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"mode\"", "]", "=", "\"w\"", "if", "isinstance", "(", "data", ",", "bintype", ")", "else", "\"wt\"", "with", "open", "(", "hdfs_path", ",", "*", "*", ...
\ Write ``data`` to ``hdfs_path``. Keyword arguments are passed to :func:`open`, except for ``mode``, which is forced to ``"w"`` (or ``"wt"`` for text data).
[ "\\", "Write", "data", "to", "hdfs_path", "." ]
python
train
quantumlib/Cirq
cirq/experiments/qubit_characterizations.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/experiments/qubit_characterizations.py#L82-L94
def plot(self, **plot_kwargs: Any) -> None: """Plots the average ground state probability vs the number of Cliffords in the RB study. Args: **plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot. """ fig = plt.figure() plt.plot(self._num_cfds_seq, se...
[ "def", "plot", "(", "self", ",", "*", "*", "plot_kwargs", ":", "Any", ")", "->", "None", ":", "fig", "=", "plt", ".", "figure", "(", ")", "plt", ".", "plot", "(", "self", ".", "_num_cfds_seq", ",", "self", ".", "_gnd_state_probs", ",", "'ro-'", ","...
Plots the average ground state probability vs the number of Cliffords in the RB study. Args: **plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot.
[ "Plots", "the", "average", "ground", "state", "probability", "vs", "the", "number", "of", "Cliffords", "in", "the", "RB", "study", "." ]
python
train
BYU-PCCL/holodeck
holodeck/command.py
https://github.com/BYU-PCCL/holodeck/blob/01acd4013f5acbd9f61fbc9caaafe19975e8b121/holodeck/command.py#L122-L130
def set_type(self, agent_type): """Set the type of agent to spawn in Holodeck. Currently accepted agents are: DiscreteSphereAgent, UAVAgent, and AndroidAgent. Args: agent_type (str): The type of agent to spawn. """ type_str = SpawnAgentCommand.__type_keys[agent_type]...
[ "def", "set_type", "(", "self", ",", "agent_type", ")", ":", "type_str", "=", "SpawnAgentCommand", ".", "__type_keys", "[", "agent_type", "]", "self", ".", "add_string_parameters", "(", "type_str", ")" ]
Set the type of agent to spawn in Holodeck. Currently accepted agents are: DiscreteSphereAgent, UAVAgent, and AndroidAgent. Args: agent_type (str): The type of agent to spawn.
[ "Set", "the", "type", "of", "agent", "to", "spawn", "in", "Holodeck", ".", "Currently", "accepted", "agents", "are", ":", "DiscreteSphereAgent", "UAVAgent", "and", "AndroidAgent", "." ]
python
train
pydanny/cookiecutter-django
hooks/post_gen_project.py
https://github.com/pydanny/cookiecutter-django/blob/bb9b482e96d1966e20745eeea87a8aa10ed1c861/hooks/post_gen_project.py#L107-L129
def generate_random_string( length, using_digits=False, using_ascii_letters=False, using_punctuation=False ): """ Example: opting out for 50 symbol-long, [a-z][A-Z][0-9] string would yield log_2((26+26+50)^50) ~= 334 bit strength. """ if not using_sysrandom: return None ...
[ "def", "generate_random_string", "(", "length", ",", "using_digits", "=", "False", ",", "using_ascii_letters", "=", "False", ",", "using_punctuation", "=", "False", ")", ":", "if", "not", "using_sysrandom", ":", "return", "None", "symbols", "=", "[", "]", "if"...
Example: opting out for 50 symbol-long, [a-z][A-Z][0-9] string would yield log_2((26+26+50)^50) ~= 334 bit strength.
[ "Example", ":", "opting", "out", "for", "50", "symbol", "-", "long", "[", "a", "-", "z", "]", "[", "A", "-", "Z", "]", "[", "0", "-", "9", "]", "string", "would", "yield", "log_2", "((", "26", "+", "26", "+", "50", ")", "^50", ")", "~", "="...
python
test
kolypto/py-exdoc
exdoc/py/__init__.py
https://github.com/kolypto/py-exdoc/blob/516526c01c203271410e7d7340024ef9f0bfa46a/exdoc/py/__init__.py#L159-L181
def _docspec(func, module=None, qualname=None, of_class=None): """ For a callable, get the full spec by merging doc_parse() and argspec() :type func: Callable :rtype: data.FDocstring """ sp = _argspec(func) doc = _doc_parse(getdoc(func), module=module, qualname=qualname) # Merge args d...
[ "def", "_docspec", "(", "func", ",", "module", "=", "None", ",", "qualname", "=", "None", ",", "of_class", "=", "None", ")", ":", "sp", "=", "_argspec", "(", "func", ")", "doc", "=", "_doc_parse", "(", "getdoc", "(", "func", ")", ",", "module", "="...
For a callable, get the full spec by merging doc_parse() and argspec() :type func: Callable :rtype: data.FDocstring
[ "For", "a", "callable", "get", "the", "full", "spec", "by", "merging", "doc_parse", "()", "and", "argspec", "()" ]
python
train
epfl-idevelop/epfl-ldap
epflldap/ldap_search.py
https://github.com/epfl-idevelop/epfl-ldap/blob/bebb94da3609d358bd83f31672eeaddcda872c5d/epflldap/ldap_search.py#L137-L150
def get_username(sciper): """ Return username of user """ attribute = 'uid' response = LDAP_search( pattern_search='(uniqueIdentifier={})'.format(sciper), attribute=attribute ) try: username = get_attribute(response, attribute) except Exception: raise Epfl...
[ "def", "get_username", "(", "sciper", ")", ":", "attribute", "=", "'uid'", "response", "=", "LDAP_search", "(", "pattern_search", "=", "'(uniqueIdentifier={})'", ".", "format", "(", "sciper", ")", ",", "attribute", "=", "attribute", ")", "try", ":", "username"...
Return username of user
[ "Return", "username", "of", "user" ]
python
train
jason-weirather/py-seq-tools
seqtools/format/sam/bam/bamindex.py
https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/format/sam/bam/bamindex.py#L163-L171
def get_range_start_line_number(self,rng): """ .. warning:: not implemented """ sys.stderr.write("error unimplemented get_range_start_line\n") sys.exit() for i in range(0,len(self._lines)): if rng.cmp(self._lines[i]['rng'])==0: return i+1 return None
[ "def", "get_range_start_line_number", "(", "self", ",", "rng", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"error unimplemented get_range_start_line\\n\"", ")", "sys", ".", "exit", "(", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "s...
.. warning:: not implemented
[ "..", "warning", "::", "not", "implemented" ]
python
train
Rapptz/discord.py
discord/client.py
https://github.com/Rapptz/discord.py/blob/05d4f7f9620ef33635d6ac965b26528e09cdaf5b/discord/client.py#L881-L913
async def fetch_guild(self, guild_id): """|coro| Retrieves a :class:`.Guild` from an ID. .. note:: Using this, you will not receive :attr:`.Guild.channels`, :class:`.Guild.members`, :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`. .. no...
[ "async", "def", "fetch_guild", "(", "self", ",", "guild_id", ")", ":", "data", "=", "await", "self", ".", "http", ".", "get_guild", "(", "guild_id", ")", "return", "Guild", "(", "data", "=", "data", ",", "state", "=", "self", ".", "_connection", ")" ]
|coro| Retrieves a :class:`.Guild` from an ID. .. note:: Using this, you will not receive :attr:`.Guild.channels`, :class:`.Guild.members`, :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`. .. note:: This method is an API call. For ...
[ "|coro|" ]
python
train
ssokolow/fastdupes
fastdupes.py
https://github.com/ssokolow/fastdupes/blob/0334545885445834307c075a445fba9fe6f0c9e7/fastdupes.py#L217-L263
def groupBy(groups_in, classifier, fun_desc='?', keep_uniques=False, *args, **kwargs): """Subdivide groups of paths according to a function. :param groups_in: Grouped sets of paths. :type groups_in: :class:`~__builtins__.dict` of iterables :param classifier: Function to group a list of pat...
[ "def", "groupBy", "(", "groups_in", ",", "classifier", ",", "fun_desc", "=", "'?'", ",", "keep_uniques", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "groups", ",", "count", ",", "group_count", "=", "{", "}", ",", "0", ",", "l...
Subdivide groups of paths according to a function. :param groups_in: Grouped sets of paths. :type groups_in: :class:`~__builtins__.dict` of iterables :param classifier: Function to group a list of paths by some attribute. :type classifier: ``function(list, *args, **kwargs) -> str`` :param fun_des...
[ "Subdivide", "groups", "of", "paths", "according", "to", "a", "function", "." ]
python
valid
koszullab/metaTOR
metator/scripts/hicstuff.py
https://github.com/koszullab/metaTOR/blob/0c1203d1dffedfa5ea380c0335b4baa9cfb7e89a/metator/scripts/hicstuff.py#L174-L205
def bin_sparse(M, subsampling_factor=3): """Perform the bin_dense procedure for sparse matrices. Remaining rows and cols are lumped with the rest at the end. """ try: from scipy.sparse import coo_matrix except ImportError as e: print(str(e)) print("I am peforming dense binni...
[ "def", "bin_sparse", "(", "M", ",", "subsampling_factor", "=", "3", ")", ":", "try", ":", "from", "scipy", ".", "sparse", "import", "coo_matrix", "except", "ImportError", "as", "e", ":", "print", "(", "str", "(", "e", ")", ")", "print", "(", "\"I am pe...
Perform the bin_dense procedure for sparse matrices. Remaining rows and cols are lumped with the rest at the end.
[ "Perform", "the", "bin_dense", "procedure", "for", "sparse", "matrices", ".", "Remaining", "rows", "and", "cols", "are", "lumped", "with", "the", "rest", "at", "the", "end", "." ]
python
train
bokeh/bokeh
bokeh/sphinxext/bokehjs_content.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/sphinxext/bokehjs_content.py#L268-L277
def setup(app): ''' Required Sphinx extension setup function. ''' app.add_node( bokehjs_content, html=( html_visit_bokehjs_content, html_depart_bokehjs_content ) ) app.add_directive('bokehjs-content', BokehJSContent)
[ "def", "setup", "(", "app", ")", ":", "app", ".", "add_node", "(", "bokehjs_content", ",", "html", "=", "(", "html_visit_bokehjs_content", ",", "html_depart_bokehjs_content", ")", ")", "app", ".", "add_directive", "(", "'bokehjs-content'", ",", "BokehJSContent", ...
Required Sphinx extension setup function.
[ "Required", "Sphinx", "extension", "setup", "function", "." ]
python
train
xeroc/python-graphenelib
graphenecommon/price.py
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/price.py#L291-L306
def json(self): """ return { "base": self["base"].json(), "quote": self["quote"].json() } """ quote = self["quote"] base = self["base"] frac = Fraction(int(quote) / int(base)).limit_denominator( 10 ** base["asset"]["precision"] ...
[ "def", "json", "(", "self", ")", ":", "quote", "=", "self", "[", "\"quote\"", "]", "base", "=", "self", "[", "\"base\"", "]", "frac", "=", "Fraction", "(", "int", "(", "quote", ")", "/", "int", "(", "base", ")", ")", ".", "limit_denominator", "(", ...
return { "base": self["base"].json(), "quote": self["quote"].json() }
[ "return", "{", "base", ":", "self", "[", "base", "]", ".", "json", "()", "quote", ":", "self", "[", "quote", "]", ".", "json", "()", "}" ]
python
valid
KrishnaswamyLab/graphtools
graphtools/base.py
https://github.com/KrishnaswamyLab/graphtools/blob/44685352be7df2005d44722903092207967457f2/graphtools/base.py#L40-L66
def _get_param_names(cls): """Get parameter names for the estimator""" # fetch the constructor or the original constructor before # deprecation wrapping if any init = getattr(cls.__init__, 'deprecated_original', cls.__init__) if init is object.__init__: # No explicit ...
[ "def", "_get_param_names", "(", "cls", ")", ":", "# fetch the constructor or the original constructor before", "# deprecation wrapping if any", "init", "=", "getattr", "(", "cls", ".", "__init__", ",", "'deprecated_original'", ",", "cls", ".", "__init__", ")", "if", "in...
Get parameter names for the estimator
[ "Get", "parameter", "names", "for", "the", "estimator" ]
python
train
knipknap/SpiffWorkflow
SpiffWorkflow/util/event.py
https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/util/event.py#L89-L120
def listen(self, callback, *args, **kwargs): """ Like :class:`connect()`, but uses a weak reference instead of a normal reference. The signal is automatically disconnected as soon as the handler is garbage collected. .. note:: Storing signal handlers as weak...
[ "def", "listen", "(", "self", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "lock", "is", "None", ":", "self", ".", "lock", "=", "Lock", "(", ")", "with", "self", ".", "lock", ":", "if", "self", ".", ...
Like :class:`connect()`, but uses a weak reference instead of a normal reference. The signal is automatically disconnected as soon as the handler is garbage collected. .. note:: Storing signal handlers as weak references means that if your handler is a local fun...
[ "Like", ":", "class", ":", "connect", "()", "but", "uses", "a", "weak", "reference", "instead", "of", "a", "normal", "reference", ".", "The", "signal", "is", "automatically", "disconnected", "as", "soon", "as", "the", "handler", "is", "garbage", "collected",...
python
valid
SUSE-Enceladus/ipa
ipa/ipa_cloud.py
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L351-L360
def _set_distro(self): """Determine distro for image and create instance of class.""" if self.distro_name == 'sles': self.distro = SLES() elif self.distro_name == 'opensuse_leap': self.distro = openSUSE_Leap() else: raise IpaCloudException( ...
[ "def", "_set_distro", "(", "self", ")", ":", "if", "self", ".", "distro_name", "==", "'sles'", ":", "self", ".", "distro", "=", "SLES", "(", ")", "elif", "self", ".", "distro_name", "==", "'opensuse_leap'", ":", "self", ".", "distro", "=", "openSUSE_Leap...
Determine distro for image and create instance of class.
[ "Determine", "distro", "for", "image", "and", "create", "instance", "of", "class", "." ]
python
train
Yubico/python-yubico
yubico/yubikey_config.py
https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L408-L429
def extended_flag(self, which, new=None): """ Get or set a extended flag. 'which' can be either a string ('SERIAL_API_VISIBLE' etc.), or an integer. You should ALWAYS use a string, unless you really know what you are doing. """ flag = _get_flag(which, ExtendedFlags) ...
[ "def", "extended_flag", "(", "self", ",", "which", ",", "new", "=", "None", ")", ":", "flag", "=", "_get_flag", "(", "which", ",", "ExtendedFlags", ")", "if", "flag", ":", "if", "not", "self", ".", "capabilities", ".", "have_extended_flag", "(", "flag", ...
Get or set a extended flag. 'which' can be either a string ('SERIAL_API_VISIBLE' etc.), or an integer. You should ALWAYS use a string, unless you really know what you are doing.
[ "Get", "or", "set", "a", "extended", "flag", "." ]
python
train
saltstack/salt
salt/modules/x509.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L401-L407
def _get_pubkey_hash(cert): ''' Returns the sha1 hash of the modulus of a public key in a cert Used for generating subject key identifiers ''' sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest() return _pretty_hex(sha_hash)
[ "def", "_get_pubkey_hash", "(", "cert", ")", ":", "sha_hash", "=", "hashlib", ".", "sha1", "(", "cert", ".", "get_pubkey", "(", ")", ".", "get_modulus", "(", ")", ")", ".", "hexdigest", "(", ")", "return", "_pretty_hex", "(", "sha_hash", ")" ]
Returns the sha1 hash of the modulus of a public key in a cert Used for generating subject key identifiers
[ "Returns", "the", "sha1", "hash", "of", "the", "modulus", "of", "a", "public", "key", "in", "a", "cert", "Used", "for", "generating", "subject", "key", "identifiers" ]
python
train
dhhagan/py-opc
opc/__init__.py
https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L951-L959
def off(self): """Turn OFF the OPC (fan and laser) :returns: boolean success state """ b1 = self.cnxn.xfer([0x03])[0] # send the command byte sleep(9e-3) # sleep for 9 ms return True if b1 == 0xF3 else False
[ "def", "off", "(", "self", ")", ":", "b1", "=", "self", ".", "cnxn", ".", "xfer", "(", "[", "0x03", "]", ")", "[", "0", "]", "# send the command byte", "sleep", "(", "9e-3", ")", "# sleep for 9 ms", "return", "True", "if", "b1", "==", "0xF3", "else",...
Turn OFF the OPC (fan and laser) :returns: boolean success state
[ "Turn", "OFF", "the", "OPC", "(", "fan", "and", "laser", ")" ]
python
valid
saltstack/salt
salt/utils/pkg/rpm.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/pkg/rpm.py#L98-L123
def parse_pkginfo(line, osarch=None): ''' A small helper to parse an rpm/repoquery command's output. Returns a pkginfo namedtuple. ''' try: name, epoch, version, release, arch, repoid, install_time = line.split('_|-') # Handle unpack errors (should never happen with the queryformat we ar...
[ "def", "parse_pkginfo", "(", "line", ",", "osarch", "=", "None", ")", ":", "try", ":", "name", ",", "epoch", ",", "version", ",", "release", ",", "arch", ",", "repoid", ",", "install_time", "=", "line", ".", "split", "(", "'_|-'", ")", "# Handle unpack...
A small helper to parse an rpm/repoquery command's output. Returns a pkginfo namedtuple.
[ "A", "small", "helper", "to", "parse", "an", "rpm", "/", "repoquery", "command", "s", "output", ".", "Returns", "a", "pkginfo", "namedtuple", "." ]
python
train
has2k1/plotnine
plotnine/facets/layout.py
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L205-L223
def xlabel(self, labels): """ Determine x-axis label Parameters ---------- labels : dict Labels as specified by the user through the ``labs`` or ``xlab`` calls. Returns ------- out : str x-axis label """ ...
[ "def", "xlabel", "(", "self", ",", "labels", ")", ":", "if", "self", ".", "panel_scales_x", "[", "0", "]", ".", "name", "is", "not", "None", ":", "return", "self", ".", "panel_scales_x", "[", "0", "]", ".", "name", "else", ":", "return", "labels", ...
Determine x-axis label Parameters ---------- labels : dict Labels as specified by the user through the ``labs`` or ``xlab`` calls. Returns ------- out : str x-axis label
[ "Determine", "x", "-", "axis", "label" ]
python
train
openego/eDisGo
edisgo/grid/components.py
https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/grid/components.py#L344-L368
def power_factor(self): """ Power factor of load Parameters ----------- power_factor : :obj:`float` Ratio of real power to apparent power. Returns -------- :obj:`float` Ratio of real power to apparent power. If power factor is not...
[ "def", "power_factor", "(", "self", ")", ":", "if", "self", ".", "_power_factor", "is", "None", ":", "if", "isinstance", "(", "self", ".", "grid", ",", "MVGrid", ")", ":", "self", ".", "_power_factor", "=", "self", ".", "grid", ".", "network", ".", "...
Power factor of load Parameters ----------- power_factor : :obj:`float` Ratio of real power to apparent power. Returns -------- :obj:`float` Ratio of real power to apparent power. If power factor is not set it is retrieved from the ne...
[ "Power", "factor", "of", "load" ]
python
train
numba/llvmlite
llvmlite/binding/value.py
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/value.py#L282-L293
def operands(self): """ Return an iterator over this instruction's operands. The iterator will yield a ValueRef for each operand. """ if not self.is_instruction: raise ValueError('expected instruction value, got %s' % (self._kind,)) ...
[ "def", "operands", "(", "self", ")", ":", "if", "not", "self", ".", "is_instruction", ":", "raise", "ValueError", "(", "'expected instruction value, got %s'", "%", "(", "self", ".", "_kind", ",", ")", ")", "it", "=", "ffi", ".", "lib", ".", "LLVMPY_Instruc...
Return an iterator over this instruction's operands. The iterator will yield a ValueRef for each operand.
[ "Return", "an", "iterator", "over", "this", "instruction", "s", "operands", ".", "The", "iterator", "will", "yield", "a", "ValueRef", "for", "each", "operand", "." ]
python
train
klahnakoski/pyLibrary
mo_dots/__init__.py
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_dots/__init__.py#L307-L319
def set_attr(obj, path, value): """ SAME AS object.__setattr__(), BUT USES DOT-DELIMITED path RETURN OLD VALUE """ try: return _set_attr(obj, split_field(path), value) except Exception as e: Log = get_logger() if PATH_NOT_FOUND in e: Log.warning(PATH_NOT_FOUND...
[ "def", "set_attr", "(", "obj", ",", "path", ",", "value", ")", ":", "try", ":", "return", "_set_attr", "(", "obj", ",", "split_field", "(", "path", ")", ",", "value", ")", "except", "Exception", "as", "e", ":", "Log", "=", "get_logger", "(", ")", "...
SAME AS object.__setattr__(), BUT USES DOT-DELIMITED path RETURN OLD VALUE
[ "SAME", "AS", "object", ".", "__setattr__", "()", "BUT", "USES", "DOT", "-", "DELIMITED", "path", "RETURN", "OLD", "VALUE" ]
python
train
tanghaibao/goatools
goatools/rpt/rpt_lev_depth.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/rpt/rpt_lev_depth.py#L149-L156
def get_cnts_levels_depths_recs(recs): """Collect counts of levels and depths in a Group of GO Terms.""" cnts = cx.defaultdict(lambda: cx.defaultdict(cx.Counter)) for rec in recs: if rec is not None and not rec.is_obsolete: cnts['level'][rec.level][rec.namespace] += 1...
[ "def", "get_cnts_levels_depths_recs", "(", "recs", ")", ":", "cnts", "=", "cx", ".", "defaultdict", "(", "lambda", ":", "cx", ".", "defaultdict", "(", "cx", ".", "Counter", ")", ")", "for", "rec", "in", "recs", ":", "if", "rec", "is", "not", "None", ...
Collect counts of levels and depths in a Group of GO Terms.
[ "Collect", "counts", "of", "levels", "and", "depths", "in", "a", "Group", "of", "GO", "Terms", "." ]
python
train
saulpw/visidata
visidata/cmdlog.py
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/cmdlog.py#L171-L218
def moveToReplayContext(self, r): 'set the sheet/row/col to the values in the replay row. return sheet' if not r.sheet: # assert not r.col and not r.row return self # any old sheet should do, row/column don't matter try: sheetidx = int(r.sheet) v...
[ "def", "moveToReplayContext", "(", "self", ",", "r", ")", ":", "if", "not", "r", ".", "sheet", ":", "# assert not r.col and not r.row", "return", "self", "# any old sheet should do, row/column don't matter", "try", ":", "sheetidx", "=", "int", "(", "r", "...
set the sheet/row/col to the values in the replay row. return sheet
[ "set", "the", "sheet", "/", "row", "/", "col", "to", "the", "values", "in", "the", "replay", "row", ".", "return", "sheet" ]
python
train
merry-bits/DBQuery
src/dbquery/query.py
https://github.com/merry-bits/DBQuery/blob/5f46dc94e2721129f8a799b5f613373e6cd9cb73/src/dbquery/query.py#L113-L125
def show(self, *args, **kwds): """ Show how the SQL looks like when executed by the DB. This might not be supported by all connection types. For example: PostgreSQL does support it, SQLite does not. :rtype: str """ # Same as in __call__, arguments win over keywords ...
[ "def", "show", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "# Same as in __call__, arguments win over keywords", "arg", "=", "args", "if", "not", "arg", ":", "arg", "=", "kwds", "# pylint: disable=redefined-variable-type", "return", "self", "...
Show how the SQL looks like when executed by the DB. This might not be supported by all connection types. For example: PostgreSQL does support it, SQLite does not. :rtype: str
[ "Show", "how", "the", "SQL", "looks", "like", "when", "executed", "by", "the", "DB", "." ]
python
train
ARMmbed/yotta
yotta/lib/component.py
https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/component.py#L250-L277
def getDependencies(self, available_components = None, search_dirs = None, target = None, available_only = False, test = False, warnings = True ): ''' Returns {component_name:component} ''' ...
[ "def", "getDependencies", "(", "self", ",", "available_components", "=", "None", ",", "search_dirs", "=", "None", ",", "target", "=", "None", ",", "available_only", "=", "False", ",", "test", "=", "False", ",", "warnings", "=", "True", ")", ":", "if", "s...
Returns {component_name:component}
[ "Returns", "{", "component_name", ":", "component", "}" ]
python
valid
treycucco/bidon
bidon/field_mapping.py
https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/field_mapping.py#L19-L40
def get_value(self, source): """Apply self.convert to the source. The parameter passed to convert depends on self.source_name. If source_name is given, self.convert(getattr(source, source_name)) is called, otherwise self.convert(source) is called. """ if self.source_name is None: present, valu...
[ "def", "get_value", "(", "self", ",", "source", ")", ":", "if", "self", ".", "source_name", "is", "None", ":", "present", ",", "value", "=", "True", ",", "self", ".", "convert", "(", "source", ")", "converted", "=", "True", "else", ":", "present", ",...
Apply self.convert to the source. The parameter passed to convert depends on self.source_name. If source_name is given, self.convert(getattr(source, source_name)) is called, otherwise self.convert(source) is called.
[ "Apply", "self", ".", "convert", "to", "the", "source", ".", "The", "parameter", "passed", "to", "convert", "depends", "on", "self", ".", "source_name", ".", "If", "source_name", "is", "given", "self", ".", "convert", "(", "getattr", "(", "source", "source...
python
train
swisscom/cleanerversion
versions/admin.py
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L261-L295
def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from django.contrib.admin.models import LogEntry # First check if the user can see this history. model = self.model obj = get_object_or_404(self.get_queryset(request), ...
[ "def", "history_view", "(", "self", ",", "request", ",", "object_id", ",", "extra_context", "=", "None", ")", ":", "from", "django", ".", "contrib", ".", "admin", ".", "models", "import", "LogEntry", "# First check if the user can see this history.", "model", "=",...
The 'history' admin view for this model.
[ "The", "history", "admin", "view", "for", "this", "model", "." ]
python
train
SBRG/ssbio
ssbio/protein/structure/properties/fatcat.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/properties/fatcat.py#L14-L43
def run_fatcat(structure_path_1, structure_path_2, fatcat_sh, outdir='', silent=False, print_cmd=False, force_rerun=False): """Run FATCAT on two PDB files, and return the path of the XML result file. Args: structure_path_1 (str): Path to PDB file structure_path_2 (str): Path to PDB file ...
[ "def", "run_fatcat", "(", "structure_path_1", ",", "structure_path_2", ",", "fatcat_sh", ",", "outdir", "=", "''", ",", "silent", "=", "False", ",", "print_cmd", "=", "False", ",", "force_rerun", "=", "False", ")", ":", "filename1", "=", "op", ".", "splite...
Run FATCAT on two PDB files, and return the path of the XML result file. Args: structure_path_1 (str): Path to PDB file structure_path_2 (str): Path to PDB file fatcat_sh (str): Path to "runFATCAT.sh" executable script outdir (str): Path to where FATCAT XML output files will b...
[ "Run", "FATCAT", "on", "two", "PDB", "files", "and", "return", "the", "path", "of", "the", "XML", "result", "file", ".", "Args", ":", "structure_path_1", "(", "str", ")", ":", "Path", "to", "PDB", "file", "structure_path_2", "(", "str", ")", ":", "Path...
python
train
Azure/azure-cosmos-python
azure/cosmos/execution_context/query_execution_info.py
https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/execution_context/query_execution_info.py#L67-L74
def get_rewritten_query(self): """Returns rewritten query or None (if any) """ rewrittenQuery = self._extract(_PartitionedQueryExecutionInfo.RewrittenQueryPath) if rewrittenQuery is not None: # Hardcode formattable filter to true for now rewrittenQuery = rewritte...
[ "def", "get_rewritten_query", "(", "self", ")", ":", "rewrittenQuery", "=", "self", ".", "_extract", "(", "_PartitionedQueryExecutionInfo", ".", "RewrittenQueryPath", ")", "if", "rewrittenQuery", "is", "not", "None", ":", "# Hardcode formattable filter to true for now ", ...
Returns rewritten query or None (if any)
[ "Returns", "rewritten", "query", "or", "None", "(", "if", "any", ")" ]
python
train
pyroscope/pyrocore
src/pyrocore/torrent/rtorrent.py
https://github.com/pyroscope/pyrocore/blob/89ad01346a570943d20311a0b488440975876612/src/pyrocore/torrent/rtorrent.py#L122-L133
def _memoize(self, name, getter, *args, **kwargs): """ Cache a stable expensive-to-get item value for later (optimized) retrieval. """ field = "custom_m_" + name cached = self.fetch(field) if cached: value = cached else: value = getter(*args, **kwa...
[ "def", "_memoize", "(", "self", ",", "name", ",", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "field", "=", "\"custom_m_\"", "+", "name", "cached", "=", "self", ".", "fetch", "(", "field", ")", "if", "cached", ":", "value", "=", ...
Cache a stable expensive-to-get item value for later (optimized) retrieval.
[ "Cache", "a", "stable", "expensive", "-", "to", "-", "get", "item", "value", "for", "later", "(", "optimized", ")", "retrieval", "." ]
python
train
jdrumgoole/mongodbshell
mongodbshell/__init__.py
https://github.com/jdrumgoole/mongodbshell/blob/7e194247ea2adc1f124532935507cdffafa2c1f6/mongodbshell/__init__.py#L454-L536
def pager(self, lines): """ Outputs lines to a terminal. It uses `shutil.get_terminal_size` to determine the height of the terminal. It expects an iterator that returns a line at a time and those lines should be terminated by a valid newline sequence. Behaviour is contro...
[ "def", "pager", "(", "self", ",", "lines", ")", ":", "try", ":", "line_count", "=", "0", "if", "self", ".", "_output_filename", ":", "print", "(", "f\"Output is also going to '{self.output_file}'\"", ")", "self", ".", "_output_file", "=", "open", "(", "self", ...
Outputs lines to a terminal. It uses `shutil.get_terminal_size` to determine the height of the terminal. It expects an iterator that returns a line at a time and those lines should be terminated by a valid newline sequence. Behaviour is controlled by a number of external class propertie...
[ "Outputs", "lines", "to", "a", "terminal", ".", "It", "uses", "shutil", ".", "get_terminal_size", "to", "determine", "the", "height", "of", "the", "terminal", ".", "It", "expects", "an", "iterator", "that", "returns", "a", "line", "at", "a", "time", "and",...
python
train
tnkteja/myhelp
virtualEnvironment/lib/python2.7/site-packages/coverage/execfile.py
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/execfile.py#L23-L70
def run_python_module(modulename, args): """Run a python module, as though with ``python -m name args...``. `modulename` is the name of the module, possibly a dot-separated name. `args` is the argument array to present as sys.argv, including the first element naming the module being executed. """ ...
[ "def", "run_python_module", "(", "modulename", ",", "args", ")", ":", "openfile", "=", "None", "glo", ",", "loc", "=", "globals", "(", ")", ",", "locals", "(", ")", "try", ":", "try", ":", "# Search for the module - inside its parent package, if any - using", "#...
Run a python module, as though with ``python -m name args...``. `modulename` is the name of the module, possibly a dot-separated name. `args` is the argument array to present as sys.argv, including the first element naming the module being executed.
[ "Run", "a", "python", "module", "as", "though", "with", "python", "-", "m", "name", "args", "...", "." ]
python
test
allenai/allennlp
allennlp/data/dataset_readers/dataset_reader.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/dataset_reader.py#L91-L145
def read(self, file_path: str) -> Iterable[Instance]: """ Returns an ``Iterable`` containing all the instances in the specified dataset. If ``self.lazy`` is False, this calls ``self._read()``, ensures that the result is a list, then returns the resulting list. If ``self...
[ "def", "read", "(", "self", ",", "file_path", ":", "str", ")", "->", "Iterable", "[", "Instance", "]", ":", "lazy", "=", "getattr", "(", "self", ",", "'lazy'", ",", "None", ")", "if", "lazy", "is", "None", ":", "logger", ".", "warning", "(", "\"Dat...
Returns an ``Iterable`` containing all the instances in the specified dataset. If ``self.lazy`` is False, this calls ``self._read()``, ensures that the result is a list, then returns the resulting list. If ``self.lazy`` is True, this returns an object whose ``__iter__`` method ...
[ "Returns", "an", "Iterable", "containing", "all", "the", "instances", "in", "the", "specified", "dataset", "." ]
python
train
schlamar/latexmk.py
latexmake.py
https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L160-L169
def _is_toc_changed(self, toc_file): ''' Test if the *.toc file has changed during the first latex run. ''' fname = '%s.toc' % self.project_name if os.path.isfile(fname): with open(fname) as fobj: if fobj.read() != toc_file: ...
[ "def", "_is_toc_changed", "(", "self", ",", "toc_file", ")", ":", "fname", "=", "'%s.toc'", "%", "self", ".", "project_name", "if", "os", ".", "path", ".", "isfile", "(", "fname", ")", ":", "with", "open", "(", "fname", ")", "as", "fobj", ":", "if", ...
Test if the *.toc file has changed during the first latex run.
[ "Test", "if", "the", "*", ".", "toc", "file", "has", "changed", "during", "the", "first", "latex", "run", "." ]
python
train
coordt/django-alphabetfilter
alphafilter/templatetags/alphafilter.py
https://github.com/coordt/django-alphabetfilter/blob/a7bc21c0ea985c2021a4668241bf643c615c6c1f/alphafilter/templatetags/alphafilter.py#L177-L202
def qs_alphabet_filter(parser, token): """ The parser/tokenizer for the queryset alphabet filter. {% qs_alphabet_filter <queryset> <field name> [<template name>] [strip_params=comma,delim,list] %} {% qs_alphabet_filter objects lastname myapp/template.html %} The template name is optional and uses...
[ "def", "qs_alphabet_filter", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "==", "3", ":", "return", "AlphabetFilterNode", "(", "bits", "[", "1", "]", ",", "bits", "[", "2...
The parser/tokenizer for the queryset alphabet filter. {% qs_alphabet_filter <queryset> <field name> [<template name>] [strip_params=comma,delim,list] %} {% qs_alphabet_filter objects lastname myapp/template.html %} The template name is optional and uses alphafilter/alphabet.html if not specified
[ "The", "parser", "/", "tokenizer", "for", "the", "queryset", "alphabet", "filter", "." ]
python
train
saltstack/salt
salt/modules/ddns.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ddns.py#L55-L68
def _config(name, key=None, **kwargs): ''' Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'. ''' if key is None: key = name if name in kwargs: value = kwargs[name] else: value ...
[ "def", "_config", "(", "name", ",", "key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "key", "is", "None", ":", "key", "=", "name", "if", "name", "in", "kwargs", ":", "value", "=", "kwargs", "[", "name", "]", "else", ":", "value", "=...
Return a value for 'name' from command line args then config file options. Specify 'key' if the config file option is not the same as 'name'.
[ "Return", "a", "value", "for", "name", "from", "command", "line", "args", "then", "config", "file", "options", ".", "Specify", "key", "if", "the", "config", "file", "option", "is", "not", "the", "same", "as", "name", "." ]
python
train
rkhleics/wagtailmodeladmin
wagtailmodeladmin/options.py
https://github.com/rkhleics/wagtailmodeladmin/blob/7fddc853bab2ff3868b8c7a03329308c55f16358/wagtailmodeladmin/options.py#L481-L490
def get_permissions_for_registration(self): """ Utilised by Wagtail's 'register_permissions' hook to allow permissions for a model to be assigned to groups in settings. This is only required if the model isn't a Page model, and isn't registered as a Snippet """ from wagta...
[ "def", "get_permissions_for_registration", "(", "self", ")", ":", "from", "wagtail", ".", "wagtailsnippets", ".", "models", "import", "SNIPPET_MODELS", "if", "not", "self", ".", "is_pagemodel", "and", "self", ".", "model", "not", "in", "SNIPPET_MODELS", ":", "re...
Utilised by Wagtail's 'register_permissions' hook to allow permissions for a model to be assigned to groups in settings. This is only required if the model isn't a Page model, and isn't registered as a Snippet
[ "Utilised", "by", "Wagtail", "s", "register_permissions", "hook", "to", "allow", "permissions", "for", "a", "model", "to", "be", "assigned", "to", "groups", "in", "settings", ".", "This", "is", "only", "required", "if", "the", "model", "isn", "t", "a", "Pa...
python
train
susam/ice
ice.py
https://github.com/susam/ice/blob/532e685c504ea96f9e42833594585159ac1d2068/ice.py#L50-L91
def cube(): """Return an Ice application with a default home page. Create :class:`Ice` object, add a route to return the default page when a client requests the server root, i.e. /, using HTTP GET method, add an error handler to return HTTP error pages when an error occurs and return this object. T...
[ "def", "cube", "(", ")", ":", "app", "=", "Ice", "(", ")", "@", "app", ".", "get", "(", "'/'", ")", "def", "default_home_page", "(", ")", ":", "\"\"\"Return a default home page.\"\"\"", "return", "simple_html", "(", "'It works!'", ",", "'<h1>It works!</h1>\\n'...
Return an Ice application with a default home page. Create :class:`Ice` object, add a route to return the default page when a client requests the server root, i.e. /, using HTTP GET method, add an error handler to return HTTP error pages when an error occurs and return this object. The returned object ...
[ "Return", "an", "Ice", "application", "with", "a", "default", "home", "page", "." ]
python
test
pycontribs/jira
jira/client.py
https://github.com/pycontribs/jira/blob/397db5d78441ed6a680a9b7db4c62030ade1fd8a/jira/client.py#L1821-L1828
def add_vote(self, issue): """Register a vote for the current authenticated user on an issue. :param issue: ID or key of the issue to vote on :rtype: Response """ url = self._get_url('issue/' + str(issue) + '/votes') return self._session.post(url)
[ "def", "add_vote", "(", "self", ",", "issue", ")", ":", "url", "=", "self", ".", "_get_url", "(", "'issue/'", "+", "str", "(", "issue", ")", "+", "'/votes'", ")", "return", "self", ".", "_session", ".", "post", "(", "url", ")" ]
Register a vote for the current authenticated user on an issue. :param issue: ID or key of the issue to vote on :rtype: Response
[ "Register", "a", "vote", "for", "the", "current", "authenticated", "user", "on", "an", "issue", "." ]
python
train