text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def add_tmp(self, value):
"""Add a temporary variable to the scope.
Parameters
----------
value : object
An arbitrary object to be assigned to a temporary variable.
Returns
-------
name : basestring
The name of the temporary variable crea... | [
"def",
"add_tmp",
"(",
"self",
",",
"value",
")",
":",
"name",
"=",
"'{name}_{num}_{hex_id}'",
".",
"format",
"(",
"name",
"=",
"type",
"(",
"value",
")",
".",
"__name__",
",",
"num",
"=",
"self",
".",
"ntemps",
",",
"hex_id",
"=",
"_raw_hex_id",
"(",
... | 31.041667 | 20.875 |
def add_layer3_vlan_interface(self, interface_id, vlan_id, address=None,
network_value=None, virtual_mapping=None, virtual_resource_name=None,
zone_ref=None, comment=None, **kw):
"""
Add a Layer 3 VLAN interface. Optionally specify an address and network if
assigning an IP to the... | [
"def",
"add_layer3_vlan_interface",
"(",
"self",
",",
"interface_id",
",",
"vlan_id",
",",
"address",
"=",
"None",
",",
"network_value",
"=",
"None",
",",
"virtual_mapping",
"=",
"None",
",",
"virtual_resource_name",
"=",
"None",
",",
"zone_ref",
"=",
"None",
... | 53.707692 | 24.507692 |
def processMeme(imgParams):
'''
Wrapper function for genMeme() and findMeme()
imgParams may be a string of the following forms:
* 'text0 | text1'
* 'text0'
* ' | text1'
Fails gracefully when it can't find or generate a meme
by returning an appropriate image url with the failure
mess... | [
"def",
"processMeme",
"(",
"imgParams",
")",
":",
"template_id",
"=",
"findMeme",
"(",
"imgParams",
")",
"if",
"template_id",
"is",
"None",
":",
"print",
"(",
"\"Couldn't find a suitable match for meme :(\"",
")",
"return",
"meme_not_supported",
"# if template_id exists... | 29.76087 | 20.369565 |
def get_market_history(self, market):
"""
Used to retrieve the latest trades that have occurred for a
specific market.
Endpoint:
1.1 /market/getmarkethistory
2.0 NO Equivalent
Example ::
{'success': True,
'message': '',
'resul... | [
"def",
"get_market_history",
"(",
"self",
",",
"market",
")",
":",
"return",
"self",
".",
"_api_query",
"(",
"path_dict",
"=",
"{",
"API_V1_1",
":",
"'/public/getmarkethistory'",
",",
"}",
",",
"options",
"=",
"{",
"'market'",
":",
"market",
",",
"'marketnam... | 33.064516 | 15.516129 |
def bucket_type_key(bucket_type):
"""
Registers a function that calculates test item key for the specified bucket type.
"""
def decorator(f):
@functools.wraps(f)
def wrapped(item, session):
key = f(item)
if session is not None:
for handler in se... | [
"def",
"bucket_type_key",
"(",
"bucket_type",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"item",
",",
"session",
")",
":",
"key",
"=",
"f",
"(",
"item",
")",
"if",
"sessio... | 24.142857 | 21.571429 |
def _generate_sdss_object_name(
self):
"""
*generate sdss object names for the results*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
"""
self.log.info('starting the ``_generate_sdss_object_name`` method')
con... | [
"def",
"_generate_sdss_object_name",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'starting the ``_generate_sdss_object_name`` method'",
")",
"converter",
"=",
"unit_conversion",
"(",
"log",
"=",
"self",
".",
"log",
")",
"# Names should be of the form... | 29.954545 | 21.863636 |
def pop_state(self, idx=None):
"""
Pops off the most recent state.
:param idx: If provided, specifies the index at which the next
string begins.
"""
self.state.pop()
if idx is not None:
self.str_begin = idx | [
"def",
"pop_state",
"(",
"self",
",",
"idx",
"=",
"None",
")",
":",
"self",
".",
"state",
".",
"pop",
"(",
")",
"if",
"idx",
"is",
"not",
"None",
":",
"self",
".",
"str_begin",
"=",
"idx"
] | 23.166667 | 17 |
def shortcut(*names):
"""Add an shortcut (alias) to a decorated function, but not to class methods!
Use aliased/alias decorators for class members!
Calling the shortcut (alias) will call the decorated function. The shortcut name will be appended
to the module's __all__ variable and the shortcut functi... | [
"def",
"shortcut",
"(",
"*",
"names",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"globals_",
"=",
"f",
".",
"__globals__",
"for",
"name",
"in",
"names",
":",
"globals_",
"[",
"name",
"]",
"=",
"f",
"if",
"'__all__'",
"in",
"globals_",
"and",
"nam... | 35.653846 | 22.038462 |
def _create_chord_chart(self, data, works, output_dir):
"""Generates and writes to a file in `output_dir` the data used to
display a chord chart.
:param data: data to derive the chord data from
:type data: `pandas.DataFrame`
:param works: works to display
:type works: `l... | [
"def",
"_create_chord_chart",
"(",
"self",
",",
"data",
",",
"works",
",",
"output_dir",
")",
":",
"matrix",
"=",
"[",
"]",
"chord_data",
"=",
"data",
".",
"unstack",
"(",
"BASE_WORK",
")",
"[",
"SHARED",
"]",
"for",
"index",
",",
"row_data",
"in",
"ch... | 45.272727 | 17.5 |
def write(self, file_or_filename, prog=None, format='xdot'):
""" Writes the case data in Graphviz DOT language.
The format 'raw' is used to dump the Dot representation of the Case
object, without further processing. The output can be processed by any
of graphviz tools, defined in 'prog'... | [
"def",
"write",
"(",
"self",
",",
"file_or_filename",
",",
"prog",
"=",
"None",
",",
"format",
"=",
"'xdot'",
")",
":",
"if",
"prog",
"is",
"None",
":",
"file",
"=",
"super",
"(",
"DotWriter",
",",
"self",
")",
".",
"write",
"(",
"file_or_filename",
... | 36.466667 | 17.233333 |
def init_get(self, request):
"""
Initialize the :class:`LogoutView` attributes on GET request
:param django.http.HttpRequest request: The current request object
"""
self.request = request
self.service = request.GET.get('service')
self.url = request.GET.ge... | [
"def",
"init_get",
"(",
"self",
",",
"request",
")",
":",
"self",
".",
"request",
"=",
"request",
"self",
".",
"service",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'service'",
")",
"self",
".",
"url",
"=",
"request",
".",
"GET",
".",
"get",
"("... | 40.3 | 18.5 |
def validate(args):
"""
cldf validate <DATASET>
Validate a dataset against the CLDF specification, i.e. check
- whether required tables and columns are present
- whether values for required columns are present
- the referential integrity of the dataset
"""
ds = _get_dataset(args)
ds... | [
"def",
"validate",
"(",
"args",
")",
":",
"ds",
"=",
"_get_dataset",
"(",
"args",
")",
"ds",
".",
"validate",
"(",
"log",
"=",
"args",
".",
"log",
")"
] | 30.272727 | 14.090909 |
def _writeFeatures(self, i, image):
"""
Write a text file containing the features as a table.
@param i: The number of the image in self._images.
@param image: A member of self._images.
@return: The C{str} features file name - just the base name, not
including the pat... | [
"def",
"_writeFeatures",
"(",
"self",
",",
"i",
",",
"image",
")",
":",
"basename",
"=",
"'features-%d.txt'",
"%",
"i",
"filename",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"_outputDir",
",",
"basename",
")",
"featureList",
"=",
"image",
"[",
"'graphInfo'",
... | 39.9375 | 11.5625 |
def get(self, request,pk):
"""
If the user requests his profile return it, else return a 403 (Forbidden)
"""
requested_profile = Profile.objects.get(user=pk)
if requested_profile.user == self.request.user:
return render(request, self.template... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"pk",
")",
":",
"requested_profile",
"=",
"Profile",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"pk",
")",
"if",
"requested_profile",
".",
"user",
"==",
"self",
".",
"request",
".",
"user",
":",
"ret... | 33 | 21.923077 |
def _grid_widgets(self):
"""Put the widgets in the correct position based on self.__compound."""
orient = str(self._scale.cget('orient'))
self._scale.grid(row=2, column=2, sticky='ew' if orient == tk.HORIZONTAL else 'ns',
padx=(0, self.__entryscalepad) if self.__compound... | [
"def",
"_grid_widgets",
"(",
"self",
")",
":",
"orient",
"=",
"str",
"(",
"self",
".",
"_scale",
".",
"cget",
"(",
"'orient'",
")",
")",
"self",
".",
"_scale",
".",
"grid",
"(",
"row",
"=",
"2",
",",
"column",
"=",
"2",
",",
"sticky",
"=",
"'ew'"... | 53.653846 | 22 |
def attached_to_model(self):
"""Tells if the current index is the one attached to the model field, not instance field"""
try:
if not bool(self.model):
return False
except AttributeError:
return False
else:
try:
return no... | [
"def",
"attached_to_model",
"(",
"self",
")",
":",
"try",
":",
"if",
"not",
"bool",
"(",
"self",
".",
"model",
")",
":",
"return",
"False",
"except",
"AttributeError",
":",
"return",
"False",
"else",
":",
"try",
":",
"return",
"not",
"bool",
"(",
"self... | 32.75 | 13.166667 |
def _get_non_empty_list(cls, iter):
"""Return a list of the input, excluding all ``None`` values."""
res = []
for value in iter:
if hasattr(value, 'items'):
value = cls._get_non_empty_dict(value) or None
if value is not None:
res.append(val... | [
"def",
"_get_non_empty_list",
"(",
"cls",
",",
"iter",
")",
":",
"res",
"=",
"[",
"]",
"for",
"value",
"in",
"iter",
":",
"if",
"hasattr",
"(",
"value",
",",
"'items'",
")",
":",
"value",
"=",
"cls",
".",
"_get_non_empty_dict",
"(",
"value",
")",
"or... | 37.111111 | 11.333333 |
def attachments_ping(request):
"""Heartbeat view for the attachments backend.
:returns: ``True`` if succeeds to write and delete, ``False`` otherwise.
"""
# Do nothing if server is readonly.
if asbool(request.registry.settings.get('readonly', False)):
return True
# We will fake a file u... | [
"def",
"attachments_ping",
"(",
"request",
")",
":",
"# Do nothing if server is readonly.",
"if",
"asbool",
"(",
"request",
".",
"registry",
".",
"settings",
".",
"get",
"(",
"'readonly'",
",",
"False",
")",
")",
":",
"return",
"True",
"# We will fake a file uploa... | 36.428571 | 22.892857 |
def default_get_arg_names_from_class_name(class_name):
"""Converts normal class names into normal arg names.
Normal class names are assumed to be CamelCase with an optional leading
underscore. Normal arg names are assumed to be lower_with_underscores.
Args:
class_name: a class name, e.g., "FooB... | [
"def",
"default_get_arg_names_from_class_name",
"(",
"class_name",
")",
":",
"parts",
"=",
"[",
"]",
"rest",
"=",
"class_name",
"if",
"rest",
".",
"startswith",
"(",
"'_'",
")",
":",
"rest",
"=",
"rest",
"[",
"1",
":",
"]",
"while",
"True",
":",
"m",
"... | 30.75 | 20.5 |
def put(self, path=None, method='PUT', **options):
""" Equals :meth:`route` with a ``PUT`` method parameter. """
return self.route(path, method, **options) | [
"def",
"put",
"(",
"self",
",",
"path",
"=",
"None",
",",
"method",
"=",
"'PUT'",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"route",
"(",
"path",
",",
"method",
",",
"*",
"*",
"options",
")"
] | 56.333333 | 6.666667 |
def _format_type(cls):
"""Format a type name for printing."""
if cls.__module__ == _BUILTIN_MODULE:
return cls.__name__
else:
return '%s.%s' % (cls.__module__, cls.__name__) | [
"def",
"_format_type",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__module__",
"==",
"_BUILTIN_MODULE",
":",
"return",
"cls",
".",
"__name__",
"else",
":",
"return",
"'%s.%s'",
"%",
"(",
"cls",
".",
"__module__",
",",
"cls",
".",
"__name__",
")"
] | 32.666667 | 13 |
def taskotron_task_outcome(config, message, outcome=None):
""" Particular taskotron task outcome
With this rule, you can limit messages to only those of particular
`taskotron <https://taskotron.fedoraproject.org/>`_ task outcome.
You can specify several outcomes by separating them with a comma ',',
... | [
"def",
"taskotron_task_outcome",
"(",
"config",
",",
"message",
",",
"outcome",
"=",
"None",
")",
":",
"# We only operate on taskotron messages, first off.",
"if",
"not",
"taskotron_result_new",
"(",
"config",
",",
"message",
")",
":",
"return",
"False",
"if",
"not"... | 36.652174 | 25.26087 |
def rating(self, **kwargs):
"""
This method lets users rate a movie. A valid session id or guest
session id is required.
Args:
session_id: see Authentication.
guest_session_id: see Authentication.
value: Rating value.
Returns:
A d... | [
"def",
"rating",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"self",
".",
"_get_id_path",
"(",
"'rating'",
")",
"payload",
"=",
"{",
"'value'",
":",
"kwargs",
".",
"pop",
"(",
"'value'",
",",
"None",
")",
",",
"}",
"response",
"=",... | 27.636364 | 18.454545 |
async def _report_version(self):
"""
This is a private message handler method.
This method reads the following 2 bytes after the report version
command (0xF9 - non sysex).
The first byte is the major number and the second byte is the
minor number.
:returns: None
... | [
"async",
"def",
"_report_version",
"(",
"self",
")",
":",
"# get next two bytes",
"major",
"=",
"await",
"self",
".",
"read",
"(",
")",
"version_string",
"=",
"str",
"(",
"major",
")",
"minor",
"=",
"await",
"self",
".",
"read",
"(",
")",
"version_string",... | 35 | 14.411765 |
def thellier_interpreter_BS_pars_calc(self, Grade_As):
'''
calcualte sample or site bootstrap paleointensities
and statistics
Grade_As={}
'''
thellier_interpreter_pars = {}
thellier_interpreter_pars['fail_criteria'] = []
thellier_interpreter_pars['pass_or_... | [
"def",
"thellier_interpreter_BS_pars_calc",
"(",
"self",
",",
"Grade_As",
")",
":",
"thellier_interpreter_pars",
"=",
"{",
"}",
"thellier_interpreter_pars",
"[",
"'fail_criteria'",
"]",
"=",
"[",
"]",
"thellier_interpreter_pars",
"[",
"'pass_or_fail'",
"]",
"=",
"'pas... | 51.564516 | 24.048387 |
def command(cmd):
"""Execute command and raise an exception upon an error.
>>> 'README' in command('ls')
True
>>> command('nonexistingcommand') #doctest: +ELLIPSIS
Traceback (most recent call last):
...
SdistCreationError
"""
status, out = commands.getstatusoutput(cmd)... | [
"def",
"command",
"(",
"cmd",
")",
":",
"status",
",",
"out",
"=",
"commands",
".",
"getstatusoutput",
"(",
"cmd",
")",
"if",
"status",
"is",
"not",
"0",
":",
"logger",
".",
"error",
"(",
"\"Something went wrong:\"",
")",
"logger",
".",
"error",
"(",
"... | 26.470588 | 16.529412 |
def deploy(self, config_file, region=None, profile_name=None):
"""
Deploy the configuration and Lambda functions of a Greengrass group to
the Greengrass core contained in the group.
:param config_file: config file of the group to deploy
:param region: the region from which to de... | [
"def",
"deploy",
"(",
"self",
",",
"config_file",
",",
"region",
"=",
"None",
",",
"profile_name",
"=",
"None",
")",
":",
"config",
"=",
"GroupConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"if",
"config",
".",
"is_fresh",
"(",
")",
":",
"rais... | 38.666667 | 20.814815 |
def get_api_version(base_url, api_version=None, timeout=10, verify=True):
"""
Get the API version specified or resolve the latest version
:return api version
:rtype: float
"""
versions = available_api_versions(base_url, timeout, verify)
newest_version = max([float(i) for i in versions]... | [
"def",
"get_api_version",
"(",
"base_url",
",",
"api_version",
"=",
"None",
",",
"timeout",
"=",
"10",
",",
"verify",
"=",
"True",
")",
":",
"versions",
"=",
"available_api_versions",
"(",
"base_url",
",",
"timeout",
",",
"verify",
")",
"newest_version",
"="... | 29.588235 | 17.705882 |
def init(opts):
'''
This function gets called when the proxy starts up. For
login
the protocol and port are cached.
'''
log.debug('Initting esxcluster proxy module in process %s', os.getpid())
log.debug('Validating esxcluster proxy input')
schema = EsxclusterProxySchema.serialize()
l... | [
"def",
"init",
"(",
"opts",
")",
":",
"log",
".",
"debug",
"(",
"'Initting esxcluster proxy module in process %s'",
",",
"os",
".",
"getpid",
"(",
")",
")",
"log",
".",
"debug",
"(",
"'Validating esxcluster proxy input'",
")",
"schema",
"=",
"EsxclusterProxySchema... | 39.721311 | 15.557377 |
def format_request_email_templ(increq, template, **ctx):
"""Format the email message element for inclusion request notification.
Formats the message according to the provided template file, using
some default fields from 'increq' object as default context.
Arbitrary context can be provided as keywords ... | [
"def",
"format_request_email_templ",
"(",
"increq",
",",
"template",
",",
"*",
"*",
"ctx",
")",
":",
"# Add minimal information to the contex (without overwriting).",
"curate_link",
"=",
"'{site_url}/communities/{id}/curate/'",
".",
"format",
"(",
"site_url",
"=",
"current_... | 38.176471 | 20.352941 |
def view_dot_graph(graph, filename=None, view=False):
"""
View the given DOT source. If view is True, the image is rendered
and viewed by the default application in the system. The file path of
the output is returned. If view is False, a graphviz.Source object is
returned. If view is False and t... | [
"def",
"view_dot_graph",
"(",
"graph",
",",
"filename",
"=",
"None",
",",
"view",
"=",
"False",
")",
":",
"# Optionally depends on graphviz package",
"import",
"graphviz",
"as",
"gv",
"src",
"=",
"gv",
".",
"Source",
"(",
"graph",
")",
"if",
"view",
":",
"... | 34.111111 | 21.722222 |
def data_ma(self):
"""
A 2D `~numpy.ma.MaskedArray` cutout image of the segment using
the minimal bounding box.
The mask is `True` for pixels outside of the source segment
(i.e. neighboring segments within the rectangular cutout image
are masked).
"""
ma... | [
"def",
"data_ma",
"(",
"self",
")",
":",
"mask",
"=",
"(",
"self",
".",
"_segment_img",
"[",
"self",
".",
"slices",
"]",
"!=",
"self",
".",
"label",
")",
"return",
"np",
".",
"ma",
".",
"masked_array",
"(",
"self",
".",
"_segment_img",
"[",
"self",
... | 36.416667 | 22.75 |
def mtime(self, fpath=None):
"""
Returns:
str: strftime-formatted mtime (modification time) of fpath
"""
return dtformat(
datetime.datetime.utcfromtimestamp(
os.path.getmtime(fpath or self.fpath))) | [
"def",
"mtime",
"(",
"self",
",",
"fpath",
"=",
"None",
")",
":",
"return",
"dtformat",
"(",
"datetime",
".",
"datetime",
".",
"utcfromtimestamp",
"(",
"os",
".",
"path",
".",
"getmtime",
"(",
"fpath",
"or",
"self",
".",
"fpath",
")",
")",
")"
] | 32.75 | 13 |
def read_line(csv_contents, options, prop_indices, mol, ensemble_list=None):
"""
read csv line
"""
if not ensemble_list:
score_field = options.score_field
status_field = options.status_field
active_label = options.active_label
decoy_label = options.decoy_label
# do the active/decoy la... | [
"def",
"read_line",
"(",
"csv_contents",
",",
"options",
",",
"prop_indices",
",",
"mol",
",",
"ensemble_list",
"=",
"None",
")",
":",
"if",
"not",
"ensemble_list",
":",
"score_field",
"=",
"options",
".",
"score_field",
"status_field",
"=",
"options",
".",
... | 32.916667 | 17.9375 |
def wvalue(wave, indep_var):
r"""
Return the dependent variable value at a given independent variable point.
If the independent variable point is not in the independent variable vector
the dependent variable value is obtained by linear interpolation
:param wave: Waveform
:type wave: :py:class... | [
"def",
"wvalue",
"(",
"wave",
",",
"indep_var",
")",
":",
"close_min",
"=",
"np",
".",
"isclose",
"(",
"indep_var",
",",
"wave",
".",
"_indep_vector",
"[",
"0",
"]",
",",
"FP_RTOL",
",",
"FP_ATOL",
")",
"close_max",
"=",
"np",
".",
"isclose",
"(",
"i... | 36.040816 | 24.061224 |
def _setLearningMode(self, l4Learning = False, l2Learning=False):
"""
Sets the learning mode for L4 and L2.
"""
for column in self.L4Columns:
column.setParameter("learn", 0, l4Learning)
for column in self.L2Columns:
column.setParameter("learningMode", 0, l2Learning) | [
"def",
"_setLearningMode",
"(",
"self",
",",
"l4Learning",
"=",
"False",
",",
"l2Learning",
"=",
"False",
")",
":",
"for",
"column",
"in",
"self",
".",
"L4Columns",
":",
"column",
".",
"setParameter",
"(",
"\"learn\"",
",",
"0",
",",
"l4Learning",
")",
"... | 36.375 | 8.125 |
def truncate_graph_bbox(G, north, south, east, west, truncate_by_edge=False, retain_all=False):
"""
Remove every node in graph that falls outside a bounding box.
Needed because overpass returns entire ways that also include nodes outside
the bbox if the way (that is, a way with a single OSM ID) has a n... | [
"def",
"truncate_graph_bbox",
"(",
"G",
",",
"north",
",",
"south",
",",
"east",
",",
"west",
",",
"truncate_by_edge",
"=",
"False",
",",
"retain_all",
"=",
"False",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"G",
"=",
"G",
".",
"cop... | 36.676471 | 21.117647 |
def add_buttons(self, *args):
"""add_buttons(*args)
The add_buttons() method adds several buttons to the Gtk.Dialog using
the button data passed as arguments to the method. This method is the
same as calling the Gtk.Dialog.add_button() repeatedly. The button data
pairs - button ... | [
"def",
"add_buttons",
"(",
"self",
",",
"*",
"args",
")",
":",
"def",
"_button",
"(",
"b",
")",
":",
"while",
"b",
":",
"t",
",",
"r",
"=",
"b",
"[",
"0",
":",
"2",
"]",
"b",
"=",
"b",
"[",
"2",
":",
"]",
"yield",
"t",
",",
"r",
"try",
... | 34.884615 | 22.884615 |
def pitch_hz_to_contour(annotation):
'''Convert a pitch_hz annotation to a contour'''
annotation.namespace = 'pitch_contour'
data = annotation.pop_data()
for obs in data:
annotation.append(time=obs.time, duration=obs.duration,
confidence=obs.confidence,
... | [
"def",
"pitch_hz_to_contour",
"(",
"annotation",
")",
":",
"annotation",
".",
"namespace",
"=",
"'pitch_contour'",
"data",
"=",
"annotation",
".",
"pop_data",
"(",
")",
"for",
"obs",
"in",
"data",
":",
"annotation",
".",
"append",
"(",
"time",
"=",
"obs",
... | 40.583333 | 15.75 |
def target_socket(self, config):
""" This method overrides :meth:`.WNetworkNativeTransport.target_socket` method. Do the same thing as
basic method do, but also checks that the result address is IPv4 address.
:param config: beacon configuration
:return: WIPV4SocketInfo
"""
target = WNetworkNativeTransport.... | [
"def",
"target_socket",
"(",
"self",
",",
"config",
")",
":",
"target",
"=",
"WNetworkNativeTransport",
".",
"target_socket",
"(",
"self",
",",
"config",
")",
"if",
"isinstance",
"(",
"target",
".",
"address",
"(",
")",
",",
"WIPV4Address",
")",
"is",
"Fal... | 43.090909 | 16.909091 |
def get_task_log(self, project, release_id, environment_id, release_deploy_phase_id, task_id, start_line=None, end_line=None, **kwargs):
"""GetTaskLog.
[Preview API] Gets the task log of a release as a plain text file.
:param str project: Project ID or project name
:param int release_id:... | [
"def",
"get_task_log",
"(",
"self",
",",
"project",
",",
"release_id",
",",
"environment_id",
",",
"release_deploy_phase_id",
",",
"task_id",
",",
"start_line",
"=",
"None",
",",
"end_line",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"route_values",
"="... | 56.512821 | 24.487179 |
def add_api_stage_to_api_key(self, api_key, api_id, stage_name):
"""
Add api stage to Api key
"""
self.apigateway_client.update_api_key(
apiKey=api_key,
patchOperations=[
{
'op': 'add',
'path': '/stages',
... | [
"def",
"add_api_stage_to_api_key",
"(",
"self",
",",
"api_key",
",",
"api_id",
",",
"stage_name",
")",
":",
"self",
".",
"apigateway_client",
".",
"update_api_key",
"(",
"apiKey",
"=",
"api_key",
",",
"patchOperations",
"=",
"[",
"{",
"'op'",
":",
"'add'",
"... | 29.214286 | 14.214286 |
def check_block_spacing(
self,
first_block_type: LineType,
second_block_type: LineType,
error_message: str,
) -> typing.Generator[AAAError, None, None]:
"""
Checks there is a clear single line between ``first_block_type`` and
``second_block_type``.
No... | [
"def",
"check_block_spacing",
"(",
"self",
",",
"first_block_type",
":",
"LineType",
",",
"second_block_type",
":",
"LineType",
",",
"error_message",
":",
"str",
",",
")",
"->",
"typing",
".",
"Generator",
"[",
"AAAError",
",",
"None",
",",
"None",
"]",
":",... | 34.285714 | 21.22449 |
def RegisterMessage(self, message):
"""Registers the given message type in the local database.
Args:
message: a message.Message, to be registered.
Returns:
The provided message.
"""
desc = message.DESCRIPTOR
self._symbols[desc.full_name] = message
if desc.file.name not in self... | [
"def",
"RegisterMessage",
"(",
"self",
",",
"message",
")",
":",
"desc",
"=",
"message",
".",
"DESCRIPTOR",
"self",
".",
"_symbols",
"[",
"desc",
".",
"full_name",
"]",
"=",
"message",
"if",
"desc",
".",
"file",
".",
"name",
"not",
"in",
"self",
".",
... | 28.941176 | 17.470588 |
def count_comments_handler(sender, **kwargs):
"""
Update Entry.comment_count when a public comment was posted.
"""
comment = kwargs['comment']
if comment.is_public:
entry = comment.content_object
if isinstance(entry, Entry):
entry.comment_count = F('comment_count') + 1
... | [
"def",
"count_comments_handler",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"comment",
"=",
"kwargs",
"[",
"'comment'",
"]",
"if",
"comment",
".",
"is_public",
":",
"entry",
"=",
"comment",
".",
"content_object",
"if",
"isinstance",
"(",
"entry",
",... | 36.4 | 9 |
def save_metadata(self, data_dir, feature_name=None):
"""See base class for details."""
filepath = _get_metadata_filepath(data_dir, feature_name)
with tf.io.gfile.GFile(filepath, 'w') as f:
json.dump({
'shape': [-1 if d is None else d for d in self._shape],
'encoding_format': self.... | [
"def",
"save_metadata",
"(",
"self",
",",
"data_dir",
",",
"feature_name",
"=",
"None",
")",
":",
"filepath",
"=",
"_get_metadata_filepath",
"(",
"data_dir",
",",
"feature_name",
")",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"filepath",
",... | 44.75 | 14.125 |
def _where_in_sub(self, column, query, boolean, negate=False):
"""
Add a where in with a sub select to the query
:param column: The column
:type column: str
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param boolean: The boolean operator
... | [
"def",
"_where_in_sub",
"(",
"self",
",",
"column",
",",
"query",
",",
"boolean",
",",
"negate",
"=",
"False",
")",
":",
"if",
"negate",
":",
"type",
"=",
"'not_in_sub'",
"else",
":",
"type",
"=",
"'in_sub'",
"self",
".",
"wheres",
".",
"append",
"(",
... | 23.235294 | 18.882353 |
def get_git_postversion(addon_dir):
""" return the addon version number, with a developmental version increment
if there were git commits in the addon_dir after the last version change.
If the last change to the addon correspond to the version number in the
manifest it is used as is for the python pack... | [
"def",
"get_git_postversion",
"(",
"addon_dir",
")",
":",
"addon_dir",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"addon_dir",
")",
"last_version",
"=",
"read_manifest",
"(",
"addon_dir",
")",
".",
"get",
"(",
"'version'",
",",
"'0.0.0'",
")",
"last_versi... | 38.018868 | 18.056604 |
def rotate(self):
""" Rotate the kill ring, then yank back the new top.
Returns
-------
A text string or None.
"""
self._index -= 1
if self._index >= 0:
return self._ring[self._index]
return None | [
"def",
"rotate",
"(",
"self",
")",
":",
"self",
".",
"_index",
"-=",
"1",
"if",
"self",
".",
"_index",
">=",
"0",
":",
"return",
"self",
".",
"_ring",
"[",
"self",
".",
"_index",
"]",
"return",
"None"
] | 23.818182 | 15.818182 |
def multisorted(items, *keys):
"""Sort by multiple attributes.
Args:
items: An iterable series to be sorted.
*keys: Key objects which extract key values from the items.
The first key will be the most significant, and the
last key the least significant. If no key function... | [
"def",
"multisorted",
"(",
"items",
",",
"*",
"keys",
")",
":",
"if",
"len",
"(",
"keys",
")",
"==",
"0",
":",
"keys",
"=",
"[",
"asc",
"(",
")",
"]",
"for",
"key",
"in",
"reversed",
"(",
"keys",
")",
":",
"items",
"=",
"sorted",
"(",
"items",
... | 34.722222 | 18.277778 |
def convertDict2Attrs(self, *args, **kwargs):
"""The trick for iterable Mambu Objects comes here:
You iterate over each element of the responded List from Mambu,
and create a Mambu Group object for each one, initializing them
one at a time, and changing the attrs attribute (which just
... | [
"def",
"convertDict2Attrs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"n",
",",
"c",
"in",
"enumerate",
"(",
"self",
".",
"attrs",
")",
":",
"# ok ok, I'm modifying elements of a list while iterating it. BAD PRACTICE!",
"try",
":",... | 45.551724 | 19.965517 |
def tag(self, tokens):
"""Return a list of (token, tag) tuples for a given list of tokens."""
# Lazy load model first time we tag
if not self.classes:
self.load(self.model)
prev, prev2 = self.START
tags = []
for i, token in enumerate(tokens):
tag =... | [
"def",
"tag",
"(",
"self",
",",
"tokens",
")",
":",
"# Lazy load model first time we tag",
"if",
"not",
"self",
".",
"classes",
":",
"self",
".",
"load",
"(",
"self",
".",
"model",
")",
"prev",
",",
"prev2",
"=",
"self",
".",
"START",
"tags",
"=",
"[",... | 36.5625 | 12.0625 |
def _debugGraph(self):
"""internal util to print out contents of graph"""
print("Len of graph: ", len(self.rdflib_graph))
for x, y, z in self.rdflib_graph:
print(x, y, z) | [
"def",
"_debugGraph",
"(",
"self",
")",
":",
"print",
"(",
"\"Len of graph: \"",
",",
"len",
"(",
"self",
".",
"rdflib_graph",
")",
")",
"for",
"x",
",",
"y",
",",
"z",
"in",
"self",
".",
"rdflib_graph",
":",
"print",
"(",
"x",
",",
"y",
",",
"z",
... | 40.4 | 9.6 |
def compare(ver1='', oper='==', ver2='', cmp_func=None, ignore_epoch=False):
'''
Compares two version numbers. Accepts a custom function to perform the
cmp-style version comparison, otherwise uses version_cmp().
'''
cmp_map = {'<': (-1,), '<=': (-1, 0), '==': (0,),
'>=': (0, 1), '>': ... | [
"def",
"compare",
"(",
"ver1",
"=",
"''",
",",
"oper",
"=",
"'=='",
",",
"ver2",
"=",
"''",
",",
"cmp_func",
"=",
"None",
",",
"ignore_epoch",
"=",
"False",
")",
":",
"cmp_map",
"=",
"{",
"'<'",
":",
"(",
"-",
"1",
",",
")",
",",
"'<='",
":",
... | 32.705882 | 21.470588 |
def from_data_frame(df, categorical=False, nb_classes=None):
"""Convert DataFrame back to pair of numpy arrays
"""
lp_rdd = df.rdd.map(lambda row: LabeledPoint(row.label, row.features))
features, labels = from_labeled_point(lp_rdd, categorical, nb_classes)
return features, labels | [
"def",
"from_data_frame",
"(",
"df",
",",
"categorical",
"=",
"False",
",",
"nb_classes",
"=",
"None",
")",
":",
"lp_rdd",
"=",
"df",
".",
"rdd",
".",
"map",
"(",
"lambda",
"row",
":",
"LabeledPoint",
"(",
"row",
".",
"label",
",",
"row",
".",
"featu... | 49.166667 | 16.833333 |
def get_s3_multipart_chunk_size(filesize):
"""Returns the chunk size of the S3 multipart object, given a file's size."""
if filesize <= AWS_MAX_MULTIPART_COUNT * AWS_MIN_CHUNK_SIZE:
return AWS_MIN_CHUNK_SIZE
else:
div = filesize // AWS_MAX_MULTIPART_COUNT
if div * AWS_MAX_MULTIPART_C... | [
"def",
"get_s3_multipart_chunk_size",
"(",
"filesize",
")",
":",
"if",
"filesize",
"<=",
"AWS_MAX_MULTIPART_COUNT",
"*",
"AWS_MIN_CHUNK_SIZE",
":",
"return",
"AWS_MIN_CHUNK_SIZE",
"else",
":",
"div",
"=",
"filesize",
"//",
"AWS_MAX_MULTIPART_COUNT",
"if",
"div",
"*",
... | 43.888889 | 12.222222 |
def post(self, request, *args, **kwargs):
"""
Returns POST response.
:param request: the request instance.
:rtype: django.http.HttpResponse.
"""
form = None
link_type = int(request.POST.get('link_type', 0))
if link_type == Link.LINK_TYPE_EMAIL:
... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"form",
"=",
"None",
"link_type",
"=",
"int",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'link_type'",
",",
"0",
")",
")",
"if",
"link_type",
"==... | 30.545455 | 15 |
def delete(self, ids):
"""
Method to delete network-ipv4's by their ids
:param ids: Identifiers of network-ipv4's
:return: None
"""
url = build_uri_with_ids('api/v3/networkv4/%s/', ids)
return super(ApiNetworkIPv4, self).delete(url) | [
"def",
"delete",
"(",
"self",
",",
"ids",
")",
":",
"url",
"=",
"build_uri_with_ids",
"(",
"'api/v3/networkv4/%s/'",
",",
"ids",
")",
"return",
"super",
"(",
"ApiNetworkIPv4",
",",
"self",
")",
".",
"delete",
"(",
"url",
")"
] | 28.1 | 17.3 |
def use(self, middleware=None, path='/', method_mask=HTTPMethod.ALL):
"""
Use the middleware (a callable with parameters res, req, next)
upon requests match the provided path.
A None path matches every request.
Returns the middleware so this method may be used as a decorator.
... | [
"def",
"use",
"(",
"self",
",",
"middleware",
"=",
"None",
",",
"path",
"=",
"'/'",
",",
"method_mask",
"=",
"HTTPMethod",
".",
"ALL",
")",
":",
"# catch decorator pattern",
"if",
"middleware",
"is",
"None",
":",
"return",
"lambda",
"mw",
":",
"self",
".... | 42.959184 | 19.857143 |
def safeMakeDirs(path, mode=0o777):
"""
Creates the given directory path, as well as intermediate directories.
Catches any I/O exception, returning False in that case; otherwise,
True is returned.
"""
try:
os.makedirs(path, mode)
return True
... | [
"def",
"safeMakeDirs",
"(",
"path",
",",
"mode",
"=",
"0o777",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
",",
"mode",
")",
"return",
"True",
"except",
"OSError",
":",
"return",
"False"
] | 29.333333 | 18 |
def datetimes_to_durations(
start_times, end_times, fill_date=datetime.today(), freq="D", dayfirst=False, na_values=None
):
"""
This is a very flexible function for transforming arrays of start_times and end_times
to the proper format for lifelines: duration and event observation arrays.
Parameters... | [
"def",
"datetimes_to_durations",
"(",
"start_times",
",",
"end_times",
",",
"fill_date",
"=",
"datetime",
".",
"today",
"(",
")",
",",
"freq",
"=",
"\"D\"",
",",
"dayfirst",
"=",
"False",
",",
"na_values",
"=",
"None",
")",
":",
"fill_date",
"=",
"pd",
"... | 42.067797 | 25.932203 |
def validate_schema(instance, schema, test_required=True, data_location=None,
skip_missing_data=False):
"""Check if DictField values are consistent with our data types.
Perform basic JSON schema validation and our custom validations:
* check that required fields are given (if `test_r... | [
"def",
"validate_schema",
"(",
"instance",
",",
"schema",
",",
"test_required",
"=",
"True",
",",
"data_location",
"=",
"None",
",",
"skip_missing_data",
"=",
"False",
")",
":",
"from",
".",
"storage",
"import",
"Storage",
"# Prevent circular import.",
"path_prefi... | 40.254054 | 22.740541 |
def set_shaders(self, vert, frag):
""" This function takes care of setting the shading code and
compiling+linking it into a working program object that is ready
to use.
"""
self._linked = False
# Create temporary shader objects
vert_handle = gl.glCreateShader(gl.G... | [
"def",
"set_shaders",
"(",
"self",
",",
"vert",
",",
"frag",
")",
":",
"self",
".",
"_linked",
"=",
"False",
"# Create temporary shader objects",
"vert_handle",
"=",
"gl",
".",
"glCreateShader",
"(",
"gl",
".",
"GL_VERTEX_SHADER",
")",
"frag_handle",
"=",
"gl"... | 50.225 | 16.15 |
def deduplicate(s, ch):
"""
From http://stackoverflow.com/q/42216559/610569
s = 'this is an irritating string with random spacing .'
deduplicate(s)
'this is an irritating string with random spacing .'
"""
return ch.join([substring for substring in s.strip().split(ch) if su... | [
"def",
"deduplicate",
"(",
"s",
",",
"ch",
")",
":",
"return",
"ch",
".",
"join",
"(",
"[",
"substring",
"for",
"substring",
"in",
"s",
".",
"strip",
"(",
")",
".",
"split",
"(",
"ch",
")",
"if",
"substring",
"]",
")"
] | 35.666667 | 19.666667 |
def get_loss(modality_type, value=None):
"""Gets default loss transformation; if none available, return value."""
if modality_type in (ModalityType.AUDIO,
ModalityType.AUDIO_SPECTRAL,
ModalityType.CLASS_LABEL,
ModalityType.IDENTITY,
... | [
"def",
"get_loss",
"(",
"modality_type",
",",
"value",
"=",
"None",
")",
":",
"if",
"modality_type",
"in",
"(",
"ModalityType",
".",
"AUDIO",
",",
"ModalityType",
".",
"AUDIO_SPECTRAL",
",",
"ModalityType",
".",
"CLASS_LABEL",
",",
"ModalityType",
".",
"IDENTI... | 45.461538 | 13.038462 |
def _set_ndb_cache_policy():
"""Tell NDB to never cache anything in memcache or in-process.
This ensures that entities fetched from Datastore input_readers via NDB
will not bloat up the request memory size and Datastore Puts will avoid
doing calls to memcache. Without this you get soft memory limit exits,
wh... | [
"def",
"_set_ndb_cache_policy",
"(",
")",
":",
"ndb_ctx",
"=",
"ndb",
".",
"get_context",
"(",
")",
"ndb_ctx",
".",
"set_cache_policy",
"(",
"lambda",
"key",
":",
"False",
")",
"ndb_ctx",
".",
"set_memcache_policy",
"(",
"lambda",
"key",
":",
"False",
")"
] | 42.727273 | 16.454545 |
def rotation_matrix(phi, theta, psi):
"""Retourne la matrice de rotation décrite par les angles d'Euler donnés en paramètres"""
return np.dot(Rz_matrix(phi), np.dot(Rx_matrix(theta), Rz_matrix(psi))) | [
"def",
"rotation_matrix",
"(",
"phi",
",",
"theta",
",",
"psi",
")",
":",
"return",
"np",
".",
"dot",
"(",
"Rz_matrix",
"(",
"phi",
")",
",",
"np",
".",
"dot",
"(",
"Rx_matrix",
"(",
"theta",
")",
",",
"Rz_matrix",
"(",
"psi",
")",
")",
")"
] | 68.333333 | 12.666667 |
def parse_declarations(self, declarations):
"""
parse a css declaration list
"""
declarations = self.declaration_re.findall(declarations)
return dict(declarations) | [
"def",
"parse_declarations",
"(",
"self",
",",
"declarations",
")",
":",
"declarations",
"=",
"self",
".",
"declaration_re",
".",
"findall",
"(",
"declarations",
")",
"return",
"dict",
"(",
"declarations",
")"
] | 33 | 6.333333 |
def like_user(self, user_id, amount=None, filtration=True):
""" Likes last user_id's medias """
if filtration:
if not self.check_user(user_id):
return False
self.logger.info("Liking user_%s's feed:" % user_id)
user_id = self.convert_to_user_id(user_id)
medias = self.get_user_medi... | [
"def",
"like_user",
"(",
"self",
",",
"user_id",
",",
"amount",
"=",
"None",
",",
"filtration",
"=",
"True",
")",
":",
"if",
"filtration",
":",
"if",
"not",
"self",
".",
"check_user",
"(",
"user_id",
")",
":",
"return",
"False",
"self",
".",
"logger",
... | 41.384615 | 16.076923 |
def draw(self, mode, selection):
""" Draw program in given mode, with given selection (IndexBuffer or
first, count).
"""
if not self._linked:
raise RuntimeError('Cannot draw program if code has not been set')
# Init
gl.check_error('Check before draw')
... | [
"def",
"draw",
"(",
"self",
",",
"mode",
",",
"selection",
")",
":",
"if",
"not",
"self",
".",
"_linked",
":",
"raise",
"RuntimeError",
"(",
"'Cannot draw program if code has not been set'",
")",
"# Init",
"gl",
".",
"check_error",
"(",
"'Check before draw'",
")... | 34.964286 | 12.571429 |
def returns_true_or_raises(f):
"""A safety net.
Decorator for functions that are only allowed to return True or raise
an exception.
Args:
f: A function whose only expected return value is True.
Returns:
A wrapped functions whose guaranteed only return value is True.
"""
@f... | [
"def",
"returns_true_or_raises",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"r... | 27.368421 | 21.736842 |
def _sm_stop_from_pain(self, *args, **kwargs):
"""
Stop chaos while there is a blockade event in progress
"""
_logger.info("Stopping chaos for blockade %s" % self._blockade_name)
self._do_reset_all() | [
"def",
"_sm_stop_from_pain",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_logger",
".",
"info",
"(",
"\"Stopping chaos for blockade %s\"",
"%",
"self",
".",
"_blockade_name",
")",
"self",
".",
"_do_reset_all",
"(",
")"
] | 39 | 12.666667 |
def update_local_reference(self, index, ref):
"""Replace the reference in the reference list and cache it."""
self._references[index] = ref
self.cache() | [
"def",
"update_local_reference",
"(",
"self",
",",
"index",
",",
"ref",
")",
":",
"self",
".",
"_references",
"[",
"index",
"]",
"=",
"ref",
"self",
".",
"cache",
"(",
")"
] | 43.25 | 7 |
def associa_equipamento(self, id_equip, id_grupo_equipamento):
"""Associa um equipamento a um grupo.
:param id_equip: Identificador do equipamento.
:param id_grupo_equipamento: Identificador do grupo de equipamento.
:return: Dicionário com a seguinte estrutura:
{'equipament... | [
"def",
"associa_equipamento",
"(",
"self",
",",
"id_equip",
",",
"id_grupo_equipamento",
")",
":",
"equip_map",
"=",
"dict",
"(",
")",
"equip_map",
"[",
"'id_grupo'",
"]",
"=",
"id_grupo_equipamento",
"equip_map",
"[",
"'id_equipamento'",
"]",
"=",
"id_equip",
"... | 45.88 | 27.88 |
def parse_line(self, line):
"""Parse VCF header ``line`` (trailing '\r\n' or '\n' is ignored)
:param str line: ``str`` with line to parse
:param dict sub_parsers: ``dict`` mapping header line types to
appropriate parser objects
:returns: appropriate :py:class:`HeaderLine` pa... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"if",
"not",
"line",
"or",
"not",
"line",
".",
"startswith",
"(",
"\"##\"",
")",
":",
"raise",
"exceptions",
".",
"InvalidHeaderException",
"(",
"'Invalid VCF header line (must start with \"##\") {}'",
".",
... | 48.347826 | 19.043478 |
def msg(self, *args, **kwargs):
"Only execute callback when interval is reached."
if self.timestamp is None or self._interval_reached():
self.callback(*args, **kwargs)
self.reset() | [
"def",
"msg",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"timestamp",
"is",
"None",
"or",
"self",
".",
"_interval_reached",
"(",
")",
":",
"self",
".",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs... | 43.2 | 13.2 |
def _create_default_config_file(self):
"""
If config file does not exists create and set default values.
"""
logger.info('Initialize Maya launcher, creating config file...\n')
self.add_section(self.DEFAULTS)
self.add_section(self.PATTERNS)
self.add_section(... | [
"def",
"_create_default_config_file",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Initialize Maya launcher, creating config file...\\n'",
")",
"self",
".",
"add_section",
"(",
"self",
".",
"DEFAULTS",
")",
"self",
".",
"add_section",
"(",
"self",
".",
"PA... | 44.304348 | 17.26087 |
def parse_block_scalar_indent(token_class):
"""Process indentation spaces in a block scalar."""
def callback(lexer, match, context):
text = match.group()
if context.block_scalar_indent is None:
if len(text) <= max(context.indent, 0):
context.st... | [
"def",
"parse_block_scalar_indent",
"(",
"token_class",
")",
":",
"def",
"callback",
"(",
"lexer",
",",
"match",
",",
"context",
")",
":",
"text",
"=",
"match",
".",
"group",
"(",
")",
"if",
"context",
".",
"block_scalar_indent",
"is",
"None",
":",
"if",
... | 40.052632 | 9.578947 |
def save(self, path, group=None, ifo='P1'):
"""
Save frequency series to a Numpy .npy, hdf, or text file. The first column
contains the sample frequencies, the second contains the values.
In the case of a complex frequency series saved as text, the imaginary
part is written as a ... | [
"def",
"save",
"(",
"self",
",",
"path",
",",
"group",
"=",
"None",
",",
"ifo",
"=",
"'P1'",
")",
":",
"ext",
"=",
"_os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"[",
"1",
"]",
"if",
"ext",
"==",
"'.npy'",
":",
"output",
"=",
"_numpy",
... | 43.546875 | 19.046875 |
def input(name, default=None, foreach=None):
"""Decorator to declare input for a node.
Plain inputs, that is plain python objects, are directly passed to
the node. Whereas streams generated by other nodes are requested
and once the handles of all input streams are available the node
is instantiated... | [
"def",
"input",
"(",
"name",
",",
"default",
"=",
"None",
",",
"foreach",
"=",
"None",
")",
":",
"assert",
"default",
"is",
"None",
"or",
"foreach",
"is",
"None",
"value",
"=",
"foreach",
"if",
"foreach",
"is",
"not",
"None",
"else",
"default",
"value"... | 38.142857 | 19.285714 |
def sndwrite_like(samples:np.ndarray, likefile:str, outfile:str) -> None:
"""
Write samples to outfile with samplerate and encoding
taken from likefile
"""
info = sndinfo(likefile)
sndwrite(samples, info.samplerate, outfile, encoding=info.encoding) | [
"def",
"sndwrite_like",
"(",
"samples",
":",
"np",
".",
"ndarray",
",",
"likefile",
":",
"str",
",",
"outfile",
":",
"str",
")",
"->",
"None",
":",
"info",
"=",
"sndinfo",
"(",
"likefile",
")",
"sndwrite",
"(",
"samples",
",",
"info",
".",
"samplerate"... | 38 | 15.714286 |
def _unicode(self):
'''This returns a printable representation of the screen as a unicode
string (which, under Python 3.x, is the same as 'str'). The end of each
screen line is terminated by a newline.'''
return u'\n'.join ([ u''.join(c) for c in self.w ]) | [
"def",
"_unicode",
"(",
"self",
")",
":",
"return",
"u'\\n'",
".",
"join",
"(",
"[",
"u''",
".",
"join",
"(",
"c",
")",
"for",
"c",
"in",
"self",
".",
"w",
"]",
")"
] | 47.333333 | 27.666667 |
def convert(self, line=None, is_end=True):
"""Read the line content and return the converted value
:param line: the line to feed to converter
:param is_end: if set to True, will raise an error if
the line has something remaining.
"""
if line is not None:
self... | [
"def",
"convert",
"(",
"self",
",",
"line",
"=",
"None",
",",
"is_end",
"=",
"True",
")",
":",
"if",
"line",
"is",
"not",
"None",
":",
"self",
".",
"line",
"=",
"line",
"if",
"not",
"self",
".",
"line",
":",
"raise",
"TomlDecodeError",
"(",
"self",... | 39.25 | 13.464286 |
def maybeDeferred(f, *args, **kw):
"""
Copied from twsited.internet.defer and add a check to detect fibers.
"""
try:
result = f(*args, **kw)
except Exception:
return fail(failure.Failure())
if IFiber.providedBy(result):
import traceback
frames = traceback.extract... | [
"def",
"maybeDeferred",
"(",
"f",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"result",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"except",
"Exception",
":",
"return",
"fail",
"(",
"failure",
".",
"Failure",
"(",
")... | 28.782609 | 15.130435 |
def fcoe_fcoe_fabric_map_fcoe_fcf_map_fcf_map_fif_rbid_fcf_map_fif_rbid_add(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe")
fcoe_fabric_map = ET.SubElement(fcoe, "fcoe-fabric... | [
"def",
"fcoe_fcoe_fabric_map_fcoe_fcf_map_fcf_map_fif_rbid_fcf_map_fif_rbid_add",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"fcoe",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"fcoe\"",
"... | 58.764706 | 27.176471 |
def sign_message(message, wif, hashfn=hashlib.sha256):
""" Sign a digest with a wif key
:param str wif: Private key in
"""
if not isinstance(message, bytes):
message = bytes(message, "utf-8")
digest = hashfn(message).digest()
priv_key = PrivateKey(wif)
p = bytes(priv_key)
... | [
"def",
"sign_message",
"(",
"message",
",",
"wif",
",",
"hashfn",
"=",
"hashlib",
".",
"sha256",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"bytes",
")",
":",
"message",
"=",
"bytes",
"(",
"message",
",",
"\"utf-8\"",
")",
"digest",
"=",... | 34.726496 | 17.811966 |
def main():
"""Run playbook"""
for flag in ('--check',):
if flag not in sys.argv:
sys.argv.append(flag)
obj = PlaybookCLI(sys.argv)
obj.parse()
obj.run() | [
"def",
"main",
"(",
")",
":",
"for",
"flag",
"in",
"(",
"'--check'",
",",
")",
":",
"if",
"flag",
"not",
"in",
"sys",
".",
"argv",
":",
"sys",
".",
"argv",
".",
"append",
"(",
"flag",
")",
"obj",
"=",
"PlaybookCLI",
"(",
"sys",
".",
"argv",
")"... | 23.25 | 14.5 |
def set(self, channel, state):
"""Set DAC value and enable output"""
checked_val = self._check_dac_val(channel, state)
self._dac_enabled = 0x40
self.i2c.write8(self._dac_enabled, checked_val * 255) | [
"def",
"set",
"(",
"self",
",",
"channel",
",",
"state",
")",
":",
"checked_val",
"=",
"self",
".",
"_check_dac_val",
"(",
"channel",
",",
"state",
")",
"self",
".",
"_dac_enabled",
"=",
"0x40",
"self",
".",
"i2c",
".",
"write8",
"(",
"self",
".",
"_... | 45 | 11.2 |
def OnClose(self, event):
"""Program exit event handler"""
# If changes have taken place save of old grid
if undo.stack().haschanged():
save_choice = self.interfaces.get_save_request_from_user()
if save_choice is None:
# Cancelled close operation
... | [
"def",
"OnClose",
"(",
"self",
",",
"event",
")",
":",
"# If changes have taken place save of old grid",
"if",
"undo",
".",
"stack",
"(",
")",
".",
"haschanged",
"(",
")",
":",
"save_choice",
"=",
"self",
".",
"interfaces",
".",
"get_save_request_from_user",
"("... | 28.175 | 21.875 |
def get_brokers(self):
"""
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects.
"""
return ['{}:{}'.format(parsedUrl.hostname, parsedUrl.port) for parsedUrl in
[urlparse(url) for url in self.kafka_url.split(',')]] | [
"def",
"get_brokers",
"(",
"self",
")",
":",
"return",
"[",
"'{}:{}'",
".",
"format",
"(",
"parsedUrl",
".",
"hostname",
",",
"parsedUrl",
".",
"port",
")",
"for",
"parsedUrl",
"in",
"[",
"urlparse",
"(",
"url",
")",
"for",
"url",
"in",
"self",
".",
... | 44.857143 | 20 |
def getFontName(self, names, default="helvetica"):
"""
Name of a font
"""
# print names, self.fontList
if type(names) is not ListType:
if type(names) not in six.string_types:
names = str(names)
names = names.strip().split(",")
for n... | [
"def",
"getFontName",
"(",
"self",
",",
"names",
",",
"default",
"=",
"\"helvetica\"",
")",
":",
"# print names, self.fontList",
"if",
"type",
"(",
"names",
")",
"is",
"not",
"ListType",
":",
"if",
"type",
"(",
"names",
")",
"not",
"in",
"six",
".",
"str... | 36 | 8.625 |
def construct_result_generator_middleware(result_generators):
"""
Constructs a middleware which intercepts requests for any method found in
the provided mapping of endpoints to generator functions, returning
whatever response the generator function returns. Callbacks must be
functions with the sign... | [
"def",
"construct_result_generator_middleware",
"(",
"result_generators",
")",
":",
"def",
"result_generator_middleware",
"(",
"make_request",
",",
"web3",
")",
":",
"def",
"middleware",
"(",
"method",
",",
"params",
")",
":",
"if",
"method",
"in",
"result_generator... | 45.3125 | 14.5625 |
def uniq(seq):
""" Return a copy of seq without duplicates. """
seen = set()
return [x for x in seq if str(x) not in seen and not seen.add(str(x))] | [
"def",
"uniq",
"(",
"seq",
")",
":",
"seen",
"=",
"set",
"(",
")",
"return",
"[",
"x",
"for",
"x",
"in",
"seq",
"if",
"str",
"(",
"x",
")",
"not",
"in",
"seen",
"and",
"not",
"seen",
".",
"add",
"(",
"str",
"(",
"x",
")",
")",
"]"
] | 39.75 | 20.5 |
def replication_state(self, repl_id):
"""
Retrieves the state for the given replication. Possible values are
``triggered``, ``completed``, ``error``, and ``None`` (meaning not yet
triggered).
:param str repl_id: Replication id used to identify the replication to
insp... | [
"def",
"replication_state",
"(",
"self",
",",
"repl_id",
")",
":",
"if",
"\"scheduler\"",
"in",
"self",
".",
"client",
".",
"features",
"(",
")",
":",
"try",
":",
"repl_doc",
"=",
"Scheduler",
"(",
"self",
".",
"client",
")",
".",
"get_doc",
"(",
"repl... | 37.4 | 19.72 |
def deserialize(cls, cls_target, obj_raw):
"""
:type cls_target: T|type
:type obj_raw: int|str|bool|float|list|dict|None
:rtype: T
"""
cls._initialize()
deserializer = cls._get_deserializer(cls_target)
if deserializer == cls:
return cls._des... | [
"def",
"deserialize",
"(",
"cls",
",",
"cls_target",
",",
"obj_raw",
")",
":",
"cls",
".",
"_initialize",
"(",
")",
"deserializer",
"=",
"cls",
".",
"_get_deserializer",
"(",
"cls_target",
")",
"if",
"deserializer",
"==",
"cls",
":",
"return",
"cls",
".",
... | 28.133333 | 18.933333 |
def _getPrototypes(indices, overlaps, topNumber=1):
"""
Given a compressed overlap array and a set of indices specifying a subset
of those in that array, return the set of topNumber indices of vectors that
have maximum average overlap with other vectors in `indices`.
@param indices (arraylike) Arra... | [
"def",
"_getPrototypes",
"(",
"indices",
",",
"overlaps",
",",
"topNumber",
"=",
"1",
")",
":",
"# find the number of data points based on the length of the overlap array",
"# solves for n: len(overlaps) = n(n-1)/2",
"n",
"=",
"numpy",
".",
"roots",
"(",
"[",
"1",
",",
... | 36.394737 | 21.078947 |
def _construct_category(glyph_name, data):
"""Derive (sub)category of a glyph name."""
# Glyphs creates glyphs that start with an underscore as "non-exportable" glyphs or
# construction helpers without a category.
if glyph_name.startswith("_"):
return None, None
# Glyph variants (e.g. "fi.a... | [
"def",
"_construct_category",
"(",
"glyph_name",
",",
"data",
")",
":",
"# Glyphs creates glyphs that start with an underscore as \"non-exportable\" glyphs or",
"# construction helpers without a category.",
"if",
"glyph_name",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"return",
... | 44.683333 | 20.6 |
def save(self):
"""
If an id exists in the database, we assume we'll update it, and if not
then we'll insert it. This could be a problem with creating your own
id's on new objects, however luckily, we keep track of if this is a new
object through a private _new variable, and use ... | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_new",
":",
"data",
"=",
"self",
".",
"_data",
".",
"copy",
"(",
")",
"ID",
"=",
"data",
".",
"pop",
"(",
"self",
".",
"primaryKey",
")",
"reply",
"=",
"r",
".",
"table",
"(",
"... | 37.848485 | 18.393939 |
def getTextualNode(self, subreference=None):
""" Retrieve a passage and store it in the object
:param subreference: CtsReference of the passage (Note : if given a list, this should be a list of string that \
compose the reference)
:type subreference: Union[CtsReference, URN, str, list]
... | [
"def",
"getTextualNode",
"(",
"self",
",",
"subreference",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"subreference",
",",
"URN",
")",
":",
"urn",
"=",
"str",
"(",
"subreference",
")",
"elif",
"isinstance",
"(",
"subreference",
",",
"CtsReference",
")... | 45.285714 | 21.357143 |
def is_permanent_redirect(self):
"""True if this Response one of the permanent versions of redirect."""
return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect)) | [
"def",
"is_permanent_redirect",
"(",
"self",
")",
":",
"return",
"(",
"'location'",
"in",
"self",
".",
"headers",
"and",
"self",
".",
"status_code",
"in",
"(",
"codes",
".",
"moved_permanently",
",",
"codes",
".",
"permanent_redirect",
")",
")"
] | 76.333333 | 29 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.