code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def _no_spelling_errors(relative_path, contents, linter_options): block_regexps = linter_options.get("block_regexps", None) chunks, shadow = spellcheckable_and_shadow_contents(contents, block_regexps) cache = linter_options.get("spellcheck_cache", None) user_words, valid_words = valid_words_dictionary_helper.create(cache) technical_words = _create_technical_words_dictionary(cache, relative_path, user_words, shadow) if linter_options.get("log_technical_terms_to"): linter_options["log_technical_terms_to"].put(technical_words.words()) return [e for e in _find_spelling_errors_in_chunks(chunks, contents, valid_words, technical_words, user_words) if e]
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list return_statement list_comprehension identifier for_in_clause identifier call identifier argument_list identifier identifier identifier identifier identifier if_clause identifier
No spelling errors in strings, comments or anything of the like.
def clear(self, *resource_types): resource_types = resource_types or tuple(self.__caches.keys()) for cls in resource_types: self.__caches[cls].clear() del self.__caches[cls]
module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier boolean_operator identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list for_statement identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list delete_statement subscript attribute identifier identifier identifier
Clear cache for each provided APIResource class, or all resources if no classes are provided
def _load_from_geo_ref(self, dsid): file_handlers = self._get_file_handlers(dsid) if not file_handlers: return None fns = [] for fh in file_handlers: base_dir = os.path.dirname(fh.filename) try: fn = fh['/attr/N_GEO_Ref'][:46] + '*.h5' fns.extend(glob(os.path.join(base_dir, fn))) if fn[:5] == 'GIMGO': fn = 'GITCO' + fn[5:] elif fn[:5] == 'GMODO': fn = 'GMTCO' + fn[5:] else: continue fns.extend(glob(os.path.join(base_dir, fn))) except KeyError: LOG.debug("Could not load geo-reference information from {}".format(fh.filename)) return fns
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block return_statement none expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier try_statement block expression_statement assignment identifier binary_operator subscript subscript identifier string string_start string_content string_end slice integer string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement comparison_operator subscript identifier slice integer string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end subscript identifier slice integer elif_clause comparison_operator subscript identifier slice integer string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end subscript identifier slice integer else_clause block continue_statement expression_statement call attribute identifier identifier argument_list call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier return_statement identifier
Load filenames from the N_GEO_Ref attribute of a dataset's file.
def input(self, request, tag): subform = self.parameter.form.asSubForm(self.parameter.name) subform.setFragmentParent(self) return tag[subform]
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement subscript identifier identifier
Add the wrapped form, as a subform, as a child of the given tag.
def surface2image(surface): global g_lock with g_lock: img_io = io.BytesIO() surface.write_to_png(img_io) img_io.seek(0) img = PIL.Image.open(img_io) img.load() if "A" not in img.getbands(): return img img_no_alpha = PIL.Image.new("RGB", img.size, (255, 255, 255)) img_no_alpha.paste(img, mask=img.split()[3]) return img_no_alpha
module function_definition identifier parameters identifier block global_statement identifier with_statement with_clause with_item identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block return_statement identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier tuple integer integer integer expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier subscript call attribute identifier identifier argument_list integer return_statement identifier
Convert a cairo surface into a PIL image
def print_runs(query): if query is None: return for tup in query: print(("{0} @ {1} - {2} id: {3} group: {4}".format( tup.end, tup.experiment_name, tup.project_name, tup.experiment_group, tup.run_group)))
module function_definition identifier parameters identifier block if_statement comparison_operator identifier none block return_statement for_statement identifier identifier block expression_statement call identifier argument_list parenthesized_expression call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier
Print all rows in this result query.
def ports(self) -> dict: return { param: self[param].raw for param in self if param.startswith(IOPORT) }
module function_definition identifier parameters identifier type identifier block return_statement dictionary_comprehension pair identifier attribute subscript identifier identifier identifier for_in_clause identifier identifier if_clause call attribute identifier identifier argument_list identifier
Create a smaller dictionary containing all ports.
def component_div(vec1, vec2): new_vec = Vector2() new_vec.X = vec1.X / vec2.X new_vec.Y = vec1.Y / vec2.Y return new_vec
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier return_statement identifier
Divide the components of the vectors and return the result.
def _update_feature_log_prob(self, alpha): smoothed_fc = self.feature_count_ + alpha smoothed_cc = self.class_count_ + alpha * 2 self.feature_log_prob_ = (np.log(smoothed_fc) - np.log(smoothed_cc.reshape(-1, 1)))
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier identifier expression_statement assignment identifier binary_operator attribute identifier identifier binary_operator identifier integer expression_statement assignment attribute identifier identifier parenthesized_expression binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list unary_operator integer integer
Apply smoothing to raw counts and recompute log probabilities
def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None): if not any([subnet_name, tags, cidr]): raise SaltInvocationError('At least one of the following must be ' 'specified: subnet_name, cidr or tags.') filter_parameters = {'filters': {}} if cidr: filter_parameters['filters']['cidr'] = cidr if subnet_name: filter_parameters['filters']['tag:Name'] = subnet_name if vpc_id: filter_parameters['filters']['VpcId'] = vpc_id if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug('The filters criteria %s matched the following subnets: %s', filter_parameters, subnets) if subnets: return [subnet.id for subnet in subnets] else: return False
module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement not_operator call identifier argument_list list identifier identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end dictionary if_statement identifier block expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier if_statement identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier block expression_statement assignment subscript subscript identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier if_statement identifier block return_statement list_comprehension attribute identifier identifier for_in_clause identifier identifier else_clause block return_statement false
Given subnet properties, find and return matching subnet ids
def globalsfilter(input_dict, check_all=False, filters=None, exclude_private=None, exclude_capitalized=None, exclude_uppercase=None, exclude_unsupported=None, excluded_names=None): output_dict = {} for key, value in list(input_dict.items()): excluded = (exclude_private and key.startswith('_')) or \ (exclude_capitalized and key[0].isupper()) or \ (exclude_uppercase and key.isupper() and len(key) > 1 and not key[1:].isdigit()) or \ (key in excluded_names) or \ (exclude_unsupported and \ not is_supported(value, check_all=check_all, filters=filters)) if not excluded: output_dict[key] = value return output_dict
module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list block expression_statement assignment identifier boolean_operator boolean_operator boolean_operator boolean_operator parenthesized_expression boolean_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end line_continuation parenthesized_expression boolean_operator identifier call attribute subscript identifier integer identifier argument_list line_continuation parenthesized_expression boolean_operator boolean_operator boolean_operator identifier call attribute identifier identifier argument_list comparison_operator call identifier argument_list identifier integer not_operator call attribute subscript identifier slice integer identifier argument_list line_continuation parenthesized_expression comparison_operator identifier identifier line_continuation parenthesized_expression boolean_operator identifier line_continuation not_operator call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement not_operator identifier block expression_statement assignment subscript identifier identifier identifier return_statement identifier
Keep only objects that can be pickled
def read_values(target_usage): all_devices = hid.HidDeviceFilter().get_devices() if not all_devices: print("Can't find any non system HID device connected") else: usage_found = False for device in all_devices: try: device.open() for report in device.find_feature_reports(): if target_usage in report: report.get() print("The value:", list(report[target_usage])) print("All the report: {0}".format(report.get_raw_data())) usage_found = True finally: device.close() if not usage_found: print("The target device was found, but the requested usage does not exist!\n")
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier false for_statement identifier identifier block try_statement block expression_statement call attribute identifier identifier argument_list for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end call identifier argument_list subscript identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier true finally_clause block expression_statement call attribute identifier identifier argument_list if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content escape_sequence string_end
read feature report values
def add_hbar_widget(self, ref, x=1, y=1, length=10): if ref not in self.widgets: widget = widgets.HBarWidget(screen=self, ref=ref, x=x, y=y, length=length) self.widgets[ref] = widget return self.widgets[ref]
module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement subscript attribute identifier identifier identifier
Add Horizontal Bar Widget
def logged_delete(self, user): self.delete() entry = ChangeLogEntry({ 'type': 'DELETED', 'documents': [self], 'user': user }) entry.insert() return entry
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end list identifier pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list return_statement identifier
Delete the document and log the event in the change log
def pad_block(block, block_size): unique_vals, unique_counts = np.unique(block, return_counts=True) most_frequent_value = unique_vals[np.argmax(unique_counts)] return np.pad(block, tuple((0, desired_size - actual_size) for desired_size, actual_size in zip(block_size, block.shape)), mode="constant", constant_values=most_frequent_value)
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement assignment identifier subscript identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier call identifier generator_expression tuple integer binary_operator identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier
Pad a block to block_size with its most frequent value
def omerc2cf(area): proj_dict = area.proj_dict args = dict(azimuth_of_central_line=proj_dict.get('alpha'), latitude_of_projection_origin=proj_dict.get('lat_0'), longitude_of_projection_origin=proj_dict.get('lonc'), grid_mapping_name='oblique_mercator', reference_ellipsoid_name=proj_dict.get('ellps', 'WGS84'), false_easting=0., false_northing=0. ) if "no_rot" in proj_dict: args['no_rotation'] = 1 if "gamma" in proj_dict: args['gamma'] = proj_dict['gamma'] return args
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier float keyword_argument identifier float if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end integer if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end return_statement identifier
Return the cf grid mapping for the omerc projection.
def update_project_template(push): import ballet.update import ballet.util.log ballet.util.log.enable(level='INFO', format=ballet.util.log.SIMPLE_LOG_FORMAT, echo=False) ballet.update.update_project_template(push=push)
module function_definition identifier parameters identifier block import_statement dotted_name identifier identifier import_statement dotted_name identifier identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute attribute attribute identifier identifier identifier identifier keyword_argument identifier false expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier
Update an existing ballet project from the upstream template
def write_to(output, txt): if (isinstance(txt, six.binary_type) or six.PY3 and isinstance(output, StringIO)) or isinstance(output, TextIOWrapper): output.write(txt) else: output.write(txt.encode("utf-8", "replace"))
module function_definition identifier parameters identifier identifier block if_statement boolean_operator parenthesized_expression boolean_operator call identifier argument_list identifier attribute identifier identifier boolean_operator attribute identifier identifier call identifier argument_list identifier identifier call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end
Write some text to some output
def _get_variant_regions(items): return list(filter(lambda x: x is not None, [tz.get_in(("config", "algorithm", "variant_regions"), data) for data in items if tz.get_in(["config", "algorithm", "coverage_interval"], data) != "genome"]))
module function_definition identifier parameters identifier block return_statement call identifier argument_list call identifier argument_list lambda lambda_parameters identifier comparison_operator identifier none list_comprehension call attribute identifier identifier argument_list tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier for_in_clause identifier identifier if_clause comparison_operator call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier string string_start string_content string_end
Retrieve variant regions defined in any of the input items.
def _eq(field, value, document): try: return document.get(field, None) == value except TypeError: return False
module function_definition identifier parameters identifier identifier identifier block try_statement block return_statement comparison_operator call attribute identifier identifier argument_list identifier none identifier except_clause identifier block return_statement false
Returns True if the value of a document field is equal to a given value
def list_security_groups(self, retrieve_all=True, **_params): return self.list('security_groups', self.security_groups_path, retrieve_all, **_params)
module function_definition identifier parameters identifier default_parameter identifier true dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier dictionary_splat identifier
Fetches a list of all security groups for a project.
def fetch(bank, key, cachedir): inkey = False key_file = os.path.join(cachedir, os.path.normpath(bank), '{0}.p'.format(key)) if not os.path.isfile(key_file): key_file = os.path.join(cachedir, os.path.normpath(bank) + '.p') inkey = True if not os.path.isfile(key_file): log.debug('Cache file "%s" does not exist', key_file) return {} try: with salt.utils.files.fopen(key_file, 'rb') as fh_: if inkey: return __context__['serial'].load(fh_)[key] else: return __context__['serial'].load(fh_) except IOError as exc: raise SaltCacheError( 'There was an error reading the cache file "{0}": {1}'.format( key_file, exc ) )
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier false expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list identifier if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier binary_operator call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier true if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement dictionary try_statement block with_statement with_clause with_item as_pattern call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block if_statement identifier block return_statement subscript call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier identifier else_clause block return_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier
Fetch information from a file.
def bind(self, container): def clone(prototype): if prototype.is_bound(): raise RuntimeError('Cannot `bind` a bound extension.') cls = type(prototype) args, kwargs = prototype.__params instance = cls(*args, **kwargs) instance.container = weakref.proxy(container) return instance instance = clone(self) for name, ext in inspect.getmembers(self, is_extension): setattr(instance, name, ext.bind(container)) return instance
module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier return_statement identifier expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier block expression_statement call identifier argument_list identifier identifier call attribute identifier identifier argument_list identifier return_statement identifier
Get an instance of this Extension to bind to `container`.
def _create_default_tiles(self): for value, background, text in self.DEFAULT_TILES: self.tiles[value] = self._make_tile(value, background, text)
module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list identifier identifier identifier
Create all default tiles, as defined above.
def tech_requirement(self) -> Optional[UnitTypeId]: if self._proto.tech_requirement == 0: return None if self._proto.tech_requirement not in self._game_data.units: return None return UnitTypeId(self._proto.tech_requirement)
module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block if_statement comparison_operator attribute attribute identifier identifier identifier integer block return_statement none if_statement comparison_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier block return_statement none return_statement call identifier argument_list attribute attribute identifier identifier identifier
Tech-building requirement of buildings - may work for units but unreliably
def _init_idxs_float(self, usr_hdrs): self.idxs_float = [ Idx for Hdr, Idx in self.hdr2idx.items() if Hdr in usr_hdrs and Hdr in self.float_hdrs]
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list if_clause boolean_operator comparison_operator identifier identifier comparison_operator identifier attribute identifier identifier
List of indexes whose values will be floats.
def _jws_header(keyid, algorithm): data = { 'typ': 'JWT', 'alg': algorithm.name, 'kid': keyid } datajson = json.dumps(data, sort_keys=True).encode('utf8') return base64url_encode(datajson)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier keyword_argument identifier true identifier argument_list string string_start string_content string_end return_statement call identifier argument_list identifier
Produce a base64-encoded JWS header.
def bdd(*keywords): settings = _personal_settings().data _storybook().with_params( **{"python version": settings["params"]["python version"]} ).only_uninherited().shortcut(*keywords).play()
module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier attribute call identifier argument_list identifier expression_statement call attribute call attribute call attribute call attribute call identifier argument_list identifier argument_list dictionary_splat dictionary pair string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier argument_list list_splat identifier identifier argument_list
Run tests matching keywords.
def proxy_it(request, port): websocket_proxy = request.registry.settings.get("pyramid_notebook.websocket_proxy", "") if websocket_proxy.strip(): r = DottedNameResolver() websocket_proxy = r.maybe_resolve(websocket_proxy) if "upgrade" in request.headers.get("connection", "").lower(): if websocket_proxy: return websocket_proxy(request, port) else: raise RuntimeError("Websocket proxy support is not configured.") proxy_app = WSGIProxyApplication(port) return request.get_response(proxy_app)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier argument_list block if_statement identifier block return_statement call identifier argument_list identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier
Proxy HTTP request to upstream IPython Notebook Tornado server.
def startLoop(): def _ipython_loop_asyncio(kernel): loop = asyncio.get_event_loop() def kernel_handler(): kernel.do_one_iteration() loop.call_later(kernel._poll_interval, kernel_handler) loop.call_soon(kernel_handler) try: if not loop.is_running(): loop.run_forever() finally: if not loop.is_running(): loop.run_until_complete(loop.shutdown_asyncgens()) loop.close() patchAsyncio() loop = asyncio.get_event_loop() if not loop.is_running(): from ipykernel.eventloops import register_integration, enable_gui register_integration('asyncio')(_ipython_loop_asyncio) enable_gui('asyncio')
module function_definition identifier parameters block function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list function_definition identifier parameters block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier try_statement block if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list finally_clause block if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator call attribute identifier identifier argument_list block import_from_statement dotted_name identifier identifier dotted_name identifier dotted_name identifier expression_statement call call identifier argument_list string string_start string_content string_end argument_list identifier expression_statement call identifier argument_list string string_start string_content string_end
Use nested asyncio event loop for Jupyter notebooks.
def remove_object(self, key): state = self.state for layer in state.layers: state.layers[layer].pop(key, None) state.need_redraw = True
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier none expression_statement assignment attribute identifier identifier true
remove an object by key from all layers
def text(self, string, x, y, color, *, font_name="font5x8.bin"): if not self._font or self._font.font_name != font_name: self._font = BitmapFont() w = self._font.font_width for i, char in enumerate(string): self._font.draw_char(char, x + (i * (w + 1)), y, self, color)
module function_definition identifier parameters identifier identifier identifier identifier identifier keyword_separator default_parameter identifier string string_start string_content string_end block if_statement boolean_operator not_operator attribute identifier identifier comparison_operator attribute attribute identifier identifier identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment identifier attribute attribute identifier identifier identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier binary_operator identifier parenthesized_expression binary_operator identifier parenthesized_expression binary_operator identifier integer identifier identifier identifier
text is not yet implemented
def center(self): bounds = self.bounds x = (bounds[1] + bounds[0])/2 y = (bounds[3] + bounds[2])/2 z = (bounds[5] + bounds[4])/2 return [x, y, z]
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator subscript identifier integer subscript identifier integer integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator subscript identifier integer subscript identifier integer integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator subscript identifier integer subscript identifier integer integer return_statement list identifier identifier identifier
Center of the bounding box around all data present in the scene
def update(self, automation): self._automation.update( {k: automation[k] for k in automation if self._automation.get(k)})
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list dictionary_comprehension pair identifier subscript identifier identifier for_in_clause identifier identifier if_clause call attribute attribute identifier identifier identifier argument_list identifier
Update the internal automation json.
def best(self): return pd.Series( { "name": self.best_dist.name, "params": self.best_param, "sse": self.best_sse, } )
module function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier
The resulting best-fit distribution, its parameters, and SSE.
def _get_at_from_session(self): try: return self.request.session['oauth_%s_access_token' % get_token_prefix( self.request_token_url)] except KeyError: raise OAuthError( _('No access token saved for "%s".') % get_token_prefix(self.request_token_url))
module function_definition identifier parameters identifier block try_statement block return_statement subscript attribute attribute identifier identifier identifier binary_operator string string_start string_content string_end call identifier argument_list attribute identifier identifier except_clause identifier block raise_statement call identifier argument_list binary_operator call identifier argument_list string string_start string_content string_end call identifier argument_list attribute identifier identifier
Get the saved access token for private resources from the session.
async def destroy(self, container = None): if container is None: container = RoutineContainer(self.scheduler) if self.queue is not None: await container.syscall_noreturn(syscall_removequeue(self.scheduler.queue, self.queue)) self.queue = None
module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement await call attribute identifier identifier argument_list call identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier none
Destroy the created subqueue to change the behavior back to Lock
def timedelta_seconds(timedelta): return (timedelta.total_seconds() if hasattr(timedelta, "total_seconds") else timedelta.days * 24 * 3600 + timedelta.seconds + timedelta.microseconds / 1000000.)
module function_definition identifier parameters identifier block return_statement parenthesized_expression conditional_expression call attribute identifier identifier argument_list call identifier argument_list identifier string string_start string_content string_end binary_operator binary_operator binary_operator binary_operator attribute identifier identifier integer integer attribute identifier identifier binary_operator attribute identifier identifier float
Returns the total timedelta duration in seconds.
def scorable_block_completion(sender, **kwargs): if not waffle.waffle().is_enabled(waffle.ENABLE_COMPLETION_TRACKING): return course_key = CourseKey.from_string(kwargs['course_id']) block_key = UsageKey.from_string(kwargs['usage_id']) block_cls = XBlock.load_class(block_key.block_type) if XBlockCompletionMode.get_mode(block_cls) != XBlockCompletionMode.COMPLETABLE: return if getattr(block_cls, 'has_custom_completion', False): return user = User.objects.get(id=kwargs['user_id']) if kwargs.get('score_deleted'): completion = 0.0 else: completion = 1.0 if not kwargs.get('grader_response'): BlockCompletion.objects.submit_completion( user=user, course_key=course_key, block_key=block_key, completion=completion, )
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement not_operator call attribute call attribute identifier identifier argument_list identifier argument_list attribute identifier identifier block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator call attribute identifier identifier argument_list identifier attribute identifier identifier block return_statement if_statement call identifier argument_list identifier string string_start string_content string_end false block return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier float else_clause block expression_statement assignment identifier float if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
When a problem is scored, submit a new BlockCompletion for that block.
def create_logger(self): name = "bors" if hasattr(self, "name"): name = self.name self.log = logging.getLogger(name) try: lvl = self.conf.get_log_level() except AttributeError: lvl = self.context.get("log_level", None) self.log.setLevel(getattr(logging, lvl, logging.INFO))
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list except_clause identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end none expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier identifier attribute identifier identifier
Generates a logger instance from the singleton
def events_list(self): evt = [] evt.extend(events.NEPALI_EVENTS[self.month, self.day]) evt.extend(events.ENGLISH_EVENTS[self.en_date.month, self.en_date.day]) return evt
module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier return_statement identifier
Returns the events today
def handle_m2m_user(self, sender, instance, **kwargs): self.handle_save(instance.user.__class__, instance.user)
module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier
Handle many to many relationships for user field
def quit(self): response = self.run() == Gtk.ResponseType.YES self.destroy() return response
module function_definition identifier parameters identifier block expression_statement assignment identifier comparison_operator call attribute identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier
Run the "are you sure" dialog for quitting Guake
def pass_verbosity(f): def new_func(*args, **kwargs): kwargs['verbosity'] = click.get_current_context().verbosity return f(*args, **kwargs) return update_wrapper(new_func, f)
module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute call attribute identifier identifier argument_list identifier return_statement call identifier argument_list list_splat identifier dictionary_splat identifier return_statement call identifier argument_list identifier identifier
Marks a callback as wanting to receive the verbosity as a keyword argument.
def _populateComboBoxes(self, row): logger.debug("_populateComboBoxes") for comboBox in self._comboBoxes: comboBox.clear() if not self.rtiIsSliceable: for comboBoxNr, comboBox in enumerate(self._comboBoxes): comboBox.addItem('', userData=None) comboBox.setEnabled(False) return nDims = self._rti.nDims nCombos = len(self._comboBoxes) for comboBoxNr, comboBox in enumerate(self._comboBoxes): comboBox.addItem(FAKE_DIM_NAME, userData = FAKE_DIM_OFFSET + comboBoxNr) for dimNr in range(nDims): comboBox.addItem(self._rti.dimensionNames[dimNr], userData=dimNr) if nDims >= nCombos: curIdx = nDims + 1 - nCombos + comboBoxNr else: curIdx = comboBoxNr + 1 if comboBoxNr < nDims else 0 assert 0 <= curIdx <= nDims + 1, \ "curIdx should be <= {}, got {}".format(nDims + 1, curIdx) comboBox.setCurrentIndex(curIdx) comboBox.setEnabled(True)
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list if_statement not_operator attribute identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_end keyword_argument identifier none expression_statement call attribute identifier identifier argument_list false return_statement expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier binary_operator identifier identifier for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list subscript attribute attribute identifier identifier identifier identifier keyword_argument identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier binary_operator binary_operator binary_operator identifier integer identifier identifier else_clause block expression_statement assignment identifier conditional_expression binary_operator identifier integer comparison_operator identifier identifier integer assert_statement comparison_operator integer identifier binary_operator identifier integer call attribute string string_start string_content string_end identifier argument_list binary_operator identifier integer identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list true
Populates the combo boxes with values of the repo tree item
def _get_localized_field_checks(self): localized_fields_checks = [] for localized_field in self.instance.localized_fields: if self.cleaned_data.get(localized_field) is None: continue f = getattr(self.instance.__class__, localized_field, None) if f and f.unique: if f.unique: local_name = get_real_fieldname(localized_field, self.language) localized_fields_checks.append((localized_field, local_name)) return localized_fields_checks
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute attribute identifier identifier identifier block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list identifier none block continue_statement expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier identifier none if_statement boolean_operator identifier attribute identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list tuple identifier identifier return_statement identifier
Get the checks we must perform for the localized fields.
def problem_serializing(value, e=None): from mo_logs import Log try: typename = type(value).__name__ except Exception: typename = "<error getting name>" try: rep = text_type(repr(value)) except Exception as _: rep = None if rep == None: Log.error( "Problem turning value of type {{type}} to json", type=typename, cause=e ) else: Log.error( "Problem turning value ({{value}}) of type {{type}} to json", value=rep, type=typename, cause=e )
module function_definition identifier parameters identifier default_parameter identifier none block import_from_statement dotted_name identifier dotted_name identifier try_statement block expression_statement assignment identifier attribute call identifier argument_list identifier identifier except_clause identifier block expression_statement assignment identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier none if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
THROW ERROR ABOUT SERIALIZING
def _deserialize(cls, key, value, fields): converter = cls._get_converter_for_field(key, None, fields) return converter.deserialize(value)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier none identifier return_statement call attribute identifier identifier argument_list identifier
Marshal incoming data into Python objects.
def _transform_i(self, x, i): x = self._shift_or_mirror_into_invertible_i(x, i) lb = self._lb[self._index(i)] ub = self._ub[self._index(i)] al = self._al[self._index(i)] au = self._au[self._index(i)] if x < lb + al: return lb + (x - (lb - al))**2 / 4 / al elif x < ub - au: return x elif x < ub + 3 * au: return ub - (x - (ub + au))**2 / 4 / au else: assert False return ub + au - (x - (ub + au))
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier subscript attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier binary_operator identifier identifier block return_statement binary_operator identifier binary_operator binary_operator binary_operator parenthesized_expression binary_operator identifier parenthesized_expression binary_operator identifier identifier integer integer identifier elif_clause comparison_operator identifier binary_operator identifier identifier block return_statement identifier elif_clause comparison_operator identifier binary_operator identifier binary_operator integer identifier block return_statement binary_operator identifier binary_operator binary_operator binary_operator parenthesized_expression binary_operator identifier parenthesized_expression binary_operator identifier identifier integer integer identifier else_clause block assert_statement false return_statement binary_operator binary_operator identifier identifier parenthesized_expression binary_operator identifier parenthesized_expression binary_operator identifier identifier
return transform of x in component i
def atlas_peer_set_zonefile_inventory( peer_hostport, peer_inv, peer_table=None ): with AtlasPeerTableLocked(peer_table) as ptbl: if peer_hostport not in ptbl.keys(): return None ptbl[peer_hostport]['zonefile_inv'] = peer_inv return peer_inv
module function_definition identifier parameters identifier identifier default_parameter identifier none block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block if_statement comparison_operator identifier call attribute identifier identifier argument_list block return_statement none expression_statement assignment subscript subscript identifier identifier string string_start string_content string_end identifier return_statement identifier
Set this peer's zonefile inventory
def reportTime(t, options, field=None): if options.pretty: return prettyTime(t, field=field) else: if field is not None: return "%*.2f" % (field, t) else: return "%.2f" % t
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement attribute identifier identifier block return_statement call identifier argument_list identifier keyword_argument identifier identifier else_clause block if_statement comparison_operator identifier none block return_statement binary_operator string string_start string_content string_end tuple identifier identifier else_clause block return_statement binary_operator string string_start string_content string_end identifier
Given t seconds, report back the correct format as string.
def nodes_aws(c_obj): aws_nodes = [] try: aws_nodes = c_obj.list_nodes() except BaseHTTPError as e: abort_err("\r HTTP Error with AWS: {}".format(e)) aws_nodes = adj_nodes_aws(aws_nodes) return aws_nodes
module function_definition identifier parameters identifier block expression_statement assignment identifier list try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier return_statement identifier
Get node objects from AWS.
def select_observations(self, name): return [n for n in self.get_obs_nodes() if n.obsname==name]
module function_definition identifier parameters identifier identifier block return_statement list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause comparison_operator attribute identifier identifier identifier
Returns nodes whose instrument-band matches 'name'
def unhandled(self, key): self.key = key self.size = self.tui.get_cols_rows() if self.search is True: if self.enter is False and self.no_matches is False: if len(key) == 1 and key.isprintable(): self.search_string += key self._search() elif self.enter is True and not self.search_string: self.search = False self.enter = False return if not self.urls and key not in "Qq": return if self.help_menu is False: try: self.keys[key]() except KeyError: pass
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator attribute identifier identifier true block if_statement boolean_operator comparison_operator attribute identifier identifier false comparison_operator attribute identifier identifier false block if_statement boolean_operator comparison_operator call identifier argument_list identifier integer call attribute identifier identifier argument_list block expression_statement augmented_assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list elif_clause boolean_operator comparison_operator attribute identifier identifier true not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier false return_statement if_statement boolean_operator not_operator attribute identifier identifier comparison_operator identifier string string_start string_content string_end block return_statement if_statement comparison_operator attribute identifier identifier false block try_statement block expression_statement call subscript attribute identifier identifier identifier argument_list except_clause identifier block pass_statement
Handle other keyboard actions not handled by the ListBox widget.
def exponential_backoff(fn, sleeptime_s_max=30 * 60): sleeptime_ms = 500 while True: if fn(): return True else: print('Sleeping {} ms'.format(sleeptime_ms)) time.sleep(sleeptime_ms / 1000.0) sleeptime_ms *= 2 if sleeptime_ms / 1000.0 > sleeptime_s_max: return False
module function_definition identifier parameters identifier default_parameter identifier binary_operator integer integer block expression_statement assignment identifier integer while_statement true block if_statement call identifier argument_list block return_statement true else_clause block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator identifier float expression_statement augmented_assignment identifier integer if_statement comparison_operator binary_operator identifier float identifier block return_statement false
Calls `fn` until it returns True, with an exponentially increasing wait time between calls
def create_turtle(self, id, shape, model_init, color_init): assert id not in self.id_to_shape data = self._create_turtle(id, shape, model_init, color_init) self.id_to_shape[id] = shape return data
module function_definition identifier parameters identifier identifier identifier identifier identifier block assert_statement comparison_operator identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier
Create a slice of memory for turtle data storage
def _filter_disabled_regions(contents): contents = list(contents) in_backticks = False contents_len = len(contents) index = 0 while index < contents_len: character = contents[index] if character == "`": if ((index + 2) < contents_len and "".join(contents[index:index + 3]) == "```"): in_backticks = not in_backticks index += 3 continue if in_backticks: contents[index] = " " index += 1 return "".join(contents)
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier false expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier integer while_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block if_statement parenthesized_expression boolean_operator comparison_operator parenthesized_expression binary_operator identifier integer identifier comparison_operator call attribute string string_start string_end identifier argument_list subscript identifier slice identifier binary_operator identifier integer string string_start string_content string_end block expression_statement assignment identifier not_operator identifier expression_statement augmented_assignment identifier integer continue_statement if_statement identifier block expression_statement assignment subscript identifier identifier string string_start string_content string_end expression_statement augmented_assignment identifier integer return_statement call attribute string string_start string_end identifier argument_list identifier
Filter regions that are contained in back-ticks.
def collect(self): if redis is None: self.log.error('Unable to import module redis') return {} for nick in self.instances.keys(): (host, port, unix_socket, auth) = self.instances[nick] self.collect_instance(nick, host, int(port), unix_socket, auth)
module function_definition identifier parameters identifier block if_statement comparison_operator identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement dictionary for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment tuple_pattern identifier identifier identifier identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier call identifier argument_list identifier identifier identifier
Collect the stats from the redis instance and publish them.
def numericise_all(input, empty2zero=False, default_blank="", allow_underscores_in_numeric_literals=False): return [numericise(s, empty2zero, default_blank, allow_underscores_in_numeric_literals) for s in input]
module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier string string_start string_end default_parameter identifier false block return_statement list_comprehension call identifier argument_list identifier identifier identifier identifier for_in_clause identifier identifier
Returns a list of numericised values from strings
def make_patch(self): path = [self.arcs[0].start_point()] for a in self.arcs: if a.direction: vertices = Path.arc(a.from_angle, a.to_angle).vertices else: vertices = Path.arc(a.to_angle, a.from_angle).vertices vertices = vertices[np.arange(len(vertices) - 1, -1, -1)] vertices = vertices * a.radius + a.center path = path + list(vertices[1:]) codes = [1] + [4] * (len(path) - 1) return PathPatch(Path(path, codes))
module function_definition identifier parameters identifier block expression_statement assignment identifier list call attribute subscript attribute identifier identifier integer identifier argument_list for_statement identifier attribute identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier attribute call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier else_clause block expression_statement assignment identifier attribute call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier expression_statement assignment identifier subscript identifier call attribute identifier identifier argument_list binary_operator call identifier argument_list identifier integer unary_operator integer unary_operator integer expression_statement assignment identifier binary_operator binary_operator identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier binary_operator identifier call identifier argument_list subscript identifier slice integer expression_statement assignment identifier binary_operator list integer binary_operator list integer parenthesized_expression binary_operator call identifier argument_list identifier integer return_statement call identifier argument_list call identifier argument_list identifier identifier
Retuns a matplotlib PathPatch representing the current region.
def parse_stations(html): html = html.replace('SLs.sls=', '').replace(';SLs.showSuggestion();', '') html = json.loads(html) return html['suggestions']
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement subscript identifier string string_start string_content string_end
Strips JS code, loads JSON
def setPriority(self, queue, priority): q = self.queueindex[queue] self.queues[q[0]].removeSubQueue(q[1]) newPriority = self.queues.setdefault(priority, CBQueue.MultiQueue(self, priority)) q[0] = priority newPriority.addSubQueue(q[1])
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute subscript attribute identifier identifier subscript identifier integer identifier argument_list subscript identifier integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript identifier integer identifier expression_statement call attribute identifier identifier argument_list subscript identifier integer
Set priority of a sub-queue
def _render(item: ConfigItem, indent: str = "") -> str: optional = item.default_value != _NO_DEFAULT if is_configurable(item.annotation): rendered_annotation = f"{item.annotation} (configurable)" else: rendered_annotation = str(item.annotation) rendered_item = "".join([ indent, "// " if optional else "", f'"{item.name}": ', rendered_annotation, f" (default: {item.default_value} )" if optional else "", f" // {item.comment}" if item.comment else "", "\n" ]) return rendered_item
module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier string string_start string_end type identifier block expression_statement assignment identifier comparison_operator attribute identifier identifier identifier if_statement call identifier argument_list attribute identifier identifier block expression_statement assignment identifier string string_start interpolation attribute identifier identifier string_content string_end else_clause block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_end identifier argument_list list identifier conditional_expression string string_start string_content string_end identifier string string_start string_end string string_start string_content interpolation attribute identifier identifier string_content string_end identifier conditional_expression string string_start string_content interpolation attribute identifier identifier string_content string_end identifier string string_start string_end conditional_expression string string_start string_content interpolation attribute identifier identifier string_end attribute identifier identifier string string_start string_end string string_start string_content escape_sequence string_end return_statement identifier
Render a single config item, with the provided indent
def sorted_filetype_items(self): processed_types = [] file_type_items = deque(self.config['file_types'].items()) while len(file_type_items): filetype, filetype_info = file_type_items.popleft() requirements = filetype_info.get('requires') if requirements is not None: missing = [req for req in requirements if req not in processed_types] if missing: file_type_items.append((filetype, filetype_info)) continue processed_types.append(filetype) yield filetype, filetype_info
module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list while_statement call identifier argument_list identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list tuple identifier identifier continue_statement expression_statement call attribute identifier identifier argument_list identifier expression_statement yield expression_list identifier identifier
Sort the instance's filetypes in using order.
def init(cls, *args, **kwargs): instance = cls() instance._values.update(dict(*args, **kwargs)) return instance
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier
Initialize the config like as you would a regular dict.
def copy(self): c = matrix() c.tt = self.tt.copy() c.n = self.n.copy() c.m = self.m.copy() return c
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list return_statement identifier
Creates a copy of the TT-matrix
def calculate_grid(self): if self.grid is None: self.grid = self.get_wellseries(self.get_grid()) if self.grid_transposed is None: self.grid_transposed = self.get_wellseries( self.transpose( self.get_grid()))
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list
Calculates and stores grid structure
def compute(self, write_to_tar=True): data = self._get_all_data(self.start_date, self.end_date) logging.info('Computing timeseries for {0} -- ' '{1}.'.format(self.start_date, self.end_date)) full, full_dt = self._compute_full_ts(data) full_out = self._full_to_yearly_ts(full, full_dt) reduced = self._apply_all_time_reductions(full_out) logging.info("Writing desired gridded outputs to disk.") for dtype_time, data in reduced.items(): data = _add_metadata_as_attrs(data, self.var.units, self.var.description, self.dtype_out_vert) self.save(data, dtype_time, dtype_out_vert=self.dtype_out_vert, save_files=True, write_to_tar=write_to_tar) return self
module function_definition identifier parameters identifier default_parameter identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list identifier attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true keyword_argument identifier identifier return_statement identifier
Perform all desired calculations on the data and save externally.
def unsubscribe(self, topic): if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("UNSUBSCRIBE: %s", topic) return self.send_unsubscribe(False, [utf8encode(topic)])
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list false list call identifier argument_list identifier
Unsubscribe to some topic.
def run_after_async(seconds, func, *args, **kwargs): t = Timer(seconds, func, args, kwargs) t.daemon = True t.start() return t
module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier expression_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list return_statement identifier
Run the function after seconds asynchronously.
async def log_source(self, **params): if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"Missed required fields"} database = client[settings.DBNAME] source_collection = database[settings.SOURCE] await source_collection.update({"public_key":params.get("public_key")}, {"$addToSet":{"source":params.get("source")}}, upsert=True) return {"result": "ok"}
module function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end if_statement not_operator identifier block return_statement dictionary pair string string_start string_content string_end integer pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript identifier attribute identifier identifier expression_statement assignment identifier subscript identifier attribute identifier identifier expression_statement await call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true return_statement dictionary pair string string_start string_content string_end string string_start string_content string_end
Logging users request sources
def primal_name(func, wrt): if not isinstance(func, types.FunctionType): raise TypeError(func) varnames = six.get_function_code(func).co_varnames return PRIMAL_NAME.format(func.__name__, ''.join(varnames[i] for i in wrt))
module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block raise_statement call identifier argument_list identifier expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier call attribute string string_start string_end identifier generator_expression subscript identifier identifier for_in_clause identifier identifier
Name for the primal of a function.
def _clean_args(sys_argv, args): base = [x for x in sys_argv if x.startswith("-") or not args.datadir == os.path.abspath(os.path.expanduser(x))] base = [x for x in base if x not in set(["--minimize-disk"])] if "--nodata" in base: base.remove("--nodata") else: base.append("--data") return base
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end not_operator comparison_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator identifier call identifier argument_list list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier
Remove data directory from arguments to pass to upgrade function.
def rmrf(items, verbose=True): "Silently remove a list of directories or files" if isinstance(items, str): items = [items] for item in items: if verbose: print("Removing {}".format(item)) shutil.rmtree(item, ignore_errors=True) try: os.remove(item) except FileNotFoundError: pass
module function_definition identifier parameters identifier default_parameter identifier true block expression_statement string string_start string_content string_end if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier for_statement identifier identifier block if_statement identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause identifier block pass_statement
Silently remove a list of directories or files
def draw(self): self.context.set_line_cap(cairo.LINE_CAP_SQUARE) self.context.save() self.context.rectangle(*self.rect) self.context.clip() cell_borders = CellBorders(self.cell_attributes, self.key, self.rect) borders = list(cell_borders.gen_all()) borders.sort(key=attrgetter('width', 'color')) for border in borders: border.draw(self.context) self.context.restore()
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list list_splat attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list keyword_argument identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list
Draws cell border to context
def ls(obj=None): if obj is None: import builtins all = builtins.__dict__.copy() all.update(globals()) objlst = sorted(conf.layers, key=lambda x:x.__name__) for o in objlst: print("%-10s : %s" %(o.__name__,o.name)) else: if isinstance(obj, type) and issubclass(obj, Packet): for f in obj.fields_desc: print("%-10s : %-20s = (%s)" % (f.name, f.__class__.__name__, repr(f.default))) elif isinstance(obj, Packet): for f in obj.fields_desc: print("%-10s : %-20s = %-15s (%s)" % (f.name, f.__class__.__name__, repr(getattr(obj,f.name)), repr(f.default))) if not isinstance(obj.payload, NoPayload): print("--") ls(obj.payload) else: print("Not a packet class. Type 'ls()' to list packet classes.")
module function_definition identifier parameters default_parameter identifier none block if_statement comparison_operator identifier none block import_statement dotted_name identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier keyword_argument identifier lambda lambda_parameters identifier attribute identifier identifier for_statement identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier else_clause block if_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute attribute identifier identifier identifier call identifier argument_list attribute identifier identifier elif_clause call identifier argument_list identifier identifier block for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute attribute identifier identifier identifier call identifier argument_list call identifier argument_list identifier attribute identifier identifier call identifier argument_list attribute identifier identifier if_statement not_operator call identifier argument_list attribute identifier identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list attribute identifier identifier else_clause block expression_statement call identifier argument_list string string_start string_content string_end
List available layers, or infos on a given layer
def generate_sample_json(): check = EpubCheck(samples.EPUB3_VALID) with open(samples.RESULT_VALID, 'wb') as jsonfile: jsonfile.write(check._stdout) check = EpubCheck(samples.EPUB3_INVALID) with open(samples.RESULT_INVALID, 'wb') as jsonfile: jsonfile.write(check._stdout)
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list attribute identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier
Generate sample json data for testing
def plot_cable_length(stats, plotpath): f, axarr = plt.subplots(2, 2, sharex=True) stats.hist(column=['Length of MV overhead lines'], bins=5, alpha=0.5, ax=axarr[0, 0]) stats.hist(column=['Length of MV underground cables'], bins=5, alpha=0.5, ax=axarr[0, 1]) stats.hist(column=['Length of LV overhead lines'], bins=5, alpha=0.5, ax=axarr[1, 0]) stats.hist(column=['Length of LV underground cables'], bins=5, alpha=0.5, ax=axarr[1, 1]) plt.savefig(os.path.join(plotpath, 'Histogram_cable_line_length.pdf'))
module function_definition identifier parameters identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list integer integer keyword_argument identifier true expression_statement call attribute identifier identifier argument_list keyword_argument identifier list string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier float keyword_argument identifier subscript identifier integer integer expression_statement call attribute identifier identifier argument_list keyword_argument identifier list string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier float keyword_argument identifier subscript identifier integer integer expression_statement call attribute identifier identifier argument_list keyword_argument identifier list string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier float keyword_argument identifier subscript identifier integer integer expression_statement call attribute identifier identifier argument_list keyword_argument identifier list string string_start string_content string_end keyword_argument identifier integer keyword_argument identifier float keyword_argument identifier subscript identifier integer integer expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end
Cable length per MV grid district
def _structure_union(self, obj, union): union_params = union.__args__ if NoneType in union_params: if obj is None: return None if len(union_params) == 2: other = ( union_params[0] if union_params[1] is NoneType else union_params[1] ) return self._structure_func.dispatch(other)(obj, other) handler = self._union_registry.get(union) if handler is not None: return handler(obj, union) cl = self._dis_func_cache(union)(obj) return self._structure_func.dispatch(cl)(obj, cl)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier identifier block if_statement comparison_operator identifier none block return_statement none if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier parenthesized_expression conditional_expression subscript identifier integer comparison_operator subscript identifier integer identifier subscript identifier integer return_statement call call attribute attribute identifier identifier identifier argument_list identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement call identifier argument_list identifier identifier expression_statement assignment identifier call call attribute identifier identifier argument_list identifier argument_list identifier return_statement call call attribute attribute identifier identifier identifier argument_list identifier argument_list identifier identifier
Deal with converting a union.
def collect_ansible_classes(): def trace_calls(frame, event, arg): if event != 'call': return try: _locals = inspect.getargvalues(frame).locals if 'self' not in _locals: return _class = _locals['self'].__class__ _class_repr = repr(_class) if 'ansible' not in _class_repr: return ANSIBLE_CLASSES[_class] = True except (AttributeError, TypeError): pass print "Gathering classes" sys.settrace(trace_calls) main()
module function_definition identifier parameters block function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block return_statement try_statement block expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block return_statement expression_statement assignment identifier attribute subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block return_statement expression_statement assignment subscript identifier identifier true except_clause tuple identifier identifier block pass_statement print_statement string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list
Run playbook and collect classes of ansible that are run.
def _or_query(self, term_list, field, field_type): term_list = [self._term_query(term, field, field_type) for term in term_list] return xapian.Query(xapian.Query.OP_OR, term_list)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier identifier identifier for_in_clause identifier identifier return_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier identifier
Joins each item of term_list decorated by _term_query with an OR.
def _merge_lib_dict(d1, d2): for required, requirings in d2.items(): if required in d1: d1[required].update(requirings) else: d1[required] = requirings return None
module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement call attribute subscript identifier identifier identifier argument_list identifier else_clause block expression_statement assignment subscript identifier identifier identifier return_statement none
Merges lib_dict `d2` into lib_dict `d1`
def provides_defaults_for(self, rule: 'Rule', **values: Any) -> bool: defaults_match = all( values[key] == self.defaults[key] for key in self.defaults if key in values ) return self != rule and bool(self.defaults) and defaults_match
module function_definition identifier parameters identifier typed_parameter identifier type string string_start string_content string_end typed_parameter dictionary_splat_pattern identifier type identifier type identifier block expression_statement assignment identifier call identifier generator_expression comparison_operator subscript identifier identifier subscript attribute identifier identifier identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator identifier identifier return_statement boolean_operator boolean_operator comparison_operator identifier identifier call identifier argument_list attribute identifier identifier identifier
Returns true if this rule provides defaults for the argument and values.
def home(self): self.command(c.LCD_RETURNHOME) self._cursor_pos = (0, 0) c.msleep(2)
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier tuple integer integer expression_statement call attribute identifier identifier argument_list integer
Set cursor to initial position and reset any shifting.
def on_episode_end(self, episode, logs={}): for callback in self.callbacks: if callable(getattr(callback, 'on_episode_end', None)): callback.on_episode_end(episode, logs=logs) else: callback.on_epoch_end(episode, logs=logs)
module function_definition identifier parameters identifier identifier default_parameter identifier dictionary block for_statement identifier attribute identifier identifier block if_statement call identifier argument_list call identifier argument_list identifier string string_start string_content string_end none block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier
Called at end of each episode for each callback in callbackList
def _load(self, keyframe=True): if self._cached: return pages = self.pages if not pages: return if not self._indexed: self._seek(-1) if not self._cache: return fh = self.parent.filehandle if keyframe is not None: keyframe = self._keyframe for i, page in enumerate(pages): if isinstance(page, inttypes): fh.seek(page) page = self._tiffpage(self.parent, index=i, keyframe=keyframe) pages[i] = page self._cached = True
module function_definition identifier parameters identifier default_parameter identifier true block if_statement attribute identifier identifier block return_statement expression_statement assignment identifier attribute identifier identifier if_statement not_operator identifier block return_statement if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list unary_operator integer if_statement not_operator attribute identifier identifier block return_statement expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment subscript identifier identifier identifier expression_statement assignment attribute identifier identifier true
Read all remaining pages from file.
def query_jobs_schedule(repo_name, revision, auth): url = "%s/%s/rev/%s?format=json" % (SELF_SERVE, repo_name, revision) LOG.debug("About to fetch %s" % url) req = requests.get(url, auth=auth, timeout=TCP_TIMEOUT) if req.status_code not in [200]: return [] return req.json()
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier list integer block return_statement list return_statement call attribute identifier identifier argument_list
Query Buildapi for jobs.
def toggle_highlighting(self, state): if self.editor is not None: if state: self.highlight_matches() else: self.clear_matches()
module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block if_statement identifier block expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list
Toggle the 'highlight all results' feature
def setup(cfg): this_module = sys.modules[__name__] for name, value in cfg.items(): if hasattr(this_module, name): setattr(this_module, name, value)
module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call identifier argument_list identifier identifier block expression_statement call identifier argument_list identifier identifier identifier
set up the global configuration from an object
def edit(self): if platform.system().lower() == 'windows': os.startfile(str(self.config_file)) else: if platform.system().lower() == 'darwin': call = 'open' else: call = 'xdg-open' subprocess.call([call, self.config_file])
module function_definition identifier parameters identifier block if_statement comparison_operator call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier else_clause block if_statement comparison_operator call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list list identifier attribute identifier identifier
Edit file with default os application.
def save_model(model, output_file): if not output_file: return with open(output_file, 'wb') as f: pickle.dump(model, f) print("Saved model to file '{}'.".format(output_file))
module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier
Save model to output_file, if given
def fit_transform(self, input, **fit_kwargs): self.fit(input, **fit_kwargs) X = self.transform(input) return X
module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier dictionary_splat identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier
Execute fit and transform in sequence.
def _dhash(self, params): m = hashlib.new('md5') m.update(self.hash.encode('utf-8')) for key in sorted(params.keys()): h_string = ('%s-%s' % (key, params[key])).encode('utf-8') m.update(h_string) return m.hexdigest()
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute parenthesized_expression binary_operator string string_start string_content string_end tuple identifier subscript identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list
Generate hash of the dictionary object.
def _get_files_modified(): cmd = "git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD" _, files_modified, _ = run(cmd) extensions = [re.escape(ext) for ext in list(SUPPORTED_FILES) + [".rst"]] test = "(?:{0})$".format("|".join(extensions)) return list(filter(lambda f: re.search(test, f), files_modified))
module function_definition identifier parameters block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier binary_operator call identifier argument_list identifier list string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement call identifier argument_list call identifier argument_list lambda lambda_parameters identifier call attribute identifier identifier argument_list identifier identifier identifier
Get the list of modified files that are Python or Jinja2.
def delete_collection(db_name, collection_name, host='localhost', port=27017): client = MongoClient("mongodb://%s:%d" % (host, port)) client[db_name].drop_collection(collection_name)
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier integer block expression_statement assignment identifier call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement call attribute subscript identifier identifier identifier argument_list identifier
Almost exclusively for testing.
def field_function(self, type_code, func_name): assert func_name in ('to_json', 'from_json') name = "field_%s_%s" % (type_code.lower(), func_name) return getattr(self, name)
module function_definition identifier parameters identifier identifier identifier block assert_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end tuple call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier identifier
Return the field function.
def debug_complete(): if not 'uniqueId' in request.args: raise ExperimentError('improper_inputs') else: unique_id = request.args['uniqueId'] mode = request.args['mode'] try: user = Participant.query.\ filter(Participant.uniqueid == unique_id).one() user.status = COMPLETED user.endhit = datetime.datetime.now() db_session.add(user) db_session.commit() except: raise ExperimentError('error_setting_worker_complete') else: if (mode == 'sandbox' or mode == 'live'): return render_template('closepopup.html') else: return render_template('complete.html')
module function_definition identifier parameters block if_statement not_operator comparison_operator string string_start string_content string_end attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute call attribute attribute identifier identifier line_continuation identifier argument_list comparison_operator attribute identifier identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list except_clause block raise_statement call identifier argument_list string string_start string_content string_end else_clause block if_statement parenthesized_expression boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_content string_end block return_statement call identifier argument_list string string_start string_content string_end else_clause block return_statement call identifier argument_list string string_start string_content string_end
Debugging route for complete.
def process_temperature_sensors(helper, session): snmp_result_temp_sensor_names = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_location'], "temperature sensors") snmp_result_temp_sensor_states = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_status'], "temperature sensors") snmp_result_temp_sensor_values = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_reading'], "temperature sensors") for i, _result in enumerate(snmp_result_temp_sensor_states): helper.update_status( helper, probe_check(snmp_result_temp_sensor_names[i], snmp_result_temp_sensor_states[i], "Temperature sensor")) if i < len(snmp_result_temp_sensor_values): helper.add_metric(label=snmp_result_temp_sensor_names[i] + " -Celsius-", value=float(snmp_result_temp_sensor_values[i]) / 10)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier subscript identifier string string_start string_content string_end string string_start string_content string_end for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier call identifier argument_list subscript identifier identifier subscript identifier identifier string string_start string_content string_end if_statement comparison_operator identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier binary_operator subscript identifier identifier string string_start string_content string_end keyword_argument identifier binary_operator call identifier argument_list subscript identifier identifier integer
process the temperature sensors
def _set_overlay_verify(name, overlay_path, config_path): global DEBUG if os.path.exists(config_path): print("Config path already exists! Not moving forward") print("config_path: {0}".format(config_path)) return -1 os.makedirs(config_path) with open(config_path + "/dtbo", 'wb') as outfile: with open(overlay_path, 'rb') as infile: shutil.copyfileobj(infile, outfile) time.sleep(0.2) if name == "CUST": return 0 elif name == "PWM0": if os.path.exists(PWMSYSFSPATH): if DEBUG: print("PWM IS LOADED!") return 0 else: if DEBUG: print("ERROR LOAIDNG PWM0") return 1 elif name == "SPI2": if os.listdir(SPI2SYSFSPATH) != "": if DEBUG: print("SPI2 IS LOADED!") return 0 else: if DEBUG: print("ERROR LOADING SPI2") return 0
module function_definition identifier parameters identifier identifier identifier block global_statement identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement unary_operator integer expression_statement call attribute identifier identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_list binary_operator identifier string string_start string_content string_end string string_start string_content string_end as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list float if_statement comparison_operator identifier string string_start string_content string_end block return_statement integer elif_clause comparison_operator identifier string string_start string_content string_end block if_statement call attribute attribute identifier identifier identifier argument_list identifier block if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end return_statement integer else_clause block if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end return_statement integer elif_clause comparison_operator identifier string string_start string_content string_end block if_statement comparison_operator call attribute identifier identifier argument_list identifier string string_start string_end block if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end return_statement integer else_clause block if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end return_statement integer
_set_overlay_verify - Function to load the overlay and verify it was setup properly
def to_json(df, columns, confidence={}): records = [] display_cols = list(columns.keys()) if not display_cols: display_cols = list(df.columns) bounds = {} for c in confidence: bounds[c] = { "min": df[confidence[c]["lower"]].min(), "max": df[confidence[c]["upper"]].max(), "lower": confidence[c]["lower"], "upper": confidence[c]["upper"] } labels = {} for c in display_cols: if "label" in columns[c]: labels[c] = columns[c]["label"] else: labels[c] = c for i, row in df.iterrows(): row_ = DataTable.format_row(row, bounds, columns) records.append({labels[c]: row_[c] for c in display_cols}) return { "data": records, "columns": [{"data": labels[c]} for c in display_cols] }
module function_definition identifier parameters identifier identifier default_parameter identifier dictionary block expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment subscript identifier identifier dictionary pair string string_start string_content string_end call attribute subscript identifier subscript subscript identifier identifier string string_start string_content string_end identifier argument_list pair string string_start string_content string_end call attribute subscript identifier subscript subscript identifier identifier string string_start string_content string_end identifier argument_list pair string string_start string_content string_end subscript subscript identifier identifier string string_start string_content string_end pair string string_start string_content string_end subscript subscript identifier identifier string string_start string_content string_end expression_statement assignment identifier dictionary for_statement identifier identifier block if_statement comparison_operator string string_start string_content string_end subscript identifier identifier block expression_statement assignment subscript identifier identifier subscript subscript identifier identifier string string_start string_content string_end else_clause block expression_statement assignment subscript identifier identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list dictionary_comprehension pair subscript identifier identifier subscript identifier identifier for_in_clause identifier identifier return_statement dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end list_comprehension dictionary pair string string_start string_content string_end subscript identifier identifier for_in_clause identifier identifier
Transforms dataframe to properly formatted json response