Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
349,800
def get_plate_values(self, plate_definition): if not plate_definition.values and not plate_definition.complement: raise PlateDefinitionError() values = [] for n in self.meta_data_manager.global_plate_definitions.all_nodes(): if n.tag == plate_definition.meta_dat...
Gets the plate values from the global meta data according to the given plate definition :param plate_definition: The plate definition :return: The plate values :type plate_definition: PlateDefinitionModel
349,801
def from_file(self, filename, table=None, delimiter=, null=, panic=True, quotechar=, parse_dates=False): if not self.table: if not table: raise GiraffeError("Table must be set or specified to load a file.") self.table = table if not isinstance...
Load from a file into the target table, handling each step of the load process. Can load from text files, and properly formatted giraffez archive files. In both cases, if Gzip compression is detected the file will be decompressed while reading and handled appropriately. The encoding is ...
349,802
def _set_metadata(element, metadata, attr_map, transform=str): for kw, attr in attr_map.items(): value = metadata.get(kw) if value is not None: element.set(attr, transform(value))
Set metadata attributes on a given ``element``. :param element: :class:`xml.etree.ElementTree.Element` instance :param metadata: Dictionary of metadata items containing attribute data for ``element``. :param attr_map: Dictionary mapping of metadata key->attribute name. :param tr...
349,803
def centerdistance(image, voxelspacing = None, mask = slice(None)): r if type(image) == tuple or type(image) == list: image = image[0] return _extract_feature(_extract_centerdistance, image, mask, voxelspacing = voxelspacing)
r""" Takes a simple or multi-spectral image and returns its voxel-wise center distance in mm. A multi-spectral image must be supplied as a list or tuple of its spectra. Optionally a binary mask can be supplied to select the voxels for which the feature should be extracted. The center dista...
349,804
def get_class(import_path=None): from django.core.exceptions import ImproperlyConfigured if import_path is None: raise ImproperlyConfigured() try: dot = import_path.rindex() except ValueError: raise ImproperlyConfigured("%s isnError importing module %s: "%s"Module "%s" does ...
Largely based on django.core.files.storage's get_storage_class
349,805
def _import_mapping(mapping, original=None): for key, value in list(mapping.items()): if isinstance(key, string_types): try: cls = import_item(key) except Exception: if original and key not in original: ...
Import any string-keys in a type mapping.
349,806
def react(self, **kwargs): react_type = kwargs.get("type", self._type) if react_type == : return self.__hover(**kwargs) elif react_type == : pass elif react_type == : return self.__reverse(**kwargs) else: raise ValueError(...
The time of recation is ignored hereTime is ignored here and should be handled by whatever called this function.
349,807
def JoinPath(stem="", *parts): parts = [SmartUnicode(path) for path in parts] result = (stem + NormalizePath(u"/".join(parts))).replace("//", "/") result = result.rstrip("/") return result or "/"
A sane version of os.path.join. The intention here is to append the stem to the path. The standard module removes the path if the stem begins with a /. Args: stem: The stem to join to. *parts: parts of the path to join. The first arg is always the root and directory traversal is not allowed. ...
349,808
def update_time_offset(self, correct_msg_id): bad = self._get_new_msg_id() old = self.time_offset now = int(time.time()) correct = correct_msg_id >> 32 self.time_offset = correct - now if self.time_offset != old: self._last_msg_id = 0 se...
Updates the time offset to the correct one given a known valid message ID.
349,809
def add_custom_nl2br_filters(self, app): _paragraph_re = re.compile(r) @app.template_filter() @evalcontextfilter def nl2br(eval_ctx, value): result = .join( % p.replace(, ) for p in _paragraph_re.split(value)) return resu...
Add a custom filter nl2br to jinja2 Replaces all newline to <BR>
349,810
def weld_arrays_to_vec_of_struct(arrays, weld_types): weld_obj = create_empty_weld_object() obj_ids = [get_weld_obj_id(weld_obj, array) for array in arrays] arrays = .format(.join(obj_ids)) if len(obj_ids) > 1 else .format(obj_ids[0]) input_types = struct_of(, weld_types) if len(obj_ids) > 1 else ...
Create a vector of structs from multiple vectors. Parameters ---------- arrays : list of (numpy.ndarray or WeldObject) Arrays to put in a struct. weld_types : list of WeldType The Weld types of the arrays in the same order. Returns ------- WeldObject Representation ...
349,811
def from_python_src( cls, pySrc, lambdas_path, json_filename: str, stem: str, save_file: bool = False, ): asts = [ast.parse(pySrc)] pgm_dict = genPGM.create_pgm_dict( lambdas_path, asts, json_filename, ...
Builds GrFN object from Python source code.
349,812
def get_jobs(self, recursive=True): if recursive: ret_dict = self.jobs.copy() for link in self._links.values(): ret_dict.update(link.get_jobs(recursive)) return ret_dict return self.jobs
Return a dictionary with all the jobs If recursive is True this will include jobs from all internal `Link`
349,813
def to_json(self, with_volumes=True): data = super().to_json() if with_volumes: data[] = [ { : vol.id, : vol.volume_type, : vol.size } for vol in self.volumes ] return da...
Augment the base `to_json` function, adding information about volumes Returns: `dict`
349,814
def _get_timeout(self, timeout): if timeout is None: return self.opts[] if isinstance(timeout, int): return timeout if isinstance(timeout, six.string_types): try: return int(timeout) except ValueError: retur...
Return the timeout to use
349,815
def build(self, name: str, force: bool = False, quiet: bool = False ) -> None: logger.debug("request to build image: %s", name) instructions = self[name] if instructions.depends_on: logger.info("building dependent imag...
Constructs a Docker image, given by its name, using the set of build instructions associated with that image. Parameters: name: the name of the Docker image. force: if `True`, the image will be rebuilt, regardless of whether or not it is already installed on the ...
349,816
def _pys2col_widths(self, line): split_line = self._split_tidy(line) key = col, tab = self._get_key(*split_line[:2]) width = float(split_line[2]) shape = self.code_array.shape try: if col < shape[1] and tab < shape[2]: self.code_ar...
Updates col_widths in code_array
349,817
def map_dual_axis(low, high, centre, dead_zone, hot_zone, value): if value <= centre: return map_single_axis(centre, low, dead_zone, hot_zone, value) else: return map_single_axis(centre, high, dead_zone, hot_zone, value)
Map an axis with a central dead zone and hot zones at each end to a range from -1.0 to 1.0. This in effect uses two calls to map_single_axis, choosing whether to use centre and low, or centre and high as the low and high values in that call based on which side of the centre value the input value falls. This is ...
349,818
def cli(ctx, dname, site): assert isinstance(ctx, Context) if dname: dname = domain_parse(dname).hostname domain = Session.query(Domain).filter(Domain.name == dname).first() if not domain: click.secho(.format(dn=dname), fg=, bold=True, err=True) re...
List all domains if no <domain> is provided. If <domain> is provided but <site> is not, lists all sites hosted under <domain>. If both <domain> and <site> are provided, lists information on the specified site.
349,819
def main(): coloredlogs.install(syslog=True) context_opts = {} program_opts = {} try: options, arguments = getopt.getopt(sys.argv[1:], , [ , , , , , , ]) for option, value in options: if option in (, ): program_op...
Command line interface for the ``update-dotdee`` program.
349,820
def setReplicationPolicy(self, pid, policy, serialVersion, vendorSpecific=None): response = self.setReplicationPolicyResponse( pid, policy, serialVersion, vendorSpecific ) return self._read_boolean_response(response)
See Also: setReplicationPolicyResponse() Args: pid: policy: serialVersion: vendorSpecific: Returns:
349,821
def sendcommand(self, name, **kwargs): self.log("sending command %s(**%s)" % (name, kwargs)) self.channel.send((name, kwargs))
send a named parametrized command to the other side.
349,822
def send_course_enrollment_statement(lrs_configuration, course_enrollment): user_details = LearnerInfoSerializer(course_enrollment.user) course_details = CourseInfoSerializer(course_enrollment.course) statement = LearnerCourseEnrollmentStatement( course_enrollment.user, course_enrollme...
Send xAPI statement for course enrollment. Arguments: lrs_configuration (XAPILRSConfiguration): XAPILRSConfiguration instance where to send statements. course_enrollment (CourseEnrollment): Course enrollment object.
349,823
def load(self): try: with open(self.config_file) as configfile: self.config = yaml.load(configfile) except TypeError: pass if self.config: self.prefix = self.config.get(, None) if not self.prefix: if os...
(Re)Load config file.
349,824
def getMonthsBuffer(self, direction): if direction == ReadMonths.kWhReverse: return self.m_rev_mons return self.m_mons
Get the months tariff SerialBlock for meter. Args: direction (int): A :class:`~ekmmeters.ReadMonths` value. Returns: SerialBlock: Requested months tariffs buffer.
349,825
def cleaned_sites(): mappings = {} for site in Site.objects.all(): match = re.match(r, site.domain) if match is not None: http, www, domain = match.groups() http_re = http or r normaliz...
Create a list of tuples mapping domains from the sites table to their site name. The domains will be cleaned into regexes that may be more permissive than the site domain is in the db. [(domain_regex, domain_name, domain_string), ...]
349,826
def generate_DJ_junction_transfer_matrices(self): nt2num = {: 0, : 1, : 2, : 3} Tdj = {} for aa in self.codons_dict.keys(): current_Tdj = np.zeros((4, 4)) for init_nt in : for codon in self.codons_dict[aa]: ...
Compute the transfer matrices for the VD junction. Sets the attributes Tdj, Sdj, Ddj, rTdj, and rDdj.
349,827
def addToStore(store, identifier, name): persistedFactory = store.findOrCreate(_PersistedFactory, identifier=identifier) persistedFactory.name = name return persistedFactory
Adds a persisted factory with given identifier and object name to the given store. This is intended to have the identifier and name partially applied, so that a particular module with an exercise in it can just have an ``addToStore`` function that remembers it in the store. If a persisted fact...
349,828
def labelset_heads(self, label): _eps = self._eps _vars = self._vars _hcons = self._hcons nodeids = {nodeid: _eps[nodeid][3].get(IVARG_ROLE, None) for nodeid in _vars[label][][]} if len(nodeids) <= 1: return list(nodeids) scope_sets =...
Return the heads of the labelset selected by *label*. Args: label: the label from which to find head nodes/EPs. Returns: An iterable of nodeids.
349,829
def cbpdn_xstep(k): YU = mp_Z_Y[k] - mp_Z_U[k] b = mp_DSf[k] + mp_xrho * sl.rfftn(YU, None, mp_cri.axisN) if mp_cri.Cd == 1: Xf = sl.solvedbi_sm(mp_Df, mp_xrho, b, axis=mp_cri.axisM) else: Xf = sl.solvemdbi_ism(mp_Df, mp_xrho, b, mp_cri.axisM, mp_cri.axisC) mp_Z_X[k] = sl.irfft...
Do the X step of the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
349,830
def on_server_start(self): self._container = self._docker_client.containers.run(self.docker_image_name, detach=True, **self.docker_params) self.signal_ready() for log_line in self.get_lines(): try: alert_dict = self.parse_line(log_line) if al...
Service run loop function. Run the desired docker container with parameters and start parsing the monitored file for alerts.
349,831
def connect(self): if self._port: self._driver = TempDeckDriver() self._driver.connect(self._port) self._device_info = self._driver.get_device_info() self._poll_stop_event = Event() Thread(target=self._poll_temperature).start() else: ...
Connect to the 'TempDeck' port Planned change- will connect to the correct port in case of multiple TempDecks
349,832
def make_from_catalogue(cls, catalogue, spacing, dilate): new = cls() cat_bbox = get_catalogue_bounding_polygon(catalogue) if dilate > 0: cat_bbox = cat_bbox.dilate(dilate) new.update({: np.min(cat_bbox.lons), : np.max(cat_bbox.lons), ...
Defines the grid on the basis of the catalogue
349,833
def hash_key(self): if self.conf.message_id: message_id = self.message.get() if message_id: return message_id.strip() logger.error( "No Message-ID in {}: {}".format(self.path, self.header_text)) raise MissingMessageID ...
Returns the canonical hash of a mail.
349,834
def flatten_hierarchical_dict(original_dict, separator=, max_recursion_depth=None): if max_recursion_depth is not None and max_recursion_depth <= 0: return original_dict if max_recursion_depth is None: next_recursion_depth = None else: next_recursion_depth = max_recursi...
Flatten a dict. Inputs ------ original_dict: dict the dictionary to flatten separator: string, optional the separator item in the keys of the flattened dictionary max_recursion_depth: positive integer, optional the number of recursions to be done. None is infinte. Outpu...
349,835
def _num_taylor_coefficients(n): _assert(n < 193, ) correction = np.array([0, 0, 1, 3, 4, 7])[_get_logn(n)] log2n = _get_logn(n - correction) m = 2 ** (log2n + 3) return m
Return number of taylor coefficients Parameters ---------- n : scalar integer Wanted number of taylor coefficients Returns ------- m : scalar integer Number of taylor coefficients calculated 8 if n <= 6 16 if 6 < n <= 12 32 if 12 < n <= 2...
349,836
def realtime_comment_classifier(sender, instance, created, **kwargs): if created: moderator_settings = getattr(settings, , None) if moderator_settings: if in moderator_settings: if not moderator_settings[]: return if not ge...
Classifies a comment after it has been created. This behaviour is configurable by the REALTIME_CLASSIFICATION MODERATOR, default behaviour is to classify(True).
349,837
def num_col(self): ret = ctypes.c_uint() _check_call(_LIB.XGDMatrixNumCol(self.handle, ctypes.byref(ret))) return ret.value
Get the number of columns (features) in the DMatrix. Returns ------- number of columns : int
349,838
def run(self): self._prepare() while self.running: if self._run() is False: break time.sleep(self._sleep_period) self.shutdown()
Main process loop.
349,839
def calculate_auc_var(auc_structure): actives, decoys = splitter(auc_structure) fpf = [x[4] for x in actives] aucvar_a = np.var(fpf, ddof=1, dtype=np.float64) tpf = [x[5] for x in decoys] aucvar_d = np.var(tpf, ddof=1, dtype=np.float64) return (aucvar_a, aucvar_d)
determine AUC variance due to actives (aucvar_a) and decoys (aucvar_d) :param roc_structure: list [(id, best_score, best_query, status, fpf, tpf), ...,] :return (aucvar_a, aucvar_d): tuple variance due to actives and decoys, respectively
349,840
def close(self): if hasattr(self, "conn"): self.conn.close() del self.conn if hasattr(self, "user"): del self.user
Close connection to this room
349,841
def _decode_subelements(self): for child in self._element: if child.tag == self._show_tag: self._show = child.text elif child.tag == self._status_tag: self._status = child.text elif child.tag == self._priority_tag: try:...
Decode the stanza subelements.
349,842
def create_from_json(cls, json_data): zipcode = ZipCode() zipcode.zipcode = json_data["zipcode_info"]["zipcode"] zipcode.meta = json_data["meta"] if "meta" in json_data else None zipcode.component_results = _create_component_results(json_data, "zipcode_info") return zi...
Deserialize zipcode json data into a ZipCode object Args: json_data (dict): The json data for this zipcode Returns: Zip object
349,843
def copy(self): "Return a copy of the drop target (to avoid wx problems on rebuild)" return ToolBoxDropTarget(self.dv, self.root, self.designer, self.inspector)
Return a copy of the drop target (to avoid wx problems on rebuild)
349,844
def add_int_enums_to_docstring(enum): if enum.__doc__ is None: enum.__doc__ = "" enum.__doc__ += ("\n\n" "Attributes\n" "----------\n") for val in list(enum): enum.__doc__ += "{} = {}\n".format(val.name, int(val)) return e...
Decorator for IntEnum which re-writes the documentation string so that Sphinx enumerates all the enumeration values. This is a work-around for Sphinx autodoc's inability to properly document IntEnums. This decorator adds enumeration names and values to the 'Attributes' section of the docstring of ...
349,845
def formatError(self, test, err): test.capturedOutput = output = self.buffer self._buf = None if not output: return err ec, ev, tb = err return (ec, self.addCaptureToErr(ev, output), tb)
Add captured output to error report.
349,846
def DbGetClassAttributeProperty(self, argin): self._log.debug("In DbGetClassAttributeProperty()") class_name = argin[0] return self.db.get_class_attribute_property(class_name, argin[1:])
Get Tango class property(ies) value :param argin: Str[0] = Tango class name Str[1] = Attribute name Str[n] = Attribute name :type: tango.DevVarStringArray :return: Str[0] = Tango class name Str[1] = Attribute property number Str[2] = Attribute property 1 name ...
349,847
def run(self): tokens = [] section = nodes.section() section[].append("available-tasks") title = nodes.title() title += nodes.Text("Default tasks") section += title task_finder = TaskFinder(Collector()) for name, task in sorted(task_finder.defau...
For each file in noseOfYeti/specs, output nodes to represent each spec file
349,848
def _eval_metric(input_, topk, correct_predictions, examples, phase): my_parameters = {} if phase in (Phase.test, Phase.infer): dtype = tf.float32 with input_.g.device(count.device): examples = tf.assign_add(count, examples) with input_.g.device(correct.device): correct_predictions =...
Creates the standard tracking varibles if in test and returns accuracy.
349,849
def post(json_data, url, dry_run=False): if dry_run: info( % json.dumps(json_data, indent=4)) else: response = SESSION.post(url, data=json.dumps(json_data), headers={: }) if response.status_code != 2...
POST json data to the url provided and verify the requests was successful
349,850
def parse_input(input_parameter): split_package_name = input_parameter.split() package_name = split_package_name[0] module_name = package_name.replace("-", ".") if len(split_package_name) >= 2: module_name = ".".join([module_name, split_package_name[1]]) return package_name, module_name
From a syntax like package_name#submodule, build a package name and complete module name.
349,851
def rc4_decrypt(key, data): if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( , len(key) )) return _decrypt(, key, data, None, None)
Decrypts RC4 ciphertext using a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of...
349,852
def sample(generator, min=-1, max=1, width=SAMPLE_WIDTH): fmt = { 1: , 2: , 4: }[width] return (struct.pack(fmt, int(sample)) for sample in \ normalize(hard_clip(generator, min, max),\ min, max, -2**(width * 8 - 1), 2**(width * 8 - 1) - 1))
Convert audio waveform generator into packed sample generator.
349,853
def unique(df, columns=None): if columns is None: columns = df.columns for col in columns: if not df[col].is_unique: raise AssertionError("Column {!r} contains non-unique values".format(col)) return df
Asserts that columns in the DataFrame only have unique values. Parameters ---------- df : DataFrame columns : list list of columns to restrict the check to. If None, check all columns. Returns ------- df : DataFrame same as the original
349,854
def create(self, **kwargs): tmos_v = self._meta_data[]._meta_data[] if LooseVersion(tmos_v) == LooseVersion() or LooseVersion( tmos_v) == LooseVersion(): if in self._meta_data: error = "There was an attempt to assign a new uri to this " \ ...
Custom _create method to accommodate for issue 11.5.4 and 12.1.1, Where creation of an object would return 404, despite the object being created.
349,855
def get_allowed_units(self, database, username, relation_id=None): self.connect(password=self.get_mysql_root_password()) allowed_units = set() for unit in related_units(relation_id): settings = relation_get(rid=relation_id, unit=unit) for attr in ["%...
Get list of units with access grants for database with username. This is typically used to provide shared-db relations with a list of which units have been granted access to the given database.
349,856
def plot_row_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1, labels=None, color_labels=None, ellipse_outline=False, ellipse_fill=True, show_points=True, **kwargs): utils.validation.check_is_fitted(self, ) if ...
Plot the row principal coordinates.
349,857
def _check_if_tag_already_exists(self): version = self.data[] if self.vcs.tag_exists(version): return True else: return False
Check if tag already exists and show the difference if so
349,858
def search(self, search_phrase, limit=None): query_string = self._make_query_from_terms(search_phrase) self._parsed_query = query_string schema = self._get_generic_schema() parser = QueryParser(, schema=schema) query = parser.parse(query_string) datasets = def...
Finds datasets by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to return. None means without limit. Returns: list of DatasetSearchResult instances.
349,859
def load(self, rel_path=None): for k, v in self.layer.iteritems(): self.add(k, v[], v.get()) filename = v.get() path = v.get() if filename: if not path: path = rel_path else: ...
Add data_sources to layer and open files with data for the data_source.
349,860
def get_portfolios3(): g1 = [0] g2 = [1] g7 = [2] g13 = [3] g14 = [4] g15 = [5] g16 = [6] g18 = [7] g21 = [8] g22 = [9] g23 = [10, 11] portfolios = [g1 + g15 + g18, g2 + g16 + g21, g13 + g22, g7 + g23] pass...
Returns portfolios with U12 and U20 generators removed and generators of the same type at the same bus aggregated.
349,861
def wordtokens(self,include_punct=True): ws=self.ents() if not include_punct: return [w for w in ws if not w.is_punct] return ws
Returns a list of this object's Words in order of their appearance. Set flattenList to False to receive a list of lists of Words.
349,862
def initial_state(self, batch_size, dtype=tf.float32, trainable=False, trainable_initializers=None, trainable_regularizers=None, name=None): if self._max_unique_stats == 1: return super(BatchNormLSTM, self).initial_state( batch_size, dtype=dtype, trainabl...
Builds the default start state tensor of zeros. Args: batch_size: An int, float or scalar Tensor representing the batch size. dtype: The data type to use for the state. trainable: Boolean that indicates whether to learn the initial state. trainable_initializers: An optional pair of initiali...
349,863
def command(self, func): command = Command(func) self._commands[func.__name__] = command return func
Decorator to add a command function to the registry. :param func: command function.
349,864
def build_seasonal_transition_noise( drift_scale, num_seasons, is_last_day_of_season): drift_scale_diag = tf.stack( [tf.zeros_like(drift_scale)] * (num_seasons - 1) + [drift_scale], axis=-1) def seasonal_transition_noise(t): noise_scale_diag = dist_util.pick_scalar_condition( ...
Build the transition noise model for a SeasonalStateSpaceModel.
349,865
def elevate_element(node, adopt_name=None, adopt_attrs=None): parent = node.getparent() grandparent = parent.getparent() child_index = parent.index(node) parent_index = grandparent.index(parent) siblings = list(parent)[child_index+1:] ...
This method serves a specialized function. It comes up most often when working with block level elements that may not be contained within paragraph elements, which are presented in the source document as inline elements (inside a paragraph element). It would be inappropriate to merely i...
349,866
def uniqueof20(k, rep=10000): alphabet = reps = [len(set(random.choice(alphabet) for i in range(k))) for j in range(rep)] return sum(reps) / len(reps)
Sample k times out of alphabet, how many different?
349,867
def multpasswordbox(msg="Fill in values for the fields." , title=" " , fields=tuple() ,values=tuple() ): r return __multfillablebox(msg,title,fields,values,"*")
r""" Same interface as multenterbox. But in multpassword box, the last of the fields is assumed to be a password, and is masked with asterisks. Example ======= Here is some example code, that shows how values returned from multpasswordbox can be checked for validity before they are accept...
349,868
def debug(func): @wraps(func) def wrapped(*args, **kwargs): arg = repr(args) + + repr(kwargs) sys.stdout.write( + func.__name__ + arg + ) try: result = func(*args, **kwargs) except: sys.stdout.write() sys.stdout.write(format_exception(*sy...
Decorator that prints a message whenever a function is entered or left.
349,869
def _get_best_subset(self, ritz): overall_evaluations = {} def evaluate(_subset, _evaluations): try: _evaluations[_subset] = \ self.subset_evaluator.evaluate(ritz, _subset) except utils.AssumptionError: ...
Return candidate set with smallest goal functional.
349,870
def get_structure_with_nodes(self): new_s = Structure.from_sites(self.structure) for v in self.vnodes: new_s.append("X", v.frac_coords) return new_s
Get the modified structure with the voronoi nodes inserted. The species is set as a DummySpecie X.
349,871
async def rewrite(self, path, method = None, keepresponse = True): "Rewrite this request to another processor. Must be called before header sent" if self._sendHeaders: raise HttpProtocolException() if getattr(self.event, , 0) >= getattr(self.protocol, , 32): raise HttpRew...
Rewrite this request to another processor. Must be called before header sent
349,872
def get_json(request, token): result = [] searchtext = request.GET[] if len(searchtext) >= 3: pickled = _simple_autocomplete_queryset_cache.get(token, None) if pickled is not None: app_label, model_name, query = pickle.loads(pickled) model = apps.get_model(app_la...
Return matching results as JSON
349,873
def items_differ(jsonitems, dbitems, subfield_dict): if len(jsonitems) == len(dbitems) == 0: return False elif len(jsonitems) != len(dbitems): match = i break if match is not None: jsonitems.pop(match)...
check whether or not jsonitems and dbitems differ
349,874
def circle_pattern(pattern_radius, circle_radius, count, center=[0.0, 0.0], angle=None, **kwargs): from .path import Path2D if angle is None: angles = np.linspace(0.0, np.pi * 2.0, count + 1)[:-1] el...
Create a Path2D representing a circle pattern. Parameters ------------ pattern_radius : float Radius of circle centers circle_radius : float The radius of each circle count : int Number of circles in the pattern center : (2,) float Center of pattern angle : float ...
349,875
def build_loss_tables(dstore): oq = dstore[] L = len(oq.loss_dt().names) R = dstore[].get_num_rlzs() serials = dstore[][] idx_by_ser = dict(zip(serials, range(len(serials)))) tbl = numpy.zeros((len(serials), L), F32) lbr = numpy.zeros((R, L), F32) for rec in dstore[].value: ...
Compute the total losses by rupture and losses by rlzi.
349,876
async def wait_for_group(self, container, networkid, timeout = 120): if networkid in self._current_groups: return self._current_groups[networkid] else: if not self._connection.connected: raise ConnectionResetException groupchanged = VXLANGroup...
Wait for a VXLAN group to be created
349,877
def split_data( *inputs, splits=[0.5, 0.5], shuffle=True, stratify_by=None, index_only=False, seed=None, ): def fractions_to_counts(fracs, n): counts = [int(np.round(n * frac)) for frac in fracs] counts[-1] = n - sum(counts[:-1]) return counts ...
Splits inputs into multiple splits of defined sizes Args: inputs: correlated tuples/lists/arrays/matrices/tensors to split splits: list containing split sizes (fractions or counts); shuffle: if True, shuffle the data before splitting stratify_by: (None or an input) if not None, use ...
349,878
def save_csv(filename, dat, index=False, **kw): import pandas from neuropythy.util import to_dataframe d = to_dataframe(dat) if any(filename.endswith(s) for s in (, , )): with gzip.open(filename, , newlines=) as fl: d.to_csv(fl, index=index, **kw) else: with open(filename, ) as ...
save_csv(filename, d) writes a pandas dataframe d to a CSV file with the given name. If pandas cannot be loaded, then an error is raised. If d is not a dataframe, to_dataframe() is called on it. All optional arguments are passed along to the pandas.DataFrame.to_csv function.
349,879
def get_public_orders(self, group=False): self._log() return self._rest_client.get( endpoint=, params={: self.name, : int(group)} )
Return public orders that are currently open. :param group: If set to True (default: False), orders with the same price are grouped. :type group: bool :return: Public orders currently open. :rtype: dict
349,880
def get_bool_resources(self, package_name, locale=): self._analyse() buff = buff += try: for i in self.values[package_name][locale]["bool"]: buff += .format(i[0], i[1]) except KeyError: pass buff += return bu...
Get the XML (as string) of all resources of type 'bool'. Read more about bool resources: https://developer.android.com/guide/topics/resources/more-resources.html#Bool :param package_name: the package name to get the resources for :param locale: the locale to get the resources for (defa...
349,881
def _build_likelihood(self): r K = self.kern.K(self.X) K_alpha = tf.matmul(K, self.q_alpha) f_mean = K_alpha + self.mean_function(self.X) I = tf.tile(tf.expand_dims(tf.eye(self.num_data, dtype=settings.float_type), 0), [self.num_latent, 1, 1]) ...
r""" q_alpha, q_lambda are variational parameters, size N x R This method computes the variational lower bound on the likelihood, which is: E_{q(F)} [ \log p(Y|F) ] - KL[ q(F) || p(F)] with q(f) = N(f | K alpha + mean, [K^-1 + diag(square(lambda))]^-1) .
349,882
def build_provider(self, stack): return self.provider_builder.build(region=stack.region, profile=stack.profile)
Builds a :class:`stacker.providers.base.Provider` suitable for operating on the given :class:`stacker.Stack`.
349,883
def tsuite_enter(trun, tsuite): if trun["conf"]["VERBOSE"]: cij.emph("rnr:tsuite:enter { name: %r }" % tsuite["name"]) rcode = 0 for hook in tsuite["hooks"]["enter"]: rcode = script_run(trun, hook) if rcode: break if trun["conf"]["VERBOSE"]: cij.e...
Triggers when entering the given testsuite
349,884
def show(self, resolve_mac=True, print_result=True): res = [] for iface_name in sorted(self.data): dev = self.data[iface_name] mac = dev.mac if resolve_mac and conf.manufdb: mac = conf.manufdb._resolve_MAC(mac) validity_color = lam...
Print list of available network interfaces in human readable form
349,885
def union(cls, *mhs): if len(mhs) < 2: raise ValueError("Cannot union less than 2 MinHash") num_perm = len(mhs[0]) seed = mhs[0].seed if any((seed != m.seed or num_perm != len(m)) for m in mhs): raise ValueError("The unioning MinHash must have the\ ...
Create a MinHash which is the union of the MinHash objects passed as arguments. Args: *mhs: The MinHash objects to be united. The argument list length is variable, but must be at least 2. Returns: datasketch.MinHash: A new union MinHash.
349,886
def max_ret_portfolio(exp_rets): if not isinstance(exp_rets, pd.Series): raise ValueError("Expected returns is not a Series") weights = exp_rets[:] weights[weights == weights.max()] = 1.0 weights[weights != weights.max()] = 0.0 weights /= weights.sum() return weights
Computes a long-only maximum return portfolio, i.e. selects the assets with maximal return. If there is more than one asset with maximal return, equally weight all of them. Parameters ---------- exp_rets: pandas.Series Expected asset returns (often historical returns). Returns ...
349,887
def plot_line_loading( network, timesteps=range(1,2), filename=None, boundaries=[], arrows=False): cmap = plt.cm.jet array_line = [[] * len(network.lines), network.lines.index] array_link = [[] * len(network.links), network.links.index] ...
Plots line loading as a colored heatmap. Line loading is displayed as relative to nominal capacity in %. Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis timesteps : range Defines which timesteps are consi...
349,888
def _extract_gcs_api_response_error(message): try: if len(message) == 3: data = json.loads(message[2]) return data[][][0][] except Exception: pass return message
A helper function to extract user-friendly error messages from service exceptions. Args: message: An error message from an exception. If this is from our HTTP client code, it will actually be a tuple. Returns: A modified version of the message that is less cryptic.
349,889
def _scan_radio_channels(self, cradio, start=0, stop=125): return list(cradio.scan_channels(start, stop, (0xff,)))
Scan for Crazyflies between the supplied channels.
349,890
def __expand_cluster_block(self, block, cluster_index, leaf_blocks, unhandled_block_indexes): block.set_cluster(cluster_index) self.__update_cluster_dendrogram(cluster_index, [block]) neighbors = self.__find_block_neighbors(block, leaf_blocks, unhandled_block_indexes) s...
! @brief Expand cluster from specific block that is considered as a central block. @param[in] block (bang_block): Block that is considered as a central block for cluster. @param[in] cluster_index (uint): Index of cluster that is assigned to blocks that forms new cluster. @param[in]...
349,891
def expanded_sequence(self, node, include_additional_constant_sites=False): if include_additional_constant_sites: L = self.seq_len else: L = self.seq_len - self.additional_constant_sites return node.cseq[self.full_to_reduced_sequence_map[:L]]
Expand a nodes compressed sequence into the real sequence Parameters ---------- node : PhyloTree.Clade Tree node Returns ------- seq : np.array Sequence as np.array of chars
349,892
def update_from_xso_item(self, xso_item): self.subscription = xso_item.subscription self.approved = xso_item.approved self.ask = xso_item.ask self.name = xso_item.name self.groups = {group.name for group in xso_item.groups}
Update the attributes (except :attr:`jid`) with the values obtained from the gixen `xso_item`. `xso_item` must be a valid :class:`.xso.Item` instance.
349,893
def decryptfile(filename, key=None, outfile=None, chunk=64 * 1024): if key is None: key = ENCRYPT_KEY if not outfile: outfile = os.path.splitext(filename)[0] with open(filename, ) as input: origsize = struct.unpack(, input.read(struct.calcsize()))[0] iv = input.read(16...
Decrypts a file using AES (CBC mode) with the given key. If no file is supplied, then the inputted file will be modified in place. The chunk value will be the size with which the function uses to read and encrypt the file. Larger chunks can be faster for some files and machines. The chunk MUST be div...
349,894
def _validateParamsFor__validateToDateTimeFormat(formats, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): _validateGenericParameters(blank=blank, strip=strip, allowlistRegexes=allowlistRegexes, blocklistRegexes=blocklistRegexes) if formats is None: raise PySimpl...
Raises PySimpleValidateException if the arguments are invalid. This is called by the validateTime() function to check its arguments. This code was refactored out to a separate function so that the PyInputPlus module (or other modules) could check their parameters' arguments for inputTime().
349,895
def _invoice_matches_cart(self): self._refresh() cart = self.invoice.cart if not cart: return True return cart.revision == self.invoice.cart_revision
Returns true if there is no cart, or if the revision of this invoice matches the current revision of the cart.
349,896
def add(connect_spec, dn, attributes): s attributes to a non-empty iterable of values. :returns: ``True`` if successful, raises an exception otherwise. CLI example: .. code-block:: bash salt ldap3.add "{ : , : { : , : ,...
Add an entry to an LDAP database. :param connect_spec: See the documentation for the ``connect_spec`` parameter for :py:func:`connect`. :param dn: Distinguished name of the entry. :param attributes: Non-empty dict mapping each of the new entry's attributes to a non...
349,897
def _container_registration(self, alias): containers = Container.find_by_name(self._client_session, alias) def validate_name(name): valid = True if name in containers: valid = False return valid count = 1 container_name = "{...
Check for an available name and return that to the caller.
349,898
def low_frequency_cutoff_from_cli(opts): instruments = opts.instruments if opts.instruments is not None else [] return {ifo: opts.low_frequency_cutoff for ifo in instruments}
Parses the low frequency cutoff from the given options. Returns ------- dict Dictionary of instruments -> low frequency cutoff.
349,899
def get_Name(name, short=False): sf = { "countryName": "C", "stateOrProvinceName": "ST", "localityName": "L", "organizationalUnitName": "OU", "organizationName": "O", "commonName": "CN", "emailAddress": "E", } return ...
Return the distinguished name of an X509 Certificate :param name: Name object to return the DN from :param short: Use short form (Default: False) :type name: :class:`cryptography.x509.Name` :type short: Boolean :rtype: str