text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def anonymous_copy(self):
"""Yield an anonymous, otherwise equally-configured copy of an Instaloader instance; Then copy its error log."""
new_loader = Instaloader(self.context.sleep, self.context.quiet, self.context.user_agent, self.dirname_pattern,
self.filename_patter... | [
"def",
"anonymous_copy",
"(",
"self",
")",
":",
"new_loader",
"=",
"Instaloader",
"(",
"self",
".",
"context",
".",
"sleep",
",",
"self",
".",
"context",
".",
"quiet",
",",
"self",
".",
"context",
".",
"user_agent",
",",
"self",
".",
"dirname_pattern",
"... | 80.8 | 0.008972 |
def _get_mount_methods(self, disk_type):
"""Finds which mount methods are suitable for the specified disk type. Returns a list of all suitable mount
methods.
"""
if self.disk_mounter == 'auto':
methods = []
def add_method_if_exists(method):
if (me... | [
"def",
"_get_mount_methods",
"(",
"self",
",",
"disk_type",
")",
":",
"if",
"self",
".",
"disk_mounter",
"==",
"'auto'",
":",
"methods",
"=",
"[",
"]",
"def",
"add_method_if_exists",
"(",
"method",
")",
":",
"if",
"(",
"method",
"==",
"'avfs'",
"and",
"_... | 40.21875 | 0.002276 |
def get_intel_notifications_feed(self, page=None, timeout=None):
""" Get notification feed in JSON for further processing.
:param page: the next_page property of the results of a previously issued query to this API. This parameter
should not be provided if it is the very first query to the ... | [
"def",
"get_intel_notifications_feed",
"(",
"self",
",",
"page",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'next'",
":",
"page",
"}",
"try",
":",
"response",
"=",
"requests",
... | 60.4 | 0.005867 |
def log_metrics(metrics, summ_writer, log_prefix, step, history=None):
"""Log metrics to summary writer and history."""
rjust_len = max([len(name) for name in metrics])
for name, value in six.iteritems(metrics):
step_log(step, "%s %s | % .8f" % (
log_prefix.ljust(5), name.rjust(rjust_len), value))
... | [
"def",
"log_metrics",
"(",
"metrics",
",",
"summ_writer",
",",
"log_prefix",
",",
"step",
",",
"history",
"=",
"None",
")",
":",
"rjust_len",
"=",
"max",
"(",
"[",
"len",
"(",
"name",
")",
"for",
"name",
"in",
"metrics",
"]",
")",
"for",
"name",
",",... | 43.818182 | 0.012195 |
def _ImportModuleHookBySuffix(name, package=None):
"""Callback when a module is imported through importlib.import_module."""
_IncrementNestLevel()
try:
# Really import modules.
module = _real_import_module(name, package)
finally:
if name.startswith('.'):
if package:
name = _ResolveRel... | [
"def",
"_ImportModuleHookBySuffix",
"(",
"name",
",",
"package",
"=",
"None",
")",
":",
"_IncrementNestLevel",
"(",
")",
"try",
":",
"# Really import modules.",
"module",
"=",
"_real_import_module",
"(",
"name",
",",
"package",
")",
"finally",
":",
"if",
"name",... | 28.555556 | 0.016949 |
def _enum_from_direction(direction):
"""Convert a string representation of a direction to an enum.
Args:
direction (str): A direction to order by. Must be one of
:attr:`~.firestore.Query.ASCENDING` or
:attr:`~.firestore.Query.DESCENDING`.
Returns:
int: The enum corr... | [
"def",
"_enum_from_direction",
"(",
"direction",
")",
":",
"if",
"isinstance",
"(",
"direction",
",",
"int",
")",
":",
"return",
"direction",
"if",
"direction",
"==",
"Query",
".",
"ASCENDING",
":",
"return",
"enums",
".",
"StructuredQuery",
".",
"Direction",
... | 32.666667 | 0.002478 |
def _compute_small_mag_correction_term(C, mag, rhypo):
"""
small magnitude correction applied to the median values
"""
if mag >= 3.00 and mag < 5.5:
min_term = np.minimum(rhypo, C['Rm'])
max_term = np.maximum(min_term, 10)
term_ln = np.log(max_term / 20)
term_ratio = ((5.... | [
"def",
"_compute_small_mag_correction_term",
"(",
"C",
",",
"mag",
",",
"rhypo",
")",
":",
"if",
"mag",
">=",
"3.00",
"and",
"mag",
"<",
"5.5",
":",
"min_term",
"=",
"np",
".",
"minimum",
"(",
"rhypo",
",",
"C",
"[",
"'Rm'",
"]",
")",
"max_term",
"="... | 35.230769 | 0.002128 |
def ensure_on():
"""
Start the DbServer if it is off
"""
if get_status() == 'not-running':
if config.dbserver.multi_user:
sys.exit('Please start the DbServer: '
'see the documentation for details')
# otherwise start the DbServer automatically; NB: I tried... | [
"def",
"ensure_on",
"(",
")",
":",
"if",
"get_status",
"(",
")",
"==",
"'not-running'",
":",
"if",
"config",
".",
"dbserver",
".",
"multi_user",
":",
"sys",
".",
"exit",
"(",
"'Please start the DbServer: '",
"'see the documentation for details'",
")",
"# otherwise... | 43.434783 | 0.000979 |
def _show_annotation_box(self, event):
"""Update an existing box or create an annotation box for an event."""
ax = event.artist.axes
# Get the pre-created annotation box for the axes or create a new one.
if self.display != 'multiple':
annotation = self.annotations[ax]
... | [
"def",
"_show_annotation_box",
"(",
"self",
",",
"event",
")",
":",
"ax",
"=",
"event",
".",
"artist",
".",
"axes",
"# Get the pre-created annotation box for the axes or create a new one.",
"if",
"self",
".",
"display",
"!=",
"'multiple'",
":",
"annotation",
"=",
"s... | 44.4 | 0.002205 |
def initialize_pop(self):
"""Generates the initial population and assigns fitnesses."""
self.initialize_cma_es(
sigma=self._params['sigma'], weights=self._params['weights'],
lambda_=self._params['popsize'],
centroid=[0] * len(self._params['value_means']))
self... | [
"def",
"initialize_pop",
"(",
"self",
")",
":",
"self",
".",
"initialize_cma_es",
"(",
"sigma",
"=",
"self",
".",
"_params",
"[",
"'sigma'",
"]",
",",
"weights",
"=",
"self",
".",
"_params",
"[",
"'weights'",
"]",
",",
"lambda_",
"=",
"self",
".",
"_pa... | 55.4 | 0.002367 |
def _set_arp_entry(self, v, load=False):
"""
Setter method for arp_entry, mapped from YANG variable /rbridge_id/arp_entry (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_arp_entry is considered as a private
method. Backends looking to populate this variable sh... | [
"def",
"_set_arp_entry",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base... | 131.772727 | 0.003767 |
def remove_negative_entries(A):
r"""Remove all negative entries from sparse matrix.
Aplus=max(0, A)
Parameters
----------
A : (M, M) scipy.sparse matrix
Input matrix
Returns
-------
Aplus : (M, M) scipy.sparse matrix
Input matrix with negative entries set to zero.
... | [
"def",
"remove_negative_entries",
"(",
"A",
")",
":",
"A",
"=",
"A",
".",
"tocoo",
"(",
")",
"data",
"=",
"A",
".",
"data",
"row",
"=",
"A",
".",
"row",
"col",
"=",
"A",
".",
"col",
"\"\"\"Positive entries\"\"\"",
"pos",
"=",
"data",
">",
"0.0",
"d... | 18 | 0.001701 |
def powerUp(self):
"""power up the Thread device"""
print '%s call powerUp' % self.port
if not self.handle:
self._connect()
self.isPowerDown = False
if self.__sendCommand(WPANCTL_CMD + 'attach')[0] != 'Fail':
time.sleep(3)
else:
return... | [
"def",
"powerUp",
"(",
"self",
")",
":",
"print",
"'%s call powerUp'",
"%",
"self",
".",
"port",
"if",
"not",
"self",
".",
"handle",
":",
"self",
".",
"_connect",
"(",
")",
"self",
".",
"isPowerDown",
"=",
"False",
"if",
"self",
".",
"__sendCommand",
"... | 32.2 | 0.006033 |
def deserialize(self, xml_input, *args, **kwargs):
"""
Convert XML to dict object
"""
return xmltodict.parse(xml_input, *args, **kwargs) | [
"def",
"deserialize",
"(",
"self",
",",
"xml_input",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"xmltodict",
".",
"parse",
"(",
"xml_input",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 32.8 | 0.011905 |
def best_practice(app_configs, **kwargs):
"""
Test for configuration recommendations. These are best practices, they
avoid hard to find bugs and unexpected behaviour.
"""
if app_configs is None:
app_configs = apps.get_app_configs()
# Take the app_configs and turn them into *old style* a... | [
"def",
"best_practice",
"(",
"app_configs",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"app_configs",
"is",
"None",
":",
"app_configs",
"=",
"apps",
".",
"get_app_configs",
"(",
")",
"# Take the app_configs and turn them into *old style* application names.",
"# This is wh... | 40.285714 | 0.001065 |
def export_kml_file(self):
"""Generate KML element tree from ``Placemarks``.
Returns:
etree.ElementTree: KML element tree depicting ``Placemarks``
"""
kml = create_elem('kml')
kml.Document = create_elem('Document')
for place in sorted(self.values(), key=lambd... | [
"def",
"export_kml_file",
"(",
"self",
")",
":",
"kml",
"=",
"create_elem",
"(",
"'kml'",
")",
"kml",
".",
"Document",
"=",
"create_elem",
"(",
"'Document'",
")",
"for",
"place",
"in",
"sorted",
"(",
"self",
".",
"values",
"(",
")",
",",
"key",
"=",
... | 34 | 0.004773 |
def urlpatterns(self):
'''load and decorate urls from all modules
then store it as cached property for less loading
'''
if not hasattr(self, '_urlspatterns'):
urlpatterns = []
# load all urls
# support .urls file and urls_conf = 'elephantblog.urls' on ... | [
"def",
"urlpatterns",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_urlspatterns'",
")",
":",
"urlpatterns",
"=",
"[",
"]",
"# load all urls",
"# support .urls file and urls_conf = 'elephantblog.urls' on default module",
"# decorate all url patterns if... | 43.88 | 0.001783 |
def srs_check(ds):
"""Check validitiy of Dataset srs
Return True if srs is properly defined
"""
# ds_srs = get_ds_srs(ds)
gt = np.array(ds.GetGeoTransform())
gt_check = ~np.all(gt == np.array((0.0, 1.0, 0.0, 0.0, 0.0, 1.0)))
proj_check = (ds.GetProjection() != '')
#proj_check = ds_srs.I... | [
"def",
"srs_check",
"(",
"ds",
")",
":",
"# ds_srs = get_ds_srs(ds)",
"gt",
"=",
"np",
".",
"array",
"(",
"ds",
".",
"GetGeoTransform",
"(",
")",
")",
"gt_check",
"=",
"~",
"np",
".",
"all",
"(",
"gt",
"==",
"np",
".",
"array",
"(",
"(",
"0.0",
","... | 28.785714 | 0.007212 |
def charts_slug_get(self, slug, **kwargs):
"""
Chart
A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster ... | [
"def",
"charts_slug_get",
"(",
"self",
",",
"slug",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"charts_slug_get_with_http_inf... | 50.076923 | 0.003014 |
def get_service(self, service_name):
"""
Given the name of a registered service, return its service definition.
"""
service = self.services.get(service_name)
if not service:
raise KeyError('Service not registered: %s' % service_name)
return service | [
"def",
"get_service",
"(",
"self",
",",
"service_name",
")",
":",
"service",
"=",
"self",
".",
"services",
".",
"get",
"(",
"service_name",
")",
"if",
"not",
"service",
":",
"raise",
"KeyError",
"(",
"'Service not registered: %s'",
"%",
"service_name",
")",
... | 37.625 | 0.006494 |
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False,
target=None, rel=None):
"""Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow... | [
"def",
"do_urlize",
"(",
"eval_ctx",
",",
"value",
",",
"trim_url_limit",
"=",
"None",
",",
"nofollow",
"=",
"False",
",",
"target",
"=",
"None",
",",
"rel",
"=",
"None",
")",
":",
"policies",
"=",
"eval_ctx",
".",
"environment",
".",
"policies",
"rel",
... | 31.428571 | 0.000882 |
def model_alias(vk, model):
"""Fill the model with alias since V1"""
model['alias'] = {}
# types
for s in vk['registry']['types']['type']:
if s.get('@category', None) == 'handle' and s.get('@alias'):
model['alias'][s['@alias']] = s['@name']
# commands
for c i... | [
"def",
"model_alias",
"(",
"vk",
",",
"model",
")",
":",
"model",
"[",
"'alias'",
"]",
"=",
"{",
"}",
"# types",
"for",
"s",
"in",
"vk",
"[",
"'registry'",
"]",
"[",
"'types'",
"]",
"[",
"'type'",
"]",
":",
"if",
"s",
".",
"get",
"(",
"'@category... | 33 | 0.006803 |
def get(self, addr, count):
"""
Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside va... | [
"def",
"get",
"(",
"self",
",",
"addr",
",",
"count",
")",
":",
"addr",
"-=",
"self",
".",
"_start_addr",
"data",
"=",
"self",
".",
"_data",
"[",
"addr",
":",
"addr",
"+",
"count",
"]",
"if",
"len",
"(",
"data",
")",
"!=",
"count",
":",
"addr",
... | 38.9375 | 0.003135 |
def is_ignored(self, options):
"""
If we have changed children and all the children which are changes
are ignored, then we are ignored. Otherwise, we are not
ignored
"""
if not self.is_change():
return False
changes = self.collect()
if not ch... | [
"def",
"is_ignored",
"(",
"self",
",",
"options",
")",
":",
"if",
"not",
"self",
".",
"is_change",
"(",
")",
":",
"return",
"False",
"changes",
"=",
"self",
".",
"collect",
"(",
")",
"if",
"not",
"changes",
":",
"return",
"False",
"for",
"change",
"i... | 26.944444 | 0.003984 |
def _finish_selecting(self, event):
"""Finaliza la seleccion.
Marca como seleccionados todos los objetos que se encuentran
dentro del recuadro de seleccion."""
self._selecting = False
canvas = self._canvas
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
... | [
"def",
"_finish_selecting",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"_selecting",
"=",
"False",
"canvas",
"=",
"self",
".",
"_canvas",
"x",
"=",
"canvas",
".",
"canvasx",
"(",
"event",
".",
"x",
")",
"y",
"=",
"canvas",
".",
"canvasy",
"(",... | 38.866667 | 0.005025 |
def previous(self, field):
"""Returns currently saved value of given field"""
# handle deferred fields that have not yet been loaded from the database
if self.instance.pk and field in self.deferred_fields and field not in self.saved_data:
# if the field has not been assigned locall... | [
"def",
"previous",
"(",
"self",
",",
"field",
")",
":",
"# handle deferred fields that have not yet been loaded from the database",
"if",
"self",
".",
"instance",
".",
"pk",
"and",
"field",
"in",
"self",
".",
"deferred_fields",
"and",
"field",
"not",
"in",
"self",
... | 50.368421 | 0.006154 |
def contains_rva(self, rva):
"""Check whether the section contains the address provided."""
# Check if the SizeOfRawData is realistic. If it's bigger than the size of
# the whole PE file minus the start address of the section it could be
# either truncated or the SizeOfRawData contains ... | [
"def",
"contains_rva",
"(",
"self",
",",
"rva",
")",
":",
"# Check if the SizeOfRawData is realistic. If it's bigger than the size of",
"# the whole PE file minus the start address of the section it could be",
"# either truncated or the SizeOfRawData contains a misleading value.",
"# In either... | 55.71875 | 0.011025 |
def delete_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Delete a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of t... | [
"def",
"delete_relationship",
"(",
"self",
",",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_delete_relationship",
"(",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_k... | 41.44898 | 0.005291 |
def create_unique_wcsname(fimg, extnum, wcsname):
"""
This function evaluates whether the specified wcsname value has
already been used in this image. If so, it automatically modifies
the name with a simple version ID using wcsname_NNN format.
Parameters
----------
fimg : obj
PyFIT... | [
"def",
"create_unique_wcsname",
"(",
"fimg",
",",
"extnum",
",",
"wcsname",
")",
":",
"wnames",
"=",
"list",
"(",
"wcsutil",
".",
"altwcs",
".",
"wcsnames",
"(",
"fimg",
",",
"ext",
"=",
"extnum",
")",
".",
"values",
"(",
")",
")",
"if",
"wcsname",
"... | 29.025641 | 0.005128 |
def _sync_repo(self, repo_url: str, revision: str or None = None) -> Path:
'''Clone a Git repository to the cache dir. If it has been cloned before, update it.
:param repo_url: Repository URL
:param revision: Revision: branch, commit hash, or tag
:returns: Path to the cloned repository... | [
"def",
"_sync_repo",
"(",
"self",
",",
"repo_url",
":",
"str",
",",
"revision",
":",
"str",
"or",
"None",
"=",
"None",
")",
"->",
"Path",
":",
"repo_name",
"=",
"repo_url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
".",
"rsplit",
"(",
"'... | 30.267857 | 0.002286 |
def write16(self, register, value):
"""Write a 16-bit value to the specified register."""
value = value & 0xFFFF
self._bus.write_word_data(self._address, register, value)
self._logger.debug("Wrote 0x%04X to register pair 0x%02X, 0x%02X",
value, register, register+1) | [
"def",
"write16",
"(",
"self",
",",
"register",
",",
"value",
")",
":",
"value",
"=",
"value",
"&",
"0xFFFF",
"self",
".",
"_bus",
".",
"write_word_data",
"(",
"self",
".",
"_address",
",",
"register",
",",
"value",
")",
"self",
".",
"_logger",
".",
... | 52.333333 | 0.009404 |
def delete_access_list_items(self, loadbalancer, item_ids):
"""
Removes the item(s) from the load balancer's access list
that match the provided IDs. 'item_ids' should be one or
more access list item IDs.
"""
if not isinstance(item_ids, (list, tuple)):
item_id... | [
"def",
"delete_access_list_items",
"(",
"self",
",",
"loadbalancer",
",",
"item_ids",
")",
":",
"if",
"not",
"isinstance",
"(",
"item_ids",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"item_ids",
"=",
"[",
"item_ids",
"]",
"valid_ids",
"=",
"[",
"itm"... | 47.789474 | 0.00324 |
def is_symbols_pair_complete(editor, symbol):
"""
Returns if the symbols pair is complete on current editor line.
:param editor: Document editor.
:type editor: QWidget
:param symbol: Symbol to check.
:type symbol: unicode
:return: Is symbols pair complete.
:rtype: bool
"""
symb... | [
"def",
"is_symbols_pair_complete",
"(",
"editor",
",",
"symbol",
")",
":",
"symbols_pairs",
"=",
"get_editor_capability",
"(",
"editor",
",",
"\"symbols_pairs\"",
")",
"if",
"not",
"symbols_pairs",
":",
"return",
"cursor",
"=",
"editor",
".",
"textCursor",
"(",
... | 34.916667 | 0.002323 |
def decode_list(self, ids):
"""Transform a sequence of int ids into a their string versions.
This method supports transforming individual input/output ids to their
string versions so that sequence to/from text conversions can be visualized
in a human readable format.
Args:
ids: list of integ... | [
"def",
"decode_list",
"(",
"self",
",",
"ids",
")",
":",
"decoded_ids",
"=",
"[",
"]",
"for",
"id_",
"in",
"ids",
":",
"if",
"0",
"<=",
"id_",
"<",
"self",
".",
"_num_reserved_ids",
":",
"decoded_ids",
".",
"append",
"(",
"RESERVED_TOKENS",
"[",
"int",... | 31.75 | 0.004587 |
def flush(self):
"""Flush data that is left in the buffer."""
for data in self.buffer:
self.output_width += data.output(self.output, self.output_width)
self.buffer.clear()
self.buffer_width = 0 | [
"def",
"flush",
"(",
"self",
")",
":",
"for",
"data",
"in",
"self",
".",
"buffer",
":",
"self",
".",
"output_width",
"+=",
"data",
".",
"output",
"(",
"self",
".",
"output",
",",
"self",
".",
"output_width",
")",
"self",
".",
"buffer",
".",
"clear",
... | 38.666667 | 0.008439 |
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
"""
result = None
evl = self.input.payload
pltclassifier.plot_classifier_errors(
evl.predictions,
absolut... | [
"def",
"do_execute",
"(",
"self",
")",
":",
"result",
"=",
"None",
"evl",
"=",
"self",
".",
"input",
".",
"payload",
"pltclassifier",
".",
"plot_classifier_errors",
"(",
"evl",
".",
"predictions",
",",
"absolute",
"=",
"bool",
"(",
"self",
".",
"resolve_op... | 36.833333 | 0.002941 |
def pkginfo_to_metadata(egg_info_path, pkginfo_path):
"""
Convert .egg-info directory with PKG-INFO to the Metadata 2.1 format
"""
pkg_info = read_pkg_info(pkginfo_path)
pkg_info.replace_header('Metadata-Version', '2.1')
requires_path = os.path.join(egg_info_path, 'requires.txt')
if os.path.... | [
"def",
"pkginfo_to_metadata",
"(",
"egg_info_path",
",",
"pkginfo_path",
")",
":",
"pkg_info",
"=",
"read_pkg_info",
"(",
"pkginfo_path",
")",
"pkg_info",
".",
"replace_header",
"(",
"'Metadata-Version'",
",",
"'2.1'",
")",
"requires_path",
"=",
"os",
".",
"path",... | 39.857143 | 0.001167 |
def find_embedding(elt, embedding=None):
"""Try to get elt embedding elements.
:param embedding: embedding element. Must have a module.
:return: a list of [module [,class]*] embedding elements which define elt.
:rtype: list
"""
result = [] # result is empty in the worst case
# start to ... | [
"def",
"find_embedding",
"(",
"elt",
",",
"embedding",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"# result is empty in the worst case",
"# start to get module",
"module",
"=",
"getmodule",
"(",
"elt",
")",
"if",
"module",
"is",
"not",
"None",
":",
"# if ... | 32.03125 | 0.000473 |
def _heappop_max(heap):
"""Maxheap version of a heappop."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup_max(heap, 0)
return returnitem
return lastelt | [
"def",
"_heappop_max",
"(",
"heap",
")",
":",
"lastelt",
"=",
"heap",
".",
"pop",
"(",
")",
"# raises appropriate IndexError if heap is empty",
"if",
"heap",
":",
"returnitem",
"=",
"heap",
"[",
"0",
"]",
"heap",
"[",
"0",
"]",
"=",
"lastelt",
"_siftup_max",... | 30.444444 | 0.003546 |
def main():
rollbar.init('ACCESS_TOKEN', environment='test', handler='twisted')
"""This runs the protocol on port 8000"""
factory = protocol.ServerFactory()
factory.protocol = Echo
reactor.listenTCP(8000, factory)
reactor.run() | [
"def",
"main",
"(",
")",
":",
"rollbar",
".",
"init",
"(",
"'ACCESS_TOKEN'",
",",
"environment",
"=",
"'test'",
",",
"handler",
"=",
"'twisted'",
")",
"factory",
"=",
"protocol",
".",
"ServerFactory",
"(",
")",
"factory",
".",
"protocol",
"=",
"Echo",
"r... | 30.625 | 0.003968 |
def coverage():
"generate coverage report and show in browser"
coverage_index = path("build/coverage/index.html")
coverage_index.remove()
sh("paver test")
coverage_index.exists() and webbrowser.open(coverage_index) | [
"def",
"coverage",
"(",
")",
":",
"coverage_index",
"=",
"path",
"(",
"\"build/coverage/index.html\"",
")",
"coverage_index",
".",
"remove",
"(",
")",
"sh",
"(",
"\"paver test\"",
")",
"coverage_index",
".",
"exists",
"(",
")",
"and",
"webbrowser",
".",
"open"... | 38.166667 | 0.004274 |
def create(self, environment, target_name):
"""
Sends "create project" command to the remote server
"""
remote_server_command(
["ssh", environment.deploy_target, "create", target_name],
environment, self,
clean_up=True,
) | [
"def",
"create",
"(",
"self",
",",
"environment",
",",
"target_name",
")",
":",
"remote_server_command",
"(",
"[",
"\"ssh\"",
",",
"environment",
".",
"deploy_target",
",",
"\"create\"",
",",
"target_name",
"]",
",",
"environment",
",",
"self",
",",
"clean_up"... | 32.555556 | 0.006645 |
def _get_perez_coefficients(perezmodel):
'''
Find coefficients for the Perez model
Parameters
----------
perezmodel : string (optional, default='allsitescomposite1990')
a character string which selects the desired set of Perez
coefficients. If model is not provided as an input... | [
"def",
"_get_perez_coefficients",
"(",
"perezmodel",
")",
":",
"coeffdict",
"=",
"{",
"'allsitescomposite1990'",
":",
"[",
"[",
"-",
"0.0080",
",",
"0.5880",
",",
"-",
"0.0620",
",",
"-",
"0.0600",
",",
"0.0720",
",",
"-",
"0.0220",
"]",
",",
"[",
"0.130... | 54.822785 | 0.000113 |
def get_ports(self, scan_id, target):
""" Get a scan's ports list. If a target is specified
it will return the corresponding port for it. If not,
it returns the port item of the first nested list in
the target's list.
"""
if target:
for item in self.scans_tabl... | [
"def",
"get_ports",
"(",
"self",
",",
"scan_id",
",",
"target",
")",
":",
"if",
"target",
":",
"for",
"item",
"in",
"self",
".",
"scans_table",
"[",
"scan_id",
"]",
"[",
"'targets'",
"]",
":",
"if",
"target",
"==",
"item",
"[",
"0",
"]",
":",
"retu... | 38.583333 | 0.004219 |
def minibatch(items, size=8):
"""Iterate over batches of items. `size` may be an iterator,
so that batch-size can vary on each step.
"""
if isinstance(size, int):
size_ = itertools.repeat(size)
else:
size_ = size
items = iter(items)
while True:
batch_size = next(size_... | [
"def",
"minibatch",
"(",
"items",
",",
"size",
"=",
"8",
")",
":",
"if",
"isinstance",
"(",
"size",
",",
"int",
")",
":",
"size_",
"=",
"itertools",
".",
"repeat",
"(",
"size",
")",
"else",
":",
"size_",
"=",
"size",
"items",
"=",
"iter",
"(",
"i... | 29.466667 | 0.002193 |
def findOODWords(isleDict, wordList):
'''
Returns all of the out-of-dictionary words found in a list of utterances
'''
oodList = []
for word in wordList:
try:
isleDict.lookup(word)
except WordNotInISLE:
oodList.append(word)
oodList = list(... | [
"def",
"findOODWords",
"(",
"isleDict",
",",
"wordList",
")",
":",
"oodList",
"=",
"[",
"]",
"for",
"word",
"in",
"wordList",
":",
"try",
":",
"isleDict",
".",
"lookup",
"(",
"word",
")",
"except",
"WordNotInISLE",
":",
"oodList",
".",
"append",
"(",
"... | 24.133333 | 0.007979 |
def asArcPyObject(self):
""" returns the Envelope as an ESRI arcpy.Polygon object """
env = self.asDictionary
ring = [[
Point(env['xmin'], env['ymin'], self._wkid),
Point(env['xmax'], env['ymin'], self._wkid),
Point(env['xmax'], env['ymax'], self._wkid),
... | [
"def",
"asArcPyObject",
"(",
"self",
")",
":",
"env",
"=",
"self",
".",
"asDictionary",
"ring",
"=",
"[",
"[",
"Point",
"(",
"env",
"[",
"'xmin'",
"]",
",",
"env",
"[",
"'ymin'",
"]",
",",
"self",
".",
"_wkid",
")",
",",
"Point",
"(",
"env",
"[",... | 40.714286 | 0.003431 |
def sxform(instring, tostring, et):
"""
Return the state transformation matrix from one frame to
another at a specified epoch.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sxform_c.html
:param instring: Name of the frame to transform from.
:type instring: str
:param tostring: N... | [
"def",
"sxform",
"(",
"instring",
",",
"tostring",
",",
"et",
")",
":",
"instring",
"=",
"stypes",
".",
"stringToCharP",
"(",
"instring",
")",
"tostring",
"=",
"stypes",
".",
"stringToCharP",
"(",
"tostring",
")",
"xform",
"=",
"stypes",
".",
"emptyDoubleM... | 35.064516 | 0.000895 |
def configure_logging(conf):
"""Initialize and configure logging."""
root_logger = logging.getLogger()
root_logger.setLevel(getattr(logging, conf.loglevel.upper()))
if conf.logtostderr:
add_stream_handler(root_logger, sys.stderr)
if conf.logtostdout:
add_stream_handler(root_logger, s... | [
"def",
"configure_logging",
"(",
"conf",
")",
":",
"root_logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"root_logger",
".",
"setLevel",
"(",
"getattr",
"(",
"logging",
",",
"conf",
".",
"loglevel",
".",
"upper",
"(",
")",
")",
")",
"if",
"conf",
... | 40.375 | 0.00303 |
def to_image_type(image_type):
'''
to_image_type(image_type) yields an image-type class equivalent to the given image_type
argument, which may be a type name or alias or an image or header object or class.
'''
if image_type is None: return None
if isinstance(image_type, type) and issubclas... | [
"def",
"to_image_type",
"(",
"image_type",
")",
":",
"if",
"image_type",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"image_type",
",",
"type",
")",
"and",
"issubclass",
"(",
"image_type",
",",
"ImageType",
")",
":",
"return",
"image_type",... | 49.947368 | 0.01758 |
def credentials(self, credentials):
"""
Sets the credentials of this WebAuthorization.
The confidential portion of the `Authorization` header that follows the `type` field. This field is write-only. It is omitted by read operations. If authorization is required, the `credentials` value must be... | [
"def",
"credentials",
"(",
"self",
",",
"credentials",
")",
":",
"if",
"credentials",
"is",
"not",
"None",
"and",
"len",
"(",
"credentials",
")",
">",
"1024",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `credentials`, length must be less than or equal to `10... | 75 | 0.005761 |
def subtractpubs(p1,p2,outcompressed=True):
'''
Pubkey inputs can be compressed or uncompressed, as long as
they're valid keys and hex strings. Use the validatepubkey()
function to validate them first. The compression of the input
keys does not do anything or matter in any way. Only the
outcompr... | [
"def",
"subtractpubs",
"(",
"p1",
",",
"p2",
",",
"outcompressed",
"=",
"True",
")",
":",
"if",
"len",
"(",
"p1",
")",
"==",
"66",
":",
"p1",
"=",
"uncompress",
"(",
"p1",
")",
"if",
"len",
"(",
"p2",
")",
"==",
"66",
":",
"p2",
"=",
"uncompres... | 32.227273 | 0.015068 |
def shader_substring(body, stack_frame=1):
"""
Call this method from a function that defines a literal shader string as the "body" argument.
Dresses up a shader string in two ways:
1) Insert #line number declaration
2) un-indents
The line number information can help debug glsl comp... | [
"def",
"shader_substring",
"(",
"body",
",",
"stack_frame",
"=",
"1",
")",
":",
"line_count",
"=",
"len",
"(",
"body",
".",
"splitlines",
"(",
"True",
")",
")",
"line_number",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"stack_frame",
"]",
"[",
"2",
... | 42.6875 | 0.007163 |
def subprocess(self):
"""Retrieve the subprocess in which this activity is defined.
If this is a task on top level, it raises NotFounderror.
:return: a subprocess :class:`Activity`
:raises NotFoundError: when it is a task in the top level of a project
:raises APIError: when oth... | [
"def",
"subprocess",
"(",
"self",
")",
":",
"subprocess_id",
"=",
"self",
".",
"_json_data",
".",
"get",
"(",
"'container'",
")",
"if",
"subprocess_id",
"==",
"self",
".",
"_json_data",
".",
"get",
"(",
"'root_container'",
")",
":",
"raise",
"NotFoundError",... | 40.8 | 0.003593 |
def crs(self, crs):
"""Setter for extent_crs property.
:param crs: The coordinate reference system for the analysis boundary.
:type crs: QgsCoordinateReferenceSystem
"""
if isinstance(crs, QgsCoordinateReferenceSystem):
self._crs = crs
self._is_ready = Fa... | [
"def",
"crs",
"(",
"self",
",",
"crs",
")",
":",
"if",
"isinstance",
"(",
"crs",
",",
"QgsCoordinateReferenceSystem",
")",
":",
"self",
".",
"_crs",
"=",
"crs",
"self",
".",
"_is_ready",
"=",
"False",
"else",
":",
"raise",
"InvalidExtentError",
"(",
"'%s... | 36.636364 | 0.004843 |
def delete_subscription(self, subscription_id, client_id, client_secret):
"""
Unsubscribe from webhook events for an existing subscription.
http://strava.github.io/api/partner/v3/events/#delete-a-subscription
:param subscription_id: ID of subscription to remove.
:type subscript... | [
"def",
"delete_subscription",
"(",
"self",
",",
"subscription_id",
",",
"client_id",
",",
"client_secret",
")",
":",
"self",
".",
"protocol",
".",
"delete",
"(",
"'/push_subscriptions/{id}'",
",",
"id",
"=",
"subscription_id",
",",
"client_id",
"=",
"client_id",
... | 42.705882 | 0.005391 |
def _update_request_context_with_user(self, user=None):
'''Store the given user as ctx.user.'''
ctx = _request_ctx_stack.top
ctx.user = self.anonymous_user() if user is None else user | [
"def",
"_update_request_context_with_user",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"ctx",
"=",
"_request_ctx_stack",
".",
"top",
"ctx",
".",
"user",
"=",
"self",
".",
"anonymous_user",
"(",
")",
"if",
"user",
"is",
"None",
"else",
"user"
] | 40.8 | 0.009615 |
def getFailedItems(self):
"""
Return an iterable of two-tuples of listeners which raised an
exception from C{processItem} and the item which was passed as
the argument to that method.
"""
for failed in self.store.query(BatchProcessingError, BatchProcessingError.processor ... | [
"def",
"getFailedItems",
"(",
"self",
")",
":",
"for",
"failed",
"in",
"self",
".",
"store",
".",
"query",
"(",
"BatchProcessingError",
",",
"BatchProcessingError",
".",
"processor",
"==",
"self",
")",
":",
"yield",
"(",
"failed",
".",
"listener",
",",
"fa... | 46.375 | 0.007937 |
def build_url_field(self, field_name, model_class):
"""
Create a field representing the object's own URL.
"""
field_class = self.serializer_url_field
field_kwargs = get_url_kwargs(model_class)
return field_class, field_kwargs | [
"def",
"build_url_field",
"(",
"self",
",",
"field_name",
",",
"model_class",
")",
":",
"field_class",
"=",
"self",
".",
"serializer_url_field",
"field_kwargs",
"=",
"get_url_kwargs",
"(",
"model_class",
")",
"return",
"field_class",
",",
"field_kwargs"
] | 33.375 | 0.007299 |
def session_path(cls, project, instance, database, session):
"""Return a fully-qualified session string."""
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/databases/{database}/sessions/{session}",
project=project,
instance=instan... | [
"def",
"session_path",
"(",
"cls",
",",
"project",
",",
"instance",
",",
"database",
",",
"session",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"projects/{project}/instances/{instance}/databases/{database}/sessions/{sessio... | 42.777778 | 0.007634 |
def p_labelled_statement(self, p):
"""labelled_statement : identifier COLON statement"""
p[0] = ast.Label(identifier=p[1], statement=p[3]) | [
"def",
"p_labelled_statement",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"Label",
"(",
"identifier",
"=",
"p",
"[",
"1",
"]",
",",
"statement",
"=",
"p",
"[",
"3",
"]",
")"
] | 50.666667 | 0.012987 |
def _convert_string_name(self, k):
"""converts things like FOO_BAR to Foo-Bar which is the normal form"""
k = String(k, "iso-8859-1")
klower = k.lower().replace('_', '-')
bits = klower.split('-')
return "-".join((bit.title() for bit in bits)) | [
"def",
"_convert_string_name",
"(",
"self",
",",
"k",
")",
":",
"k",
"=",
"String",
"(",
"k",
",",
"\"iso-8859-1\"",
")",
"klower",
"=",
"k",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"bits",
"=",
"klower",
".",
"split",
... | 46.166667 | 0.007092 |
def wrap(self, data):
"""Wrap this with the root schema definitions."""
if self.nested: # no need to wrap, will be in outer defs
return data
name = self.obj.__class__.__name__
self._nested_schema_classes[name] = data
root = {
'definitions': self._nested_... | [
"def",
"wrap",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"nested",
":",
"# no need to wrap, will be in outer defs",
"return",
"data",
"name",
"=",
"self",
".",
"obj",
".",
"__class__",
".",
"__name__",
"self",
".",
"_nested_schema_classes",
"[",
... | 34.583333 | 0.004695 |
def remove(self, elem):
"""
Return new deque with first element from left equal to elem removed. If no such element is found
a ValueError is raised.
>>> pdeque([2, 1, 2]).remove(2)
pdeque([1, 2])
"""
try:
return PDeque(self._left_list.remove(elem), se... | [
"def",
"remove",
"(",
"self",
",",
"elem",
")",
":",
"try",
":",
"return",
"PDeque",
"(",
"self",
".",
"_left_list",
".",
"remove",
"(",
"elem",
")",
",",
"self",
".",
"_right_list",
",",
"self",
".",
"_length",
"-",
"1",
")",
"except",
"ValueError",... | 44.777778 | 0.008505 |
def _set_interface_isis(self, v, load=False):
"""
Setter method for interface_isis, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_isis is considered as a private
m... | [
"def",
"_set_interface_isis",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | 81.818182 | 0.005491 |
def write_sample_sheet(path, accessions, names, celfile_urls, sel=None):
"""Write the sample sheet."""
with open(path, 'wb') as ofh:
writer = csv.writer(ofh, dialect='excel-tab',
lineterminator=os.linesep,
quoting=csv.QUOTE_NONE)
# write he... | [
"def",
"write_sample_sheet",
"(",
"path",
",",
"accessions",
",",
"names",
",",
"celfile_urls",
",",
"sel",
"=",
"None",
")",
":",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"ofh",
":",
"writer",
"=",
"csv",
".",
"writer",
"(",
"ofh",
",",
... | 44.8 | 0.001458 |
def time(arg):
"""Converts the value into a unix time (seconds since unix epoch).
For example:
convert.time(datetime.now())
# '1409810596'
:param arg: The time.
:type arg: datetime.datetime or int
"""
# handle datetime instances.
if _has_method(arg, "timetuple"):
ar... | [
"def",
"time",
"(",
"arg",
")",
":",
"# handle datetime instances.",
"if",
"_has_method",
"(",
"arg",
",",
"\"timetuple\"",
")",
":",
"arg",
"=",
"_time",
".",
"mktime",
"(",
"arg",
".",
"timetuple",
"(",
")",
")",
"if",
"isinstance",
"(",
"arg",
",",
... | 22.888889 | 0.002331 |
def add_new_directory(self, node):
"""
Adds a new directory next to given Node associated path.
:param node: Node.
:type node: ProjectNode or DirectoryNode or FileNode
:return: Method success.
:rtype: bool
"""
if self.__script_editor.model.is_authoring_n... | [
"def",
"add_new_directory",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"__script_editor",
".",
"model",
".",
"is_authoring_node",
"(",
"node",
")",
":",
"return",
"False",
"directory",
",",
"state",
"=",
"QInputDialog",
".",
"getText",
"(",
"se... | 36.433333 | 0.004456 |
def start(self):
"""
Run the process.
"""
if self:
raise ProcessError(
"Process '%s' has been already started" % self.name)
first_run = not self.has_started
# Run process
self._process = self._process_cls(*self._process_args)
se... | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
":",
"raise",
"ProcessError",
"(",
"\"Process '%s' has been already started\"",
"%",
"self",
".",
"name",
")",
"first_run",
"=",
"not",
"self",
".",
"has_started",
"# Run process",
"self",
".",
"_process",
"... | 38.083333 | 0.002134 |
def exists(self):
"""Test whether this instance exists.
See
https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1#google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig
:rtype: bool
:returns: True if the instance exists, else false
""... | [
"def",
"exists",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"_client",
".",
"instance_admin_api",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"try",
":",
"api",
".",
"get_instance",
"(",
"self",
".",
"name",
",",
"metada... | 30.333333 | 0.003552 |
def get_linc_rna_genes(
path_or_buffer,
remove_duplicates=True,
**kwargs):
r"""Get list of all protein-coding genes based on Ensembl GTF file.
Parameters
----------
See :func:`get_genes` function.
Returns
-------
`pandas.DataFrame`
Table with rows corres... | [
"def",
"get_linc_rna_genes",
"(",
"path_or_buffer",
",",
"remove_duplicates",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"valid_biotypes",
"=",
"set",
"(",
"[",
"'lincRNA'",
"]",
")",
"df",
"=",
"get_genes",
"(",
"path_or_buffer",
",",
"valid_biotypes",
... | 24.52381 | 0.005607 |
def set_nodes(self, nlabels = [], coords = [], nsets = {}, **kwargs):
r"""
Sets the node data.
:arg nlabels: node labels. Items be strictly positive and int typed
in 1D array-like with shape :math:`(N_n)`.
:type nlabels: 1D uint typed array-like
:arg coords: node coordinates.... | [
"def",
"set_nodes",
"(",
"self",
",",
"nlabels",
"=",
"[",
"]",
",",
"coords",
"=",
"[",
"]",
",",
"nsets",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"# DATA PREPROCESSING",
"nlabels",
"=",
"np",
".",
"array",
"(",
"nlabels",
")",
".",
"a... | 43.333333 | 0.020063 |
def prevnode(edges, component):
"""get the pervious component in the loop"""
e = edges
c = component
n2c = [(a, b) for a, b in e if type(a) == tuple]
c2n = [(a, b) for a, b in e if type(b) == tuple]
node2cs = [(a, b) for a, b in e if b == c]
c2nodes = []
for node2c in node2cs:
c2... | [
"def",
"prevnode",
"(",
"edges",
",",
"component",
")",
":",
"e",
"=",
"edges",
"c",
"=",
"component",
"n2c",
"=",
"[",
"(",
"a",
",",
"b",
")",
"for",
"a",
",",
"b",
"in",
"e",
"if",
"type",
"(",
"a",
")",
"==",
"tuple",
"]",
"c2n",
"=",
"... | 32.652174 | 0.001294 |
def GetTypeManager(self):
""" Get dynamic type manager """
dynTypeMgr = None
if self.hostSystem:
try:
dynTypeMgr = self.hostSystem.RetrieveDynamicTypeManager()
except vmodl.fault.MethodNotFound as err:
pass
if not dynTypeMgr:
# Older host not s... | [
"def",
"GetTypeManager",
"(",
"self",
")",
":",
"dynTypeMgr",
"=",
"None",
"if",
"self",
".",
"hostSystem",
":",
"try",
":",
"dynTypeMgr",
"=",
"self",
".",
"hostSystem",
".",
"RetrieveDynamicTypeManager",
"(",
")",
"except",
"vmodl",
".",
"fault",
".",
"M... | 37.066667 | 0.021053 |
def cluster_on_extra_high_voltage(network, busmap, with_time=True):
""" Main function of the EHV-Clustering approach. Creates a new clustered
pypsa.Network given a busmap mapping all bus_ids to other bus_ids of the
same network.
Parameters
----------
network : pypsa.Network
Container fo... | [
"def",
"cluster_on_extra_high_voltage",
"(",
"network",
",",
"busmap",
",",
"with_time",
"=",
"True",
")",
":",
"network_c",
"=",
"Network",
"(",
")",
"buses",
"=",
"aggregatebuses",
"(",
"network",
",",
"busmap",
",",
"{",
"'x'",
":",
"_leading",
"(",
"bu... | 33.493506 | 0.000377 |
def show_install(show_nvidia_smi:bool=False):
"Print user's setup information"
import platform, fastai.version
rep = []
opt_mods = []
rep.append(["=== Software ===", None])
rep.append(["python", platform.python_version()])
rep.append(["fastai", fastai.__version__])
rep.append(["fastpr... | [
"def",
"show_install",
"(",
"show_nvidia_smi",
":",
"bool",
"=",
"False",
")",
":",
"import",
"platform",
",",
"fastai",
".",
"version",
"rep",
"=",
"[",
"]",
"opt_mods",
"=",
"[",
"]",
"rep",
".",
"append",
"(",
"[",
"\"=== Software ===\"",
",",
"None",... | 37.276786 | 0.006766 |
def is_weighted(self):
"""True if weights have been applied to the measure(s) for this cube.
Unweighted counts are available for all cubes. Weighting applies to
any other measures provided by the cube.
"""
cube_dict = self._cube_dict
if cube_dict.get("query", {}).get("we... | [
"def",
"is_weighted",
"(",
"self",
")",
":",
"cube_dict",
"=",
"self",
".",
"_cube_dict",
"if",
"cube_dict",
".",
"get",
"(",
"\"query\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"weight\"",
")",
"is",
"not",
"None",
":",
"return",
"True",
"if",
"cube... | 40.388889 | 0.004032 |
def _variable_on_cpu(name, shape, initializer):
"""Helper to create a Variable stored on CPU memory.
Args:
name: name of the variable
shape: list of ints
initializer: initializer for Variable
Returns:
Variable Tensor
"""
with tf.device('/cpu:0'):
dtype = tf.float16 if FLAGS.use_fp16 else... | [
"def",
"_variable_on_cpu",
"(",
"name",
",",
"shape",
",",
"initializer",
")",
":",
"with",
"tf",
".",
"device",
"(",
"'/cpu:0'",
")",
":",
"dtype",
"=",
"tf",
".",
"float16",
"if",
"FLAGS",
".",
"use_fp16",
"else",
"tf",
".",
"float32",
"var",
"=",
... | 27.133333 | 0.009501 |
def delete_grade_entry(self, grade_entry_id):
"""Deletes the ``GradeEntry`` identified by the given ``Id``.
arg: grade_entry_id (osid.id.Id): the ``Id`` of the
``GradeEntry`` to delete
raise: NotFound - a ``GradeEntry`` was not found identified by
the given `... | [
"def",
"delete_grade_entry",
"(",
"self",
",",
"grade_entry_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.delete_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'grading'",
",",
"collection",
"=",
"'GradeEntry'",
","... | 51.346154 | 0.002941 |
def hold_exception(method):
"""Decorator for glib callback methods of GLibMainLoop used to store the
exception raised."""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
"""Wrapper for methods decorated with `hold_exception`."""
# pylint: disable=W0703,W0212
try:
... | [
"def",
"hold_exception",
"(",
"method",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapper for methods decorated with `hold_exception`.\"\"\"",
"# pylin... | 40 | 0.004883 |
def transformArray(data, keysToSplit=[]):
"""
Transform a SPARQL json array based on the rules of transform
"""
transformed = [ ]
for item in data:
transformed.append(transform(item, keysToSplit))
return transformed | [
"def",
"transformArray",
"(",
"data",
",",
"keysToSplit",
"=",
"[",
"]",
")",
":",
"transformed",
"=",
"[",
"]",
"for",
"item",
"in",
"data",
":",
"transformed",
".",
"append",
"(",
"transform",
"(",
"item",
",",
"keysToSplit",
")",
")",
"return",
"tra... | 30 | 0.008097 |
def _base64_to_file(b64str, outfpath, writetostrio=False):
'''This converts the base64 encoded string to a file.
Parameters
----------
b64str : str
A base64 encoded strin that is the output of `base64.b64encode`.
outfpath : str
The path to where the file will be written. This shou... | [
"def",
"_base64_to_file",
"(",
"b64str",
",",
"outfpath",
",",
"writetostrio",
"=",
"False",
")",
":",
"try",
":",
"filebytes",
"=",
"base64",
".",
"b64decode",
"(",
"b64str",
")",
"# if we're writing back to a stringio object",
"if",
"writetostrio",
":",
"outobj"... | 29.741379 | 0.001122 |
def fileattr_from_metadata(md):
# type: (dict) -> collections.namedtuple
"""Convert fileattr metadata in json metadata
:param dict md: metadata dictionary
:rtype: PosixFileAttr or WindowsFileAttr or None
:return: fileattr metadata
"""
try:
mdattr = json.loads(
md[JSON_KEY... | [
"def",
"fileattr_from_metadata",
"(",
"md",
")",
":",
"# type: (dict) -> collections.namedtuple",
"try",
":",
"mdattr",
"=",
"json",
".",
"loads",
"(",
"md",
"[",
"JSON_KEY_BLOBXFER_METADATA",
"]",
")",
"[",
"_JSON_KEY_FILE_ATTRIBUTES",
"]",
"except",
"(",
"KeyError... | 38 | 0.000755 |
def right_press(self, event):
"""
Callback for the right mouse button event to pop up the correct menu.
:param event: Tkinter event
"""
self.set_current()
current = self.canvas.find_withtag("current")
if current and current[0] in self.canvas.find_withtag(... | [
"def",
"right_press",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"set_current",
"(",
")",
"current",
"=",
"self",
".",
"canvas",
".",
"find_withtag",
"(",
"\"current\"",
")",
"if",
"current",
"and",
"current",
"[",
"0",
"]",
"in",
"self",
".",
... | 37.333333 | 0.005226 |
def autorun(func, _depth=1):
"""
Runs the function if the module in which it is declared is being run
directly from the commandline. Putting the following after the function
definition would be similar:
if __name__ == '__main__':
func()
NOTE: This will work most... | [
"def",
"autorun",
"(",
"func",
",",
"_depth",
"=",
"1",
")",
":",
"frame_local",
"=",
"sys",
".",
"_getframe",
"(",
"_depth",
")",
".",
"f_locals",
"if",
"'__name__'",
"in",
"frame_local",
"and",
"frame_local",
"[",
"'__name__'",
"]",
"==",
"'__main__'",
... | 32.842105 | 0.001558 |
def create_schema(self):
"""Create all necessary tables"""
cursor = self.cursor
execute = cursor.execute
execute('SHOW TABLES')
tables = {table for table, in cursor}
if 'gauged_data' not in tables:
execute("""CREATE TABLE gauged_data (
namespac... | [
"def",
"create_schema",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"cursor",
"execute",
"=",
"cursor",
".",
"execute",
"execute",
"(",
"'SHOW TABLES'",
")",
"tables",
"=",
"{",
"table",
"for",
"table",
",",
"in",
"cursor",
"}",
"if",
"'gauged_dat... | 47.6 | 0.000915 |
def convert_sed_cols(tab):
"""Cast SED column names to lowercase."""
# Update Column names
for colname in list(tab.columns.keys()):
newname = colname.lower()
newname = newname.replace('dfde', 'dnde')
if tab.columns[colname].name == newname:
continue
tab.columns... | [
"def",
"convert_sed_cols",
"(",
"tab",
")",
":",
"# Update Column names",
"for",
"colname",
"in",
"list",
"(",
"tab",
".",
"columns",
".",
"keys",
"(",
")",
")",
":",
"newname",
"=",
"colname",
".",
"lower",
"(",
")",
"newname",
"=",
"newname",
".",
"r... | 24.785714 | 0.002778 |
def move_partition_replica(self, under_loaded_rg, eligible_partition):
"""Move partition to under-loaded replication-group if possible."""
# Evaluate possible source and destination-broker
source_broker, dest_broker = self._get_eligible_broker_pair(
under_loaded_rg,
eligi... | [
"def",
"move_partition_replica",
"(",
"self",
",",
"under_loaded_rg",
",",
"eligible_partition",
")",
":",
"# Evaluate possible source and destination-broker",
"source_broker",
",",
"dest_broker",
"=",
"self",
".",
"_get_eligible_broker_pair",
"(",
"under_loaded_rg",
",",
"... | 47.842105 | 0.002157 |
def download(ctx, archive_name, filepath, version):
'''
Download an archive
'''
_generate_api(ctx)
var = ctx.obj.api.get_archive(archive_name)
if version is None:
version = var.get_default_version()
var.download(filepath, version=version)
archstr = var.archive_name +\
... | [
"def",
"download",
"(",
"ctx",
",",
"archive_name",
",",
"filepath",
",",
"version",
")",
":",
"_generate_api",
"(",
"ctx",
")",
"var",
"=",
"ctx",
".",
"obj",
".",
"api",
".",
"get_archive",
"(",
"archive_name",
")",
"if",
"version",
"is",
"None",
":"... | 24.823529 | 0.002283 |
def format_errors(self, errors, many):
"""Format validation errors as JSON Error objects."""
if not errors:
return {}
if isinstance(errors, (list, tuple)):
return {'errors': errors}
formatted_errors = []
if many:
for index, errors in iteritems... | [
"def",
"format_errors",
"(",
"self",
",",
"errors",
",",
"many",
")",
":",
"if",
"not",
"errors",
":",
"return",
"{",
"}",
"if",
"isinstance",
"(",
"errors",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"{",
"'errors'",
":",
"errors",
"... | 39.136364 | 0.002268 |
def replace_insight(self, project_owner, project_id, id, **kwargs):
"""
Replace an insight
Replace an insight.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving t... | [
"def",
"replace_insight",
"(",
"self",
",",
"project_owner",
",",
"project_id",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
... | 67.642857 | 0.003644 |
def group_pivot(self, group_resource):
"""Pivot point on groups for this resource.
This method will return all *resources* (indicators, tasks, victims, etc) for this resource
that are associated with the provided resource id (indicator value).
**Example Endpoints URI's**
+----... | [
"def",
"group_pivot",
"(",
"self",
",",
"group_resource",
")",
":",
"resource",
"=",
"self",
".",
"copy",
"(",
")",
"resource",
".",
"_request_uri",
"=",
"'{}/{}'",
".",
"format",
"(",
"group_resource",
".",
"request_uri",
",",
"resource",
".",
"_request_uri... | 66.060606 | 0.005877 |
def join(args):
"""
%prog join file1.txt(pivotfile) file2.txt ..
Join tabular-like files based on common column.
--column specifies the column index to pivot on.
Use comma to separate multiple values if the pivot column is different
in each file. Maintain the order in the first file.
--... | [
"def",
"join",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"join",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--column\"",
",",
"default",
"=",
"\"0\"",
",",
"help",
"=",
"\"0-based column id, multiple values allowed [default: %default]\"",
"... | 33.022727 | 0.002005 |
def filter_and_copy_table(tab, to_remove):
""" Filter and copy a FITS table.
Parameters
----------
tab : FITS Table object
to_remove : [int ...}
list of indices to remove from the table
returns FITS Table object
"""
nsrcs = len(tab)
mask = np.zeros((nsrcs), '?')
mas... | [
"def",
"filter_and_copy_table",
"(",
"tab",
",",
"to_remove",
")",
":",
"nsrcs",
"=",
"len",
"(",
"tab",
")",
"mask",
"=",
"np",
".",
"zeros",
"(",
"(",
"nsrcs",
")",
",",
"'?'",
")",
"mask",
"[",
"to_remove",
"]",
"=",
"True",
"inv_mask",
"=",
"np... | 22.222222 | 0.004796 |
def connection_open(self) -> None:
"""
Callback when the WebSocket opening handshake completes.
Enter the OPEN state and start the data transfer phase.
"""
# 4.1. The WebSocket Connection is Established.
assert self.state is State.CONNECTING
self.state = State.O... | [
"def",
"connection_open",
"(",
"self",
")",
"->",
"None",
":",
"# 4.1. The WebSocket Connection is Established.",
"assert",
"self",
".",
"state",
"is",
"State",
".",
"CONNECTING",
"self",
".",
"state",
"=",
"State",
".",
"OPEN",
"logger",
".",
"debug",
"(",
"\... | 47.176471 | 0.003667 |
def _public(self, command, **params):
"""Invoke the 'command' public API with optional params."""
params['command'] = command
response = self.session.get(self._public_url, params=params)
return response | [
"def",
"_public",
"(",
"self",
",",
"command",
",",
"*",
"*",
"params",
")",
":",
"params",
"[",
"'command'",
"]",
"=",
"command",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"_public_url",
",",
"params",
"=",
"params",
")"... | 46 | 0.008547 |
def read_undone_from_datastore(self, shard_id=None, num_shards=None):
"""Reads undone work from the datastore.
If shard_id and num_shards are specified then this method will attempt
to read undone work for shard with id shard_id. If no undone work was found
then it will try to read shard (shard_id+1) a... | [
"def",
"read_undone_from_datastore",
"(",
"self",
",",
"shard_id",
"=",
"None",
",",
"num_shards",
"=",
"None",
")",
":",
"if",
"shard_id",
"is",
"not",
"None",
":",
"shards_list",
"=",
"[",
"(",
"i",
"+",
"shard_id",
")",
"%",
"num_shards",
"for",
"i",
... | 34.769231 | 0.005382 |
def connection_made(self, address):
"""When a connection is made the proxy is available."""
self._proxy = PickleProxy(self.loop, self)
for d in self._proxy_deferreds:
d.callback(self._proxy) | [
"def",
"connection_made",
"(",
"self",
",",
"address",
")",
":",
"self",
".",
"_proxy",
"=",
"PickleProxy",
"(",
"self",
".",
"loop",
",",
"self",
")",
"for",
"d",
"in",
"self",
".",
"_proxy_deferreds",
":",
"d",
".",
"callback",
"(",
"self",
".",
"_... | 44.4 | 0.00885 |
def _get_headers(self):
"""Built headers for request to IPinfo API."""
headers = {
'user-agent': 'IPinfoClient/Python{version}/1.0'.format(version=sys.version_info[0]),
'accept': 'application/json'
}
if self.access_token:
headers['authorization'] = 'B... | [
"def",
"_get_headers",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"'user-agent'",
":",
"'IPinfoClient/Python{version}/1.0'",
".",
"format",
"(",
"version",
"=",
"sys",
".",
"version_info",
"[",
"0",
"]",
")",
",",
"'accept'",
":",
"'application/json'",
"}",
... | 33.545455 | 0.007916 |
def getSortedUsers(self, order="public"):
"""Return a list with sorted users.
:param order: the field to sort the users.
- contributions (total number of contributions)
- public (public contributions)
- private (private contributions)
- name
-... | [
"def",
"getSortedUsers",
"(",
"self",
",",
"order",
"=",
"\"public\"",
")",
":",
"if",
"order",
"==",
"\"contributions\"",
":",
"self",
".",
"__users",
".",
"sort",
"(",
"key",
"=",
"lambda",
"u",
":",
"u",
"[",
"\"contributions\"",
"]",
",",
"reverse",
... | 40.526316 | 0.001268 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.