code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def devpiserver_cmdline_run(xom): if xom.config.args.theme == 'semantic-ui': xom.config.args.theme = resource_filename('devpi_semantic_ui', '') xom.log.info("Semantic UI Theme loaded")
Load theme when `theme` parameter is 'semantic-ui'.
def optimize_thumbnail(thumbnail): try: optimize_command = settings.THUMBNAIL_OPTIMIZE_COMMAND[ determinetype(thumbnail.path)] if not optimize_command: return except (TypeError, KeyError, NotImplementedError): return storage = thumbnail.storage try: ...
Optimize thumbnail images by removing unnecessary data
def _split_overlays(self): "Splits overlays inside the HoloMap into list of HoloMaps" if not issubclass(self.type, CompositeOverlay): return None, self.clone() item_maps = OrderedDict() for k, overlay in self.data.items(): for key, el in overlay.items(): ...
Splits overlays inside the HoloMap into list of HoloMaps
def interval(best,lo=np.nan,hi=np.nan): return [float(best),[float(lo),float(hi)]]
Pythonized interval for easy output to yaml
def handle_ctrlchan(handler, msg, nick, send): with handler.db.session_scope() as db: parser = init_parser(send, handler, nick, db) try: cmdargs = parser.parse_args(msg) except arguments.ArgumentException as e: err_str = r"invalid choice: .* \(choose from 'quote', 'he...
Handle the control channel.
def _move_cursor_to_line(self, line): last_line = self._text_edit.document().blockCount() - 1 self._cursor.clearSelection() self._cursor.movePosition(self._cursor.End) to_insert = '' for i in range(line - last_line): to_insert += '\n' if to_insert: ...
Moves the cursor to the specified line, if possible.
def retrieve_keys(bucket, key, prefix='', postfix='', delim='/', directories=False, recursive=False): if key and prefix: assert key.endswith(delim) key += prefix if not key.endswith(delim) and key: if BotoClient.check_prefix(bucket, key + delim, deli...
Retrieve keys from a bucket
def serialize(self, tag): handler = getattr(self, f'serialize_{tag.serializer}', None) if handler is None: raise TypeError(f'Can\'t serialize {type(tag)!r} instance') return handler(tag)
Return the literal representation of a tag.
def devices(self): if self._all_devices: return self._all_devices self._all_devices = {} self._all_devices['cameras'] = [] self._all_devices['base_station'] = [] url = DEVICES_ENDPOINT data = self.query(url) for device in data.get('data'): ...
Return all devices on Arlo account.
def op_gen(mcode): gen = op_tbl[mcode[0]] ret = gen[0] nargs = len(gen) i = 1 while i < nargs: if i < len(mcode): ret |= (mcode[i]&gen[i][0]) << gen[i][1] i += 1 return ret
Generate a machine instruction using the op gen table.
def uts46_remap(domain, std3_rules=True, transitional=False): from .uts46data import uts46data output = u"" try: for pos, char in enumerate(domain): code_point = ord(char) uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (...
Re-map the characters in the string according to UTS46 processing.
def balance(self, account: Address): return self.web3.eth.getBalance(to_checksum_address(account), 'pending')
Return the balance of the account of the given address.
def maybe_start_recording(tokens, index): if _is_really_comment(tokens, index): return _CommentedLineRecorder(index, tokens[index].line) return None
Return a new _CommentedLineRecorder when it is time to record.
def move_backward(self): self.at(ardrone.at.pcmd, True, 0, self.speed, 0, 0)
Make the drone move backwards.
def perform_get_or_create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) process = serializer.validated_data.get('process') process_input = request.data.get('input', {}) fill_with_defaults(process_inp...
Perform "get_or_create" - return existing object if found.
def _update_asset_content_url_to_match_id(self, ac): mgr = self._provider_session._get_provider_manager('REPOSITORY') aas = mgr.get_asset_admin_session_for_repository(self._provider_session._catalog_id, proxy=self._provider_session._proxy) ...
update the ac URL value to match the ident
def bind_blueprint(pale_api_module, flask_blueprint): if not isinstance(flask_blueprint, Blueprint): raise TypeError(("pale.flask_adapter.bind_blueprint expected the " "passed in flask_blueprint to be an instance of " "Blueprint, but it was an instance of %s...
Binds an implemented pale API module to a Flask Blueprint.
def command_line_runner(): filename = sys.argv[-1] if not filename.endswith(".rst"): print("ERROR! Please enter a ReStructuredText filename!") sys.exit() print(rst_to_json(file_opener(filename)))
I run functions from the command-line!
def _read_indexlist(self, name): setattr(self, '_' + name, [self._timeline[int(i)] for i in self.db.lrange('site:{0}'.format(name), 0, -1)])
Read a list of indexes.
def get(self, x, y): for piece in self.pieces: if (piece.x, piece.y) == (x, y): return piece
Return piece placed at the provided coordinates.
def web_hook_receiver(sender, **kwargs): deployment = Deployment.objects.get(pk=kwargs.get('deployment_id')) hooks = deployment.web_hooks if not hooks: return for hook in hooks: data = payload_generator(deployment) deliver_hook(deployment, hook.url, data)
Generic receiver for the web hook firing piece.
def _erase_in_line(self, type_of=0): row = self.display[self.y] attrs = self.attributes[self.y] if type_of == 0: row = row[:self.x] + u" " * (self.size[1] - self.x) attrs = attrs[:self.x] + [self.default_attributes] * (self.size[1] - self.x) elif type_of == 1: ...
Erases the row in a specific way, depending on the type_of.
def inject_experiment(): exp = Experiment(session) return dict(experiment=exp, env=os.environ)
Inject experiment and enviroment variables into the template context.
def locate_run(output, target, no_newline): from .config import ConfigStore cfstore = ConfigStore() path = getattr(cfstore, "{0}_path".format(target)) output.write(path) if not no_newline: output.write("\n")
Print location of RASH related file.
def DocbookSlidesPdf(env, target, source=None, *args, **kw): target, source = __extend_targets_sources(target, source) __init_xsl_stylesheet(kw, env, '$DOCBOOK_DEFAULT_XSL_SLIDESPDF', ['slides','fo','plain.xsl']) __builder = __select_builder(__lxml_builder, __libxml2_builder, __xsltproc_builder) result ...
A pseudo-Builder, providing a Docbook toolchain for PDF slides output.
def pretty_print_table(headers, rows): table = make_table(headers=headers, rows=rows) pretty_print_table_instance(table)
Pretty print a table from headers and rows.
def bounds_window(bounds, affine): w, s, e, n = bounds row_start, col_start = rowcol(w, n, affine) row_stop, col_stop = rowcol(e, s, affine, op=math.ceil) return (row_start, row_stop), (col_start, col_stop)
Create a full cover rasterio-style window
def from_dir(cwd): "Context manager to ensure in the cwd directory." import os curdir = os.getcwd() try: os.chdir(cwd) yield finally: os.chdir(curdir)
Context manager to ensure in the cwd directory.
def entries_in_tree_oid(self, prefix, tree_oid): try: tree = self.git.get_object(tree_oid) except KeyError: log.warning("Couldn't find object {0}".format(tree_oid)) return empty else: return frozenset(self.entries_in_tree(prefix, tree))
Find the tree at this oid and return entries prefixed with ``prefix``
def upload(ctx): settings.add_cli_options(ctx.cli_options, settings.TransferAction.Upload) ctx.initialize(settings.TransferAction.Upload) specs = settings.create_upload_specifications( ctx.cli_options, ctx.config) del ctx.cli_options for spec in specs: blobxfer.api.Uploader( ...
Upload files to Azure Storage
def next_weekday(weekday): ix = WEEKDAYS.index(weekday) if ix == len(WEEKDAYS)-1: return WEEKDAYS[0] return WEEKDAYS[ix+1]
Returns the name of the weekday after the given weekday name.
def delete(self): response = self.hv.delete_request('people/' + str(self.id)) return response
Deletes the person immediately.
def convert_svg(svgstr, size, filepath, target): "convert to PDF or PNG" if target == "PDF": img = cairo.PDFSurface(filepath, size, size) elif target == "PNG": img = cairo.ImageSurface(cairo.FORMAT_ARGB32, size, size) else: system.exit("unknown file type conversion") ctx = cairo.Context...
convert to PDF or PNG
def prt_line_detail(self, prt, line): values = line.split('\t') self._prt_line_detail(prt, values)
Print line header and values in a readable format.
def getBinding(self): wsdl = self.getService().getWSDL() return wsdl.bindings[self.binding]
Return the Binding object that is referenced by this port.
def construct_wishart(self,v,X): self.adjust_prior(list(range(int((len(self.latent_variables.z_list)-self.ylen-(self.ylen**2-self.ylen)/2)), int(len(self.latent_variables.z_list)))), fam.InverseWishart(v,X))
Constructs a Wishart prior for the covariance matrix
def countNeighbours(self, cell): count = 0 y, x = cell y = y % self.y_grid x = x % self.x_grid y1 = (y - 1) % self.y_grid y2 = (y + 1) % self.y_grid x1 = (x - 1) % self.x_grid x2 = (x + 1) % self.x_grid cell = y, x for neighbour in product(...
Return the number active neighbours within one positions away from cell
def cublasDtrmv(handle, uplo, trans, diag, n, A, lda, x, inx): status = _libcublas.cublasDtrmv_v2(handle, _CUBLAS_FILL_MODE[uplo], _CUBLAS_OP[trans], _CUBLAS_DIAG[diag], ...
Matrix-vector product for real triangular matrix.
def encode(obj): if hasattr(obj, '__id__'): return msgpack.ExtType(ExtType.REF, msgpack.packb(obj.__id__)) return obj
Encode an object for proper decoding by Java or ObjC
def check(projects): log = logging.getLogger('ciu') log.info('{0} top-level projects to check'.format(len(projects))) print('Finding and checking dependencies ...') blockers = dependencies.blockers(projects) print('') for line in message(blockers): print(line) print('') for line ...
Check the specified projects for Python 3 compatibility.
def __insert_wrapper(func): def check_func(self, key, new_item, instance=0): if key not in self.keys(): raise KeyError("%s not a key in label" % (key)) if not isinstance(new_item, (list, OrderedMultiDict)): raise TypeError("The new item must be a list or P...
Make sure the arguments given to the insert methods are correct
def weed(self): _ext = [k for k in self._dict.keys() if k not in self.c_param] for k in _ext: del self._dict[k]
Get rid of key value pairs that are not standard
def read_data(fo, writer_schema, reader_schema=None): record_type = extract_record_type(writer_schema) logical_type = extract_logical_type(writer_schema) if reader_schema and record_type in AVRO_TYPES: if writer_schema == reader_schema: reader_schema = None else: matc...
Read data from file object according to schema.
def run_script(self, requires, script_name): ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name self.require(requires)[0].run_script(script_name, ns)
Locate distribution for `requires` and run `script_name` script
def class_name_str(obj, skip_parent=False): rt = str(type(obj)).split(" ")[1][1:-2] if skip_parent: rt = rt.split(".")[-1] return rt
return's object's class name as string
def reject(self, func): return self._wrap(list(filter(lambda val: not func(val), self.obj)))
Return all the elements for which a truth test fails.
def handle_simple_sequencing(func): from .assessment import assessment_utilities def wrapper(*args, **kwargs): if 'create_assessment_part' in func.__name__: result = func(*args, **kwargs) assessment_utilities.update_parent_sequence_map(result) elif func.__name__ == 'delet...
decorator, deal with simple sequencing cases
def dump(self, directory): payload = '{}:{}'.format(self.fingerprint, self.serialized_bytes_length) safe_file_dump(self._path(directory), payload=payload)
Dump this Digest object adjacent to the given directory.
def follow_logs(instance_log_id, sleep_duration=1): cur_idx = 0 job_terminated = False while not job_terminated: log_file_contents = ResourceClient().get_content(instance_log_id) print_output = log_file_contents[cur_idx:] job_terminated = any(terminal_output in print_output for termi...
Follow the logs until Job termination.
def _encode_query(query): if query == '': return query query_args = [] for query_kv in query.split('&'): k, v = query_kv.split('=') query_args.append(k + "=" + quote(v.encode('utf-8'))) return '&'.join(query_args)
Quote all values of a query string.
def pkey_get(clas,pool_or_cursor,*vals): "lookup by primary keys in order" pkey = clas.PKEY.split(',') if len(vals)!=len(pkey): raise ValueError("%i args != %i-len primary key for %s"%(len(vals),len(pkey),clas.TABLE)) rows = list(clas.select(pool_or_cursor,**dict(zip(pkey,vals)))) if not rows: ...
lookup by primary keys in order
def GetMetricMetadata(): return [ stats_utils.CreateCounterMetadata("grr_client_unknown"), stats_utils.CreateCounterMetadata("grr_decoding_error"), stats_utils.CreateCounterMetadata("grr_decryption_error"), stats_utils.CreateCounterMetadata("grr_authenticated_messages"), stats_utils.Crea...
Returns a list of MetricMetadata for communicator-related metrics.
def _handle_token(self, token): try: return _HANDLERS[type(token)](self, token) except KeyError: err = "_handle_token() got unexpected {0}" raise ParserError(err.format(type(token).__name__))
Handle a single token.
def tree(): session = AppAggregate().open_session() classes = session.query(AssetClass).all() root = [] for ac in classes: if ac.parentid is None: root.append(ac) print_row("id", "asset class", "allocation", "level") print(f"-------------------------------") for ac in roo...
Display a tree of asset classes
def nx_all_nodes_between(graph, source, target, data=False): import utool as ut if source is None: sources = list(ut.nx_source_nodes(graph)) assert len(sources) == 1, ( 'specify source if there is not only one') source = sources[0] if target is None: sinks = list(...
Find all nodes with on paths between source and target.
def save_load(jid, load, minions=None): conn, mdb = _get_conn(ret=None) to_save = _safe_copy(load) if PYMONGO_VERSION > _LooseVersion('2.3'): mdb.jobs.insert_one(to_save) else: mdb.jobs.insert(to_save)
Save the load for a given job id
def parse_safari (url_data): from ..bookmarks.safari import parse_bookmark_data for url, name in parse_bookmark_data(url_data.get_content()): url_data.add_url(url, name=name)
Parse a Safari bookmark file.
def prepend(self, *nodes: Union[str, AbstractNode]) -> None: node = _to_node_list(nodes) if self.firstChild: self.insertBefore(node, self.firstChild) else: self.appendChild(node)
Insert new nodes before first child node.
def nullval(cls): d = dict(cls.__dict__.items()) for k in d: d[k] = 0 d['sl'] = cls.sl d[cls.level] = 0 return cls(**d)
Create a new instance where all of the values are 0
def add_child(self, child, modify=False): SceneGraph.add_child(self, child) self.notify() if modify: child._model_matrix_transform[:] = trans.inverse_matrix(self.model_matrix_global) child._normal_matrix_transform[:] = trans.inverse_matrix(self.normal_matrix_global)
Adds an object as a child in the scene graph. With modify=True, model_matrix_transform gets change from identity and prevents the changes of the coordinates of the child
def _collect_external_resources(self, resource_attr): external_resources = [] for _, cls in sorted(Model.model_class_reverse_map.items(), key=lambda arg: arg[0]): external = getattr(cls, resource_attr, None) if isinstance(external, string_types): if external not i...
Collect external resources set on resource_attr attribute of all models.
def PrintRanges(type, name, ranges): print "static const %s %s[] = {" % (type, name,) for lo, hi in ranges: print "\t{ %d, %d }," % (lo, hi) print "};"
Print the ranges as an array of type named name.
def _parse_user_flags(): try: idx = list(sys.argv).index('--user-flags') user_flags_file = sys.argv[idx + 1] except (ValueError, IndexError): user_flags_file = '' if user_flags_file and os.path.isfile(user_flags_file): from ryu.utils import _import_module_file _import...
Parses user-flags file and loads it to register user defined options.
def find_conda(): USER_HOME = os.path.expanduser('~') CONDA_HOME = os.environ.get('CONDA_HOME', '') PROGRAMDATA = os.environ.get('PROGRAMDATA', '') search_paths = [ join(PROGRAMDATA, 'miniconda2', 'scripts'), join(PROGRAMDATA, 'miniconda3', 'scripts'), join(USER_HOME, 'miniconda2...
Try to find conda on the system
def save(self): with open(self.store_file_path, 'w') as fh: fh.write(json.dumps(self.store, indent=4))
Write the store dict to a file specified by store_file_path
def connect_socket(self, sock: socket.socket) -> None: try: sock.connect((self._tunnel_host, self._tunnel_port)) except socket.timeout as e: raise ProxyError(self.ERR_PROXY_OFFLINE.format(str(e))) except socket.error as e: raise ProxyError(self.ERR_PROXY_OFFLI...
Setup HTTP tunneling with the configured proxy.
def _create_optimizer_node(self): self.lr_var = tf.Variable(0.0, trainable=False) tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars), self.max_grad_norm) optimizer = tf.train.GradientDescentOptimizer...
Create the optimizer node of the graph.
def _pack(self): data = ByteBuffer() if not hasattr(self, '__fields__'): return data.array for field in self.__fields__: field.encode(self, data) return data.array
Pack the message and return an array.
def close(self, suppress_logging=False): pool_names = list(self.pools) for name in pool_names: self._close(name, suppress_logging)
iterates thru all publisher pools and closes them
def _call(self, x, out=None): wrapped_x = self.prod_op.domain.element([x], cast=False) return self.prod_op(wrapped_x, out=out)
Evaluate all operators in ``x`` and broadcast.
def list_lbaas_l7policies(self, retrieve_all=True, **_params): return self.list('l7policies', self.lbaas_l7policies_path, retrieve_all, **_params)
Fetches a list of all L7 policies for a listener.
def sanitize_word(word): if type(word) == str: try: word = word.decode() except AttributeError: pass word = word.strip() word = re.sub(r'\([^)]*\)', '', word) word = re.sub(r'[ "\'-;.]+', '', unidecode(word)) return word.lower()
sanitize a word by removing its accents, special characters, etc
def signup(self, project_name, email): uri = 'openstack/sign-up' data = { "project_name": project_name, "email": email, } post_body = json.dumps(data) resp, body = self.post(uri, body=post_body) self.expected_success(200, resp.status) body ...
Signup for a new project.
def _update_checksum(self): source_list = [int(octet) for octet in self.source.split(".")] destination_list = [int(octet) for octet in self.destination.split(".")] source_upper = (source_list[0] << 8) + source_list[1] source_lower = (source_list[2] << 8) + sou...
Update the packet checksum to enable integrity check.
def check_address(self, address): if address is None: self.raise_error(InvalidAddress, details='address is None') if all(letter == address[0] for letter in address) or len(address) < self.minFundingAddressLength or ' ' in address: self.raise_error(InvalidAddress, details='address...
Checks an address is not the same character repeated or an empty sequence
def inasafe_sub_analysis_summary_field_value( exposure_key, field, feature, parent): _ = feature, parent project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) project = QgsProject.instance() key = ('{provenance}__{exposure}').format( provenance=pr...
Retrieve a value from field in the specified exposure analysis layer.
def _get_ids_from_hostname(self, hostname): results = self.list_instances(hostname=hostname, mask="id") return [result['id'] for result in results]
List VS ids which match the given hostname.
def _concat(self, first_data, second_data): assert len(first_data) == len( second_data), 'data source should contain the same size' if first_data and second_data: return [ concat( first_data[x], second_data[x], ...
Helper function to concat two NDArrays.
def _get_dirs(user_dir, startup_dir): try: users = os.listdir(user_dir) except WindowsError: users = [] full_dirs = [] for user in users: full_dir = os.path.join(user_dir, user, startup_dir) if os.path.exists(full_dir): full_dirs.append(full_dir) return fu...
Return a list of startup dirs
def _handle_tag_jpegtables(self): obj = _make_object("JPEGTables") assert self._src.read(2) == b'\xFF\xD8' eoimark1 = eoimark2 = None allbytes = [b'\xFF\xD8'] while not (eoimark1 == b'\xFF' and eoimark2 == b'\xD9'): newbyte = self._src.read(1) allbytes.app...
Handle the JPEGTables tag.
def remove_all_nexusport_bindings(): LOG.debug("remove_all_nexusport_bindings() called") session = bc.get_writer_session() session.query(nexus_models_v2.NexusPortBinding).delete() session.flush()
Removes all nexusport bindings.
def _load_rsp(rsp): first = rsp.find('(') + 1 last = rsp.rfind(')') return json.loads(rsp[first:last])
Converts raw Flickr string response to Python dict
def transformer_wikitext103_l16k_memory_v0(): hparams = transformer_wikitext103_l4k_memory_v0() hparams.max_length = 16384 hparams.split_targets_chunk_length = 64 hparams.split_targets_max_chunks = int( hparams.max_length / hparams.split_targets_chunk_length) target_tokens_per_batch = 4096 hparams.bat...
HParams for training languagemodel_wikitext103_l16k with memory.
def extract_images_jbig2(pike, root, log, options): jbig2_groups = defaultdict(list) for pageno, xref, ext in extract_images( pike, root, log, options, extract_image_jbig2 ): group = pageno // options.jbig2_page_group_size jbig2_groups[group].append((xref, ext)) jbig2_groups = { ...
Extract any bitonal image that we think we can improve as JBIG2
def _cmd_up(self): revision = self._get_revision() if not self._rev: self._log(0, "upgrading current revision") else: self._log(0, "upgrading from revision %s" % revision) for rev in self._revisions[int(revision) - 1:]: sql_files = glob.glob(os.path.jo...
Upgrade to a revision
def url(self): "Returns the URL that can be visited to obtain a verifier code" query_string = {'oauth_token': self.oauth_token} if self.scope: query_string['scope'] = self.scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \ urlencode(query_string) return...
Returns the URL that can be visited to obtain a verifier code
def fprint(self, file, indent): return lib.zdir_fprint(self._as_parameter_, coerce_py_file(file), indent)
Print contents of directory to open stream
def skimage_sinogram_space(geometry, volume_space, sinogram_space): padded_size = int(np.ceil(volume_space.shape[0] * np.sqrt(2))) det_width = volume_space.domain.extent[0] * np.sqrt(2) skimage_detector_part = uniform_partition(-det_width / 2.0, det_width / 2.0,...
Create a range adapted to the skimage radon geometry.
def handle_input(self, input_str, place=True, check=False): user = self.get_player() pos = self.validate_input(input_str) if pos[0] == 'u': self.undo(pos[1]) return pos if place: result = self.set_pos(pos, check) return result else:...
Transfer user input to valid chess position
def close_files(self): for name in self: if getattr(self, '_%s_diskflag' % name): file_ = getattr(self, '_%s_file' % name) file_.close()
Close all files with an activated disk flag.
def make_transparent(image): data = image.copy().getdata() modified = [] for item in data: if _check_pixel(item) is True: modified.append((255, 255, 255, 255)) continue modified.append(item) image.putdata(modified) return image
Turn all black pixels in an image into transparent ones
def _get_datetimes(self, timestep=1): start_moy = DateTime(self._month, self._day_of_month).moy if timestep == 1: start_moy = start_moy + 30 num_moys = 24 * timestep return tuple( DateTime.from_moy(start_moy + (i * (1 / timestep) * 60)) for i in xrange...
List of datetimes based on design day date and timestep.
async def addSignalHandlers(self): def sigint(): self.printf('<ctrl-c>') if self.cmdtask is not None: self.cmdtask.cancel() self.loop.add_signal_handler(signal.SIGINT, sigint)
Register SIGINT signal handler with the ioloop to cancel the currently running cmdloop task.
def set(self, key, value, extend=False, **kwargs): self.__setitem__(key, value, extend, **kwargs)
Extended standard set function.
def remove(self, (s, p, o), context=None): named_graph = _get_named_graph(context) query_sets = _get_query_sets_for_object(o) filter_parameters = dict() if named_graph is not None: filter_parameters['context_id'] = named_graph.id if s: filter_parameters['s...
Removes a triple from the store.
def multiCall(*commands, dependent=True, bundle=False, print_result=False, print_commands=False): results = [] dependent_failed = False for command in commands: if not dependent_failed: response = call(command, print_result=print_result, print_co...
Calls the function 'call' multiple times, given sets of commands
def recordset(method): def wrapper(self, *args, **kwargs): if self.__records__ is None: raise ValidationError( 'There are no records in the set.', ) return method(self, *args, **kwargs) return Api.model(wrapper)
Use this to decorate methods that expect a record set.
def add(self, item): if item in self._set: self._fifo.remove(item) elif len(self._set) == self.max_items: self._set.remove(self._fifo.pop(0)) self._fifo.append(item) self._set.add(item)
Add an item to the set discarding the oldest item if necessary.
def update_gradients_diag(self, dL_dKdiag, X): self.variance.gradient = np.sum(dL_dKdiag) self.period.gradient = 0 self.lengthscale.gradient = 0
derivative of the diagonal of the covariance matrix with respect to the parameters.
def delete_node(self, node_id): node = self.get_node(node_id) for e in node['edges']: self.delete_edge_by_id(e) edges = [edge_id for edge_id, edge in list(self.edges.items()) if edge['vertices'][1] == node_id] for e in edges: self.delete_edge_by_id(e) del ...
Removes the node identified by node_id from the graph.