Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
355,600
def update_looks(self): if self.state == : style = {: , : } else: style = {: } for artist in self.artist_list: artist.update(style)
Updates the looks of the gate depending on state.
355,601
def get_object(self, queryset=None): profile, dummy = ForumProfile.objects.get_or_create(user=self.request.user) return profile
Returns the considered object.
355,602
def _empty_cache(self, termlist=None): if termlist is None: for term in six.itervalues(self.terms): term._empty_cache() else: for term in termlist: try: self.terms[term.id]._empty_cache() except Attribut...
Empty the cache associated with each `Term` instance. This method is called when merging Ontologies or including new terms in the Ontology to make sure the cache of each term is cleaned and avoid returning wrong memoized values (such as Term.rchildren() TermLists, which get memoized for...
355,603
def layer_definition_type(layer): layer_purposes = [, ] layer_purpose = [p for p in layer_purposes if p in layer.keywords] if not layer_purpose: return None layer_purpose = layer_purpose[0] return definition(layer.keywords[layer_purpose])
Returned relevant layer definition based on layer purpose. Returned the the correct definition of layer based on its purpose. For example, if a layer have layer_purpose: exposure, and exposure: roads then it will return definition for exposure_roads. That's why it only supports hazard layer or exposur...
355,604
def find_zone_name(data, zone_id): if not isinstance(data, BeautifulSoup): raise TypeError("Function requires BeautilSoup HTML element.") table = data.find(, {: }) table_body = table.find() rows = table_body.find_all(, {: }) for row in rows: if row.get_text().startswith(str(zon...
Find on the HTML document the zone name. # expected result <span class="more_info" \ title="Zone can be renamed on Setup tab">1 - zone1</span>, :param data: BeautifulSoup object :param zone: zone id :return: zone name :rtype: string :raises TypeError: if data is not a BeautifulSoup...
355,605
def string(self, *args): data = self.bytes(*args) if data is not None: return data.rstrip(b"\x00").decode()
return string stored in node
355,606
def get_transfer_history(self, from_block: int, to_block: Optional[int] = None, from_address: Optional[str] = None, to_address: Optional[str] = None, token_address: Optional[str] = None) -> List[Dict[str, any]]: assert from_address or to_address...
Get events for erc20 transfers. At least one of `from_address`, `to_address` or `token_address` must be defined An example of event: { "args": { "from": "0x1Ce67Ea59377A163D47DFFc9BaAB99423BE6EcF1", "to": "0xaE9E15896fd32E59C7d89ce7a95a9352D6ebD70E", ...
355,607
def generate_sections(self): datasets = Dataset.objects.values( ).annotate( upload_count=Count( ) ).order_by() return [ { : dataset[], : get_hub_name_from_slug(dataset[]), ...
Return all hubs, slugs, and upload counts.
355,608
def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file, debug=False): if output_file is None: output_file = tempfile.NamedTemporaryFile().name data_loader = DataLoader(test_file, num_buckets_test, vocab) record = data_l...
Evaluate parser on a data set Parameters ---------- parser : BiaffineParser biaffine parser vocab : ParserVocabulary vocabulary built from data set num_buckets_test : int size of buckets (cluster sentences into this number of clusters) test_batch_size : int batch...
355,609
def _parse_body(self, robj, response, expected_statuses): if response is None: return None status, headers, data = response if not status: m = .format( self._node.host, self._node.http_port) raise RiakError(m) ...
Parse the body of an object response and populate the object.
355,610
def spkw15(handle, body, center, inframe, first, last, segid, epoch, tp, pa, p, ecc, j2flg, pv, gm, j2, radius): handle = ctypes.c_int(handle) body = ctypes.c_int(body) center = ctypes.c_int(center) inframe = stypes.stringToCharP(inframe) first = ctypes.c_double(first) last = cty...
Write an SPK segment of type 15 given a type 15 data record. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw15_c.html :param handle: Handle of an SPK file open for writing. :type handle: int :param body: Body code for ephemeris object. :type body: int :param center: Body code for ...
355,611
def on_service_arrival(self, svc_ref): with self._lock: if self.reference is None: service = self._context.get_service(svc_ref) self.reference = svc_ref self._value.set_service(service) self.__still_valid = Tru...
Called when a service has been registered in the framework :param svc_ref: A service reference
355,612
def cmd_delete(args): major = args.get(0) minor = args.get(1) if major is not None: if major in penStore.data: if minor is None: if len(penStore.data[major]) > 0: if raw_input("are you sure (y/n)? ") not in [, , , ]: return...
Deletes a node
355,613
def check_default_values(section, key, validator=None): if validator is None: validator = Validator() try: validator.get_default_value(section[key]) except KeyError: parents = get_section_path(section) msg = % (key, parents, section[key]) ...
Raise an MissingDefaultError if a value in section does not have a default values :param section: the section of a configspec :type section: section :param key: a key of the section :type key: str :param validator: a Validator object to get the default values :type validator: Validator :ret...
355,614
def quic_graph_lasso_ebic(X, gamma=0): print("QuicGraphicalLassoEBIC with:") print(" mode: path") print(" gamma: {}".format(gamma)) model = QuicGraphicalLassoEBIC(lam=1.0, init_method="cov", gamma=gamma) model.fit(X) print(" len(path lams): {}".format(len(model.path_))) print(" ...
Run QuicGraphicalLassoEBIC with gamma. QuicGraphicalLassoEBIC is a convenience class. Results should be identical to those obtained via quic_graph_lasso_ebic_manual.
355,615
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter(.format( event.data_type)) event_values = event.CopyToDict() http_headers = event_values.get(, None) if http_headers: event_values[] = http_headers.replace(, )...
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
355,616
def close(self): if self._closed: return if self._autoclose: self._transport.close() self._transport._closed.wait() self._transport = None self._closed = True
Close the stream. If *autoclose* was passed to the constructor then the underlying transport will be closed as well.
355,617
def copyWorkitem(self, copied_from, title=None, description=None, prefix=None): copied_wi = self.getWorkitem(copied_from) if title is None: title = copied_wi.title if prefix is not None: title = prefix + title if description...
Create a workitem by copying from an existing one :param copied_from: the to-be-copied workitem id :param title: the new workitem title/summary. If `None`, will copy that from a to-be-copied workitem :param description: the new workitem description. If `None`, will copy ...
355,618
def reportSuspiciousNode(self, nodeName: str, reason=None, code: int = None, offendingMsg=None): logger.warning("{} raised suspicion on node {} for {}; suspicion code " ...
Report suspicion on a node and add it to this node's blacklist. :param nodeName: name of the node to report suspicion on :param reason: the reason for suspicion
355,619
def set_rules(self, rules): self.rules_to_ignore = rules.get("ignore", []) self.rules_to_run = rules.get("apply", [])
Sets the rules to be run or ignored for the audit. Args: rules: a dictionary of the format `{"ignore": [], "apply": []}`. See https://github.com/GoogleChrome/accessibility-developer-tools/tree/master/src/audits Passing `{"apply": []}` or `{}` means to check for all available rule...
355,620
def prev(self, name=None): if self.parent is None or self.index is None: return None for idx in xrange(self.index - 1, -1, -1): if name is None or self.parent[idx].tagname == name: return self.parent[idx]
Returns the previous sibling of this node. :param name: If specified, only consider elements with this tag name :rtype: :class:`XmlElement`
355,621
def dispatch(self, *args, **kwargs): return super(StrainDelete, self).dispatch(*args, **kwargs)
This decorator sets this view to have restricted permissions.
355,622
def _GetLink(self): if self._link is None: self._link = if self.entry_type != definitions.FILE_ENTRY_TYPE_LINK: return self._link link = self._fsapfs_file_entry.symbolic_link_target if link and link[0] != self._file_system.PATH_SEPARATOR: self._link = .format(...
Retrieves the link. Returns: str: path of the linked file.
355,623
def derive_child_context(self, whence): return _HandlerContext( container=self.container, queue=self.queue, field_name=None, annotations=None, depth=self.depth, whence=whence, value=bytearray(), ion_type=N...
Derives a scalar context as a child of the current context.
355,624
def transit_decrypt_data(self, name, ciphertext, context=None, nonce=None, batch_input=None, mount_point=): url = .format(mount_point, name) params = { : ciphertext } if context is not None: params[] = context if nonce is not None: par...
POST /<mount_point>/decrypt/<name> :param name: :type name: :param ciphertext: :type ciphertext: :param context: :type context: :param nonce: :type nonce: :param batch_input: :type batch_input: :param mount_point: :type mou...
355,625
def proximal(self): if self.pointwise_norm.exponent == 1: return proximal_l1(space=self.domain) elif self.pointwise_norm.exponent == 2: return proximal_l1_l2(space=self.domain) else: raise NotImplementedError( )
Return the ``proximal factory`` of the functional. See Also -------- odl.solvers.nonsmooth.proximal_operators.proximal_l1 : `proximal factory` for the L1-norm.
355,626
def find_dupes(paths, exact=False, ignores=None, min_size=0): groups = {: getPaths(paths, ignores)} groups = groupBy(groups, sizeClassifier, , min_size=min_size) groups = groupBy(groups, hashClassifier, , limit=HEAD_SIZE) if exact: groups = groupBy(groups, groupByContent, f...
High-level code to walk a set of paths and find duplicate groups. :param exact: Whether to compare file contents by hash or by reading chunks in parallel. :type exact: :class:`~__builtins__.bool` :param paths: See :meth:`~fastdupes.getPaths` :param ignores: See :meth:`~fastdupes.getP...
355,627
def transformer(data, label): data = mx.image.imresize(data, IMAGE_SIZE, IMAGE_SIZE) data = mx.nd.transpose(data, (2, 0, 1)) data = data.astype(np.float32) / 128.0 - 1 return data, label
data preparation
355,628
def plotOverlaps(vList, w, base="random", k=20): for i,v in enumerate(vList): if i==0: col = "m" label = "Random vector" else: col="c" label = "" if i==1: label="Test images" overlaps = v.matmul(w.t()) sortedOverlaps = overlaps.sort()[0].tolist()[0][::-1] plt....
Given a list of vectors v, compute the overlap of each with the weight matrix w and plot the overlap curves.
355,629
def get_code(self): return "" if not self.is_enabled else (.format(SITE_KEY=self.site_key, THEME=self.theme, TYPE=self.type, SIZE=self.size, TABINDEX=self.tabindex))
Returns the new ReCaptcha code :return:
355,630
def get_beam(self, ra, dec): if self.lat is None: factor = 1 else: factor = np.cos(np.radians(dec - self.lat)) return Beam(self.beam.a / factor, self.beam.b, self.beam.pa)
Determine the beam at the given sky location. Parameters ---------- ra, dec : float The sky coordinates at which the beam is determined. Returns ------- beam : :class:`AegeanTools.fits_image.Beam` A beam object, with a/b/pa in sky coordinates
355,631
def set_peer_authenticated(self, peer, restart_stream = False): with self.lock: self.peer_authenticated = True self.peer = peer if restart_stream: self._restart_stream() self.event(AuthenticatedEvent(self.peer))
Mark the other side of the stream authenticated as `peer` :Parameters: - `peer`: local JID just authenticated - `restart_stream`: `True` when stream should be restarted (needed after SASL authentication) :Types: - `peer`: `JID` - `restart_st...
355,632
def no_loop_in_parents(self, attr1, attr2): parents = Graph() for item in self: if attr1 == "self": obj = item.uuid else: obj = getattr(item, attr1, None) if...
Find loop in dependencies. For now, used with the following attributes : :(self, parents): host dependencies from host object :(host_name, dependent_host_name):\ host dependencies from hostdependencies object :(service_description, dependent_service_description): ...
355,633
def add_molfile(self, molfile, data): if not isinstance(molfile, Molfile): raise ValueError(.format(type(molfile))) if not isinstance(data, dict): raise ValueError(.format(type(data))) entry_ids = sorted(self.keys(), key=lambda x: int(x)) if entry_ids: ...
Add ``Molfile`` and data to ``SDfile`` object. :param molfile: ``Molfile`` instance. :type molfile: :class:`~ctfile.ctfile.Molfile`. :param dict data: Data associated with ``Molfile`` instance. :return: None. :rtype: :py:obj:`None`.
355,634
def initialize(log_file, project_dir=None, debug=False): t be created and the location won print_splash() log.setup_logging(log_file, print_log_location=False, debug=debug) logger = log.get_logger() if project_dir is not None: make_dir(os.path.normpath(project_dir)) logger.info(.form...
Initializes an AbTools pipeline. Initialization includes printing the AbTools splash, setting up logging, creating the project directory, and logging both the project directory and the log location. Args: log_file (str): Path to the log file. Required. project_dir (str): Path to the ...
355,635
def setup(self): self.log.info() if not os.path.exists(self.pathToWorkspace): os.makedirs(self.pathToWorkspace) if not os.path.exists(self.pathToWorkspace + "/qubits_output"): os.makedirs(self.pathToWorkspace + "/qubits_output") spectr...
*setup the workspace in the requested location* **Return:** - ``None``
355,636
def add(self, message): if self._is_stringable(message) or self._is_qstring(message): self.message.append(Text(message)) elif isinstance(message, MessageElement): self.message.append(message) elif isinstance(message, Message): self.message.extend(mess...
Add a MessageElement to the end of the queue. Strings can be passed and are automatically converted in to item.Text() :param message: An element to add to the message queue. :type message: safe.messaging.Message, MessageElement, str
355,637
def new_file(self): file = self.get_untitled_file_name() LOGGER.debug("> Creating file.".format(file)) self.set_file(file, is_modified=False, is_untitled=True) self.__set_document_signals() return file
Creates a new editor file. :return: File name. :rtype: unicode
355,638
def get_pointer(self, name, timeout=None): exist = self._exist(name) isobject = self._isobject(name, exist) if exist == 0: raise Oct2PyError( % name) elif exist == 1: return _make_variable_ptr_instance(self, name) elif isobject: ...
Get a pointer to a named object in the Octave workspace. Parameters ---------- name: str The name of the object in the Octave workspace. timemout: float, optional. Time to wait for response from Octave (per line). Examples -------- ...
355,639
def _assertion(self, matcher, value): if isinstance(value, Expectation): assertion = value._assertion.__get__(self, Expectation) assertion(matcher, value.value) else: hc.assert_that(value, matcher)
Perform the actual assertion for the given matcher and value. Override this method to apply a special configuration when performing the assertion. If the assertion fails it should raise an AssertionError.
355,640
def read_buffer(io, print_output=False, print_func=None): def _print(line): if print_output: if print_func: formatted_...
Reads a file-like buffer object into lines and optionally prints the output.
355,641
def array_to_encoded(array, dtype=None, encoding=): array = np.asanyarray(array) shape = array.shape flat = np.ravel(array) if dtype is None: dtype = array.dtype encoded = {: np.dtype(dtype).str, : shape} if encoding in [, ]: packed = base64.b64encode(fl...
Export a numpy array to a compact serializable dictionary. Parameters ------------ array : array Any numpy array dtype : str or None Optional dtype to encode array encoding : str 'base64' or 'binary' Returns --------- encoded : dict Has keys: 'dtype': str...
355,642
def _prints_status_screen(self): if not PyFunceble.CONFIGURATION["quiet"]: if PyFunceble.CONFIGURATION["less"]: to_print = [ self.tested, self.domain_status, PyFunce...
Logic behind the printing (on screen) when generating status file.
355,643
def create_objective(self, objective_form): collection = JSONClientValidated(, collection=, runtime=self._runtime) if not isinstance(objective_form, ABCObjectiveForm): raise errors.In...
Creates a new ``Objective``. arg: objective_form (osid.learning.ObjectiveForm): the form for this ``Objective`` return: (osid.learning.Objective) - the new ``Objective`` raise: IllegalState - ``objective_form`` already used in a create transaction rai...
355,644
def call_with_search_field(self, name, callback): done = False while not done: def check(*_): if name in self._search_fields: return True self._found_fields = None return False self.ut...
Calls a piece of code with the DOM element that corresponds to a search field of the table. If the callback causes a ``StaleElementReferenceException``, this method will refetch the search fields and try again. Consequently **the callback should be designed to be callable multip...
355,645
def changeSize(self, fromLayerSize, toLayerSize): if toLayerSize <= 0 or fromLayerSize <= 0: raise LayerError(, \ (fromLayerSize, toLayerSize)) dweight = Numeric.zeros((fromLayerSize, toLayerSize), ) wed = Numeric.zeros((fromLayerSize, toLayerS...
Changes the size of the connection depending on the size change of either source or destination layer. Should only be called through Network.changeLayerSize().
355,646
def play(self): if self.status == UNINITIALIZED or self.clip is None: raise RuntimeError("Player uninitialized or no file loaded") if self.status == EOS: logger.debug("End of stream has already been reached") return if self.status in [PLAYING,PAUSED]: logger.warning("Video already...
Start the playback of the video. The playback loop is run in a separate thread, so this function returns immediately. This allows one to implement things such as event handling loops (e.g. check for key presses) elsewhere.
355,647
def getDeviceList(self, skip_on_access_error=False, skip_on_error=False): return list( self.getDeviceIterator( skip_on_error=skip_on_access_error or skip_on_error, ), )
Return a list of all USB devices currently plugged in, as USBDevice instances. skip_on_error (bool) If True, ignore devices which raise USBError. skip_on_access_error (bool) DEPRECATED. Alias for skip_on_error.
355,648
def predict_expectation(self, X, ancillary_X=None): alpha_, beta_ = self._prep_inputs_for_prediction_and_return_scores(X, ancillary_X) v = (alpha_ * np.pi / beta_) / np.sin(np.pi / beta_) v = np.where(beta_ > 1, v, np.nan) return pd.DataFrame(v, index=_get_index(X))
Predict the expectation of lifetimes, :math:`E[T | x]`. Parameters ---------- X: numpy array or DataFrame a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order as the train...
355,649
def paths_list(): paths = set() try: paths.add(os.getcwd()) except FileNotFoundError: log.warning("The current working directory doesnt exist") if sys.platform.startswith("win"): if hasattr(sys, "frozen"): ...
Gets a folder list of possibly available QEMU binaries on the host. :returns: List of folders where Qemu binaries MAY reside.
355,650
def generate(): data_bytes = bytearray(random.getrandbits(8) for i in range(REQID.REQID_SIZE)) return REQID(data_bytes)
Generates a random REQID for request
355,651
def redirect_output(fileobj): old = sys.stdout sys.stdout = fileobj try: yield fileobj finally: sys.stdout = old
Redirect standard out to file.
355,652
def Ntubes_Perrys(DBundle, Do, Ntp, angle=30): rs Handbook [1]_ for estimating the number of tubes in a tube bundle of differing geometries and tube sizes. Claimed accuracy of 24 tubes. Parameters ---------- DBundle : float Outer diameter of tube bundle, [m] Do : int Tube ou...
r'''A rough equation presented in Perry's Handbook [1]_ for estimating the number of tubes in a tube bundle of differing geometries and tube sizes. Claimed accuracy of 24 tubes. Parameters ---------- DBundle : float Outer diameter of tube bundle, [m] Do : int Tube outer diameter...
355,653
def _calcCTRBUF(self): self.ctr_cks = self.encrypt(struct.pack("Q", self.ctr_iv)) self.ctr_iv += 1 self.ctr_pos = 0
Calculates one block of CTR keystream
355,654
def indices_removed(lst, idxs): ret = [item for k,item in enumerate(lst) if k not in idxs] return type(lst)(ret)
Returns a copy of lst with each index in idxs removed.
355,655
def resolve_from_dictionary(dictionary, key_list, default_value=None): try: current_value = dictionary key_list = key_list if isinstance(key_list, list) else [key_list] for key in key_list: current_value = current_value[key] return current_value except KeyError:...
Take value from a given key list from dictionary. Example: given dictionary d, key_list = ['foo', 'bar'], it will try to resolve d['foo']['bar']. If not possible, return default_value. :param dictionary: A dictionary to resolve. :type dictionary: dict :param key_list: A list of key to resolve...
355,656
def admin_required(obj): decorator = request_passes_test(lambda r, *args, **kwargs: r.user.is_superuser) return wrap_object(obj, decorator)
Requires that the user be logged AND be set as a superuser
355,657
def linkify_s_by_module(self, modules): for i in self: links_list = strip_and_uniq(i.modules) new = [] for name in [e for e in links_list if e]: module = modules.find_by_name(name) if module is not None and module.uuid not in new: ...
Link modules to items :param modules: Modules object (list of all the modules found in the configuration) :type modules: alignak.objects.module.Modules :return: None
355,658
def getstatsdict(self, names, default=numpy.nan): return dict(zip(names, self.getstats(names, default=default)))
Get the requested stats as a dictionary. If a requested stat is not an attribute (implying it hasn't been stored), then the default value is returned for that stat. Parameters ---------- names : list of str The names of the stats to get. default : float, opt...
355,659
def decode_network_packet(buf): off = 0 blen = len(buf) while off < blen: ptype, plen = header.unpack_from(buf, off) if plen > blen - off: raise ValueError("Packet longer than amount of data in buffer") if ptype not in _decoders: raise ValueError("Mess...
Decodes a network packet in collectd format.
355,660
def _init_map(self): QuestionTextFormRecord._init_map(self) self.my_osid_object_form._my_map[] = \ self._choices_metadata[][0]
stub
355,661
def die(msg, errlvl=1, prefix="Error: "): stderr("%s%s\n" % (prefix, msg)) sys.exit(errlvl)
Convenience function to write short message to stderr and quit.
355,662
def ion_or_solid_comp_object(formula): m = re.search(r"\[([^\[\]]+)\]|\(aq\)", formula) if m: comp_obj = Ion.from_formula(formula) elif re.search(r"\(s\)", formula): comp_obj = Composition(formula[:-3]) else: comp_obj = Composition(formula) return comp_obj
Returns either an ion object or composition object given a formula. Args: formula: String formula. Eg. of ion: NaOH(aq), Na[+]; Eg. of solid: Fe2O3(s), Fe(s), Na2O Returns: Composition/Ion object
355,663
def _take_action(self): return not self.unless() return not self.unless
Determines whether to perform the action or not. Checks whether or not an action should be taken. This is determined by the truthy value for the unless parameter. If unless is a callback method, it will be invoked with no parameters in order to determine whether or not the action should...
355,664
def imagetransformer_base_10l_8h_big_uncond_dr03_dan_64_2d(): hparams = image_transformer2d_base() hparams.unconditional = True hparams.hidden_size = 512 hparams.batch_size = 1 hparams.img_len = 64 hparams.num_heads = 8 hparams.filter_size = 2048 hparams.batch_size = 1 hparams.max_length = 3075 h...
big 1d model for unconditional generation on imagenet.
355,665
def current_ioloop(io_loop): orig_loop = tornado.ioloop.IOLoop.current() io_loop.make_current() try: yield finally: orig_loop.make_current()
A context manager that will set the current ioloop to io_loop for the context
355,666
def is_invalid_date(d): if not isinstance(d, DATE_TYPES): return False if d.year < 1970 or d.year >= 2100: return True
Return boolean to indicate whether date is invalid, None if valid, False if not a date >>> import datetime >>> is_invalid_date(datetime.datetime(1970, 1, 1, 0, 0, 1)) >>> is_invalid_date(datetime.datetime(1970, 1, 1)) >>> is_invalid_date(datetime.datetime(1969, 12, 31, 23, 59, 59, 999999)) True ...
355,667
def trim_disconnected_blobs(im, inlets): r temp = sp.zeros_like(im) temp[inlets] = True labels, N = spim.label(im + temp) im = im ^ (clear_border(labels=labels) > 0) return im
r""" Removes foreground voxels not connected to specified inlets Parameters ---------- im : ND-array The array to be trimmed inlets : ND-array of tuple of indices The locations of the inlets. Any voxels *not* connected directly to the inlets will be trimmed Returns ...
355,668
def update_athlete(self, city=None, state=None, country=None, sex=None, weight=None): params = {: city, : state, : country, : sex} params = {k: v for (k, v) in params.items() if v is not None} if weight is not None: param...
Updates the properties of the authorized athlete. http://strava.github.io/api/v3/athlete/#update :param city: City the athlete lives in :param state: State the athlete lives in :param country: Country the athlete lives in :param sex: Sex of the athlete :param weight: We...
355,669
def setup_from_yamlfile(self, yamlfile, output_shell=False): self.logger.debug( + yamlfile) with open(yamlfile, ) as yamlfd: yamlconfig = yaml.load(yamlfd) for instance in yamlconfig[]: self.add_instance(instance[].upper(), ...
Setup from yaml config @param yamlfile: path to yaml config file @type yamlfile: str @param output_shell: write output from this connection to standard output @type output_shell: bool
355,670
def to_fasta_str(self, line_width=50, include_coords=True): res = ">" + self.name if include_coords: res += ":" + str(self.start) + "-" + str(self.end) res += " (" + str(self.remaining) + ")" m_str = self.meta_data_to_string() if m_str: res += (" " + m_str) res += "\n" for...
:return: string representation of this sequence object in fasta format
355,671
def fail(self, key, **kwargs): try: msg = self.error_messages[key] except KeyError: class_name = self.__class__.__name__ msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) raise Assert...
A helper method that simply raises a `ValidationError`.
355,672
def rectify_partial_form_field(base_field, partial_form_fields): base_field.label = base_field.help_text = for fieldset in partial_form_fields: if not isinstance(fieldset, (list, tuple)): fieldset = [fieldset] for field in fieldset: base_field.validators.append...
In base_field reset the attributes label and help_text, since they are overriden by the partial field. Additionally, from the list, or list of lists of partial_form_fields append the bound validator methods to the given base field.
355,673
async def series(self): items = [] for i in await self.items: if i.type == : items.append(i) elif hasattr(i, ): items.extend(await i.series) return items
list of series in the collection |force| |coro| Returns ------- list of type :class:`embypy.objects.Series`
355,674
def ret(self, retn_target=None): if retn_target is None: return self.pop() return_target_index = self._find_return_target(retn_target) if return_target_index is not None: o = self while return_target_index >= 0: o...
Pop one or many call frames from the stack. This method is called when returning from a function in CFG recovery. :param int retn_target: The target to return to. :return: None
355,675
def _default_transpose_size(input_shape, stride, kernel_shape=None, padding=SAME): if not input_shape: raise TypeError("input_shape is None; if using Sonnet, are you sure you " "have connected the module to inputs?") input_length = len(input_shape) stride = _...
Returns default (maximal) output shape for a transpose convolution. In general, there are multiple possible output shapes that a transpose convolution with a given `input_shape` can map to. This function returns the output shape which evenly divides the stride to produce the input shape in a forward convolutio...
355,676
def chmod(path, mode, operator=, recursive=False): =+- if mode > 0o777 and operator != : raise ValueError() if operator == : mode_ = path.stat().st_mode | mode elif operator == : mode_ = path.stat().st_mode & ~mode else: mode_ = mode if path.is_symlink(): ...
Change file mode bits. When recursively chmodding a directory, executable bits in ``mode`` are ignored when applying to a regular file. E.g. ``chmod(path, mode=0o777, recursive=True)`` would apply ``mode=0o666`` to regular files. Symlinks are ignored. Parameters ---------- path : ~pathlib...
355,677
def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None): req = Request( method=method....
Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the...
355,678
def _return_response_and_status_code(response): if response.status_code == requests.codes.ok: return dict(results=response.json(), response_code=response.status_code) elif response.status_code == 204: return dict(error=, response_code=response.status_code) elif respo...
Output the requests response JSON and status code :rtype : dict :param response: requests response object :return: dict containing the JSON response and/or the status code with error string.
355,679
def drop_database(self, name, force=False): if not force or self.exists_database(name): tables = self.list_tables(database=name) udfs = self.list_udfs(database=name) udas = self.list_udas(database=name) else: tables = [] udfs = [] ...
Drop an Impala database. Parameters ---------- name : string Database name force : bool, default False If False and there are any tables in this database, raises an IntegrityError
355,680
def peak_signal_to_noise_ratio(true, pred): return 10.0 * tf.log(1.0 / mean_squared_error(true, pred)) / tf.log(10.0)
Image quality metric based on maximal signal power vs. power of the noise. Args: true: the ground truth image. pred: the predicted image. Returns: peak signal to noise ratio (PSNR)
355,681
def _handle_usecols(self, columns, usecols_key): if self.usecols is not None: if callable(self.usecols): col_indices = _evaluate_usecols(self.usecols, usecols_key) elif any(isinstance(u, str) for u in self.usecols): if len(columns) > 1: ...
Sets self._col_indices usecols_key is used if there are string usecols.
355,682
def Run(self, unused_arg): logging.debug("Disabling service") win32serviceutil.ChangeServiceConfig( None, config.CONFIG["Nanny.service_name"], startType=win32service.SERVICE_DISABLED) svc_config = QueryService(config.CONFIG["Nanny.service_name"]) if svc_config[1] == win32se...
This kills us with no cleanups.
355,683
def get_params_and_defaults(param_list, db): return [[p, d] for p, d in db.get_all_values_of_all_params().items()]
Deduce [parameter, default] pairs from simulations available in the db. Args: param_list (list): List of parameters to query for. db (DatabaseManager): Database where to query for defaults.
355,684
def find_missing_modules(): missing_modules = [] for module in MODULES: try: __import__(module[1]) except ImportError: missing_modules.append(module) return missing_modules
look for dependency that setuptools cannot check or that are too painful to install with setuptools
355,685
def to_graphml(graph: BELGraph, path: Union[str, BinaryIO]) -> None: rv = nx.MultiDiGraph() for node in graph: rv.add_node(node.as_bel(), function=node.function) for u, v, key, edge_data in graph.edges(data=True, keys=True): rv.add_edge( u.as_bel(), v.as_bel(),...
Write this graph to GraphML XML file using :func:`networkx.write_graphml`. The .graphml file extension is suggested so Cytoscape can recognize it.
355,686
def set_image(self, user, image_path): _, ext = os.path.splitext(image_path) shutil.copy(image_path, self._custom_image_path(user, ext))
Sets a custom image for the game. `image_path` should refer to an image file on disk
355,687
def _render_list(self, items, empty=): if not items or len(items) == 0: self._segments.append(empty) return self._segments.append() for o in items: self._segments.append() self._segments.append(str(o)) self._segments.append() self._segments.append()
Renders an HTML list with the specified list of strings. Args: items: the iterable collection of objects to render. empty: what to render if the list is None or empty.
355,688
def directories(self): dirlist_p = new_gp_object("CameraList") lib.gp_camera_folder_list_folders(self._cam._cam, self.path.encode(), dirlist_p, self._cam._ctx) for idx in range(lib.gp_list_count(dirlist_p)): name = os.path.join( ...
Get a generator that yields all subdirectories in the directory.
355,689
def FD(self): if self.Verbose: print("Finite Difference Solution Technique") try: self.qs except: self.qs = self.q0.copy() del self.q0 self.x = np.arange(self.dx/2., self.dx * self.qs.shape[0], self.dx) if self.dimens...
Set-up for the finite difference solution method
355,690
def acquire(self,blocking=True,timeout=None,shared=False): with self._lock: if shared: self._acquire_shared(blocking,timeout) else: self._acquire_exclusive(blocking,timeout) assert not (self.is_shared and self.is_exclusive)
Acquire the lock in shared or exclusive mode.
355,691
def _pyproj_inv(self, other, ellipse = ): s inv operation on two LatLon objects Returns the initial heading and reverse heading in degrees, and the distance in km. heading_initialheading_reversedistance': distance}
Perform Pyproj's inv operation on two LatLon objects Returns the initial heading and reverse heading in degrees, and the distance in km.
355,692
def perform_request(self, method, url, params=None, body=None): if body is not None: body = self.serializer.dumps(body) else: data = {} return response, data, duration
Perform the actual request. Retrieve a connection. Pass all the information to it's perform_request method and return the data. :arg method: HTTP method to use :arg url: absolute url (without host) to target :arg params: dictionary of query parameters, will be handed over to the...
355,693
def present(name, grant=None, database=None, user=None, host=, grant_option=False, escape=True, revoke_first=False, ssl_option=False, **connection_args): s already in place. This effectively means tha...
Ensure that the grant is present with the specified properties name The name (key) of the grant to add grant The grant priv_type (i.e. select,insert,update OR all privileges) database The database priv_level (i.e. db.tbl OR db.*) user The user to apply the grant to ...
355,694
def validate_search_space_content(experiment_config): try: search_space_content = json.load(open(experiment_config.get(), )) for value in search_space_content.values(): if not value.get() or not value.get(): print_error() exit(1) except: p...
Validate searchspace content, if the searchspace file is not json format or its values does not contain _type and _value which must be specified, it will not be a valid searchspace file
355,695
def add_node(self, node_name, dataframe=False): if node_name is None: return None return self.add_nodes([node_name], dataframe=dataframe)
Add a single node to the network.
355,696
def _set_get_mpls_autobw_template_brief(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=get_mpls_autobw_template_brief.get_mpls_autobw_template_brief, is_leaf=True, yang_name="get-mpls-autobw-template-brief", rest_name="get-mpls-autobw-template-brief"...
Setter method for get_mpls_autobw_template_brief, mapped from YANG variable /brocade_mpls_rpc/get_mpls_autobw_template_brief (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_mpls_autobw_template_brief is considered as a private method. Backends looking to populate t...
355,697
def make_timestamp(el_time): hrs = el_time // 3600.0 mins = (el_time % 3600.0) // 60.0 secs = el_time % 60.0 stamp = "{0}h {1}m {2}s".format(int(hrs), int(mins), int(secs)) return stamp
Generate an hour-minutes-seconds timestamp from an interval in seconds. Assumes numeric input of a time interval in seconds. Converts this interval to a string of the format "#h #m #s", indicating the number of hours, minutes, and seconds in the interval. Intervals greater than 24h are unproblematic....
355,698
def _flat_columns_in_table(self, table): for col in self._get_dbt_columns_from_bq_table(table): flattened = col.flatten() for subcol in flattened: yield subcol
An iterator over the flattened columns for a given schema and table. Resolves child columns as having the name "parent.child".
355,699
def compare(args): p = OptionParser(compare.__doc__) p.set_cpus() opts, args = p.parse_args(args) if len(args) < 2: sys.exit(not p.print_help()) truths = args[0] cnvoutputs = args[1:] cpus = min(len(cnvoutputs), opts.cpus) p = Pool(processes=cpus) results = [] file...
%prog compare NA12878_array_hg38.bed *.seg Compare cnv output to known ground truths.