Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
351,100
def encryption_key(self, alg, **kwargs): if not self.key: self.deserialize() try: tsize = ALG2KEYLEN[alg] except KeyError: raise UnsupportedAlgorithm(alg) if tsize <= 32: _enc_key = sha256_digest(self.key)[:tsize] ...
Return an encryption key as per http://openid.net/specs/openid-connect-core-1_0.html#Encryption :param alg: encryption algorithm :param kwargs: :return: encryption key as byte string
351,101
def check_merkle_hash(self): calculated_hash = merkle([tx.hash() for tx in self.txs], double_sha256) if calculated_hash != self.merkle_root: raise BadMerkleRootError( "calculated %s but block contains %s" % (b2h(calculated_hash), b2h(self.merkle_root)))
Raise a BadMerkleRootError if the Merkle hash of the transactions does not match the Merkle hash included in the block.
351,102
def write(self, directory): status_file = os.path.join(directory, self.STATUS_FILE) status = { : self.STATUS_FORMAT, : coverage.__version__, : self.settings, : self.files, } fout = open(status_file, "wb") try: ...
Write the current status to `directory`.
351,103
def connect_tcp(self, address, port): info(, address, port) self._connect_tcp(address, port)
Connect to tcp/ip `address`:`port`. Delegated to `_connect_tcp`.
351,104
def _fetch(self): if not self.is_local and not self._obcache_current: def _remote_fetch(id): return distob.engine[id] self._obcache = self._dv.apply_sync(_remote_fetch, self._id) self._obcache_current = True self.__engine_affi...
forces update of a local cached copy of the real object (regardless of the preference setting self.cache)
351,105
def build_taxonomy(self, level, namespace, predicate, value): return { : level, : namespace, : predicate, : value }
:param level: info, safe, suspicious or malicious :param namespace: Name of analyzer :param predicate: Name of service :param value: value :return: dict
351,106
def normal_var(data, mean): if not isinstance(data, np.ndarray): data = np.array(data) cumm = [0.0] cumm.extend(np.cumsum(np.power(np.abs(data - mean), 2))) def cost(s, t): dist = float(t - s) diff = cumm[t] - cumm[s] return dist * np.log(diff/dist) r...
Creates a segment cost function for a time series with a Normal distribution with changing variance Args: data (:obj:`list` of float): 1D time series data variance (float): variance Returns: function: Function with signature (int, int) -> float where the ...
351,107
def src_addr(self): try: return socket.inet_ntop(self._af, self.raw[self._src_addr].tobytes()) except (ValueError, socket.error): pass
The packet source address.
351,108
def subscribe_async(self, event, handler): self._handlers.async_handlers[event].append(handler)
Subscribes an asynchronous Handler for the given Event. An asynchronous handler is executed concurrently to the others without blocking the Events flow. @param event: (str|see.Event) event to react to. @param handler: (callable) function or method to subscribe.
351,109
def warp_image_by_corner_points_projection(corner_points, image): top_left, top_right, bottom_left, bottom_right = np.array(corner_points) top_edge = np.linalg.norm(top_right - top_left) bottom_edge = np.linalg.norm(bottom_right - bottom_left) left_edge = np.linalg.norm(top_left - bottom_left...
Given corner points of a Sudoku, warps original selection to a square image. :param corner_points: :type: corner_points: list :param image: :type image: :return: :rtype:
351,110
def create_routine_loader(self, rdbms):
Factory for creating a Routine Loader objects (i.e. objects for loading stored routines into a RDBMS instance from (pseudo) SQL files. :param str rdbms: The target RDBMS (i.e. mysql, mssql or pgsql). :rtype: pystratum.RoutineLoader.RoutineLoader
351,111
def legacy_events_view(request): events = TeacherEvent.objects.all() event_count = events.count() paginator = Paginator(events, 100) page = request.GET.get() try: events = paginator.page(page) except PageNotAnInteger: events = paginator.page(1) except EmptyPage: ...
View to see legacy events.
351,112
def password_link_expired(self, now=None): if not now: now = datetime.datetime.utcnow() return self.password_link_expires < now
Check if password link expired
351,113
def data(self): if self._resources is None: self.__init() if "data" in self._resources: url = self._url + "/data" return _data.Data(url=url, securityHandler=self._securityHandler, initialize=True, ...
returns the reference to the data functions as a class
351,114
def write_gene_recs(self, db, gene_id): gene_rec = db[gene_id] self.write_rec(gene_rec) self.write_mRNA_children(db, mRNA_id) for gene_child in db.children(gene_id, level=1): if gene_child.featuretype != "mRNA": self.wri...
NOTE: The goal of this function is to have a canonical ordering when outputting a gene and all of its records to a file. The order is intended to be: gene # mRNAs sorted by length, with longest mRNA first mRNA_1 # Exons of mRNA, sorted by start position (ascendi...
351,115
def as_completed(fs, timeout=None): if timeout is not None: end_time = timeout + time.time() fs = set(fs) with _AcquireFutures(fs): finished = set( f for f in fs if f._state in [CANCELLED_AND_NOTIFIED, FINISHED]) pending = fs - finished w...
An iterator over the given futures that yields each as it completes. Args: fs: The sequence of Futures (possibly created by different Executors) to iterate over. timeout: The maximum number of seconds to wait. If None, then there is no limit on the wait time. Returns: ...
351,116
def parse_events(cls, ev_args, parent_ctx): dest = [("start", )+tuple(ev_args)] result = yield from capture_events( super().parse_events(ev_args, parent_ctx), dest ) result._set_captured_events(dest) return result
Capture the events sent to :meth:`.XSO.parse_events`, including the initial `ev_args` to a list and call :meth:`_set_captured_events` on the result of :meth:`.XSO.parse_events`. Like the method it overrides, :meth:`parse_events` is suspendable.
351,117
def update_plugin_dialog(package_name=None, update_args=None, update_kwargs=None, ignore_not_installed=True): thread_context = {} if package_name is None: installed_plugins_ = installed_plugins(only_conda=True) installed_package_names = [plugin_i[...
Launch dialog to track status of update of specified plugin package. .. versionadded:: 0.19 .. versionchanged:: 0.20 Add support for updating multiple packages (update all **installed** plugins by default). Add :data:`update_args` and :data:`update_kwargs` arguments. .. versionch...
351,118
def generate_string(out_dir, limits): max_limit = max((int(v) for v in limits)) with open(filename(out_dir, ), ) as out_f: with IncludeGuard(out_f): out_f.write( .format(VERSION) ) generate_make...
Generate string.hpp
351,119
def scaleBy(self, factor): factor = normalizers.normalizeTransformationScale(factor) self._scale(factor)
Scales all kerning values by **factor**. **factor** will be an :ref:`type-int-float`, ``tuple`` or ``list``. The first value of the **factor** will be used to scale the kerning values. >>> myKerning.scaleBy(2) >>> myKerning.scaleBy((2,3))
351,120
def mles(self): mle_vals = np.ndarray((self._nx)) for i in range(self._nx): mle_vals[i] = self._loglikes[i].mle() return mle_vals
return the maximum likelihood estimates for each of the energy bins
351,121
def data(self): cutout = np.copy(self._segment_img[self.slices]) cutout[cutout != self.label] = 0 return cutout
A 2D cutout image of the segment using the minimal bounding box, where pixels outside of the labeled region are set to zero (i.e. neighboring segments within the rectangular cutout image are not shown).
351,122
def addTerminalState(self, state): table = self._copy() table.table[state] = {} return table
Create a new L{TransitionTable} with all of the same transitions as this L{TransitionTable} plus a new state with no transitions. @param state: The new state to include in the new table. @return: The newly created L{TransitionTable}.
351,123
def score_at_fpr(fg_vals, bg_vals, fpr=0.01): bg_vals = np.array(bg_vals) return scoreatpercentile(bg_vals, 100 - 100 * fpr)
Returns the motif score at a specific FPR (default 1%). Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. fpr : float, optional The FPR (between 0.0 and 1.0). Retur...
351,124
def rs_simple_encode_msg(msg_in, nsym, fcr=0, generator=2, gen=None): s slower than the inlined function below)' global field_charac if (len(msg_in) + nsym) > field_charac: raise ValueError("Message is too long (%i when max is %i)" % (len(msg_in)+nsym, field_charac)) if gen is None: gen = rs_generator_p...
Simple Reed-Solomon encoding (mainly an example for you to understand how it works, because it's slower than the inlined function below)
351,125
def decode(data): data = bytearray(data) result = bytearray() pos = 0 while pos < len(data): header_byte = data[pos] if header_byte > 127: header_byte -= 256 pos += 1 if 0 <= header_byte <= 127: result.extend(data[pos:pos+header_byte+1]) ...
Decodes a PackBit encoded data.
351,126
def _filter_releases(self): global display_filter_log filter_plugins = filter_release_plugins() if not filter_plugins: if display_filter_log: logger.info("No release filters are enabled. Skipping filtering") display_filter_log = False ...
Run the release filtering plugins
351,127
def hr_diagram_figure(cluster): temps, lums = round_teff_luminosity(cluster) x, y = temps, lums colors, color_mapper = hr_diagram_color_helper(temps) x_range = [max(x) + max(x) * 0.05, min(x) - min(x) * 0.05] source = ColumnDataSource(data=dict(x=x, y=y, color=colors)) pf = figure(y_axis_t...
Given a cluster create a Bokeh plot figure creating an H-R diagram.
351,128
def get_image(width, height=None, background_color="cccccc", random_background_color=False): return Image( url=placeholdit.get_url( width, height=height, background_color=background_color, random_background_color=random_background_color ), ...
Returns image with caption, credit, and random background color as requested.
351,129
def cluster(args): args = _check_args(args) read_stats_file = op.join(args.dir_out, "read_stats.tsv") if file_exists(read_stats_file): os.remove(read_stats_file) bam_file, seq_obj = _clean_alignment(args) logger.info("Parsing matrix file") seqL, y, l = parse_ma_file(seq_obj, args...
Creating clusters
351,130
def load_and_append(instrument_dict, instruments=None, raise_errors=False): if instruments is None: instruments = {} updated_instruments = {} updated_instruments.update(instruments) loaded_failed = {} for instrument_name, instrument_class_name in instrume...
load instrument from instrument_dict and append to instruments Args: instrument_dict: dictionary of form instrument_dict = { name_of_instrument_1 : {"settings" : settings_dictionary, "class" : name_of_class} name_of_instrument_2 :...
351,131
def rom(addr, dout, CONTENT): @always_comb def read(): dout.next = CONTENT[int(addr)] return read
CONTENT == tuple of non-sparse values
351,132
def _shape_array(array1, array2): if len(array1) > len(array2): new_array = array2 old_array = array1 else: new_array = array1 old_array = array2 length = len(old_array) - len(new_array) for i in range(length): n = new_array[-1].copy() n[0::3] += 1 ...
Function that equalises the input arrays by zero-padding the shortest one. ---------- Parameters ---------- array1: list or numpy.array Array array2: list or numpy.array Array Return ------ arrays: numpy.array Array containing the equal-length arrays.
351,133
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None): * conn = _auth(profile) return conn.create_vpnservice(subnet, router, name, admin_state_up)
Creates a new VPN service CLI Example: .. code-block:: bash salt '*' neutron.create_vpnservice router-name name :param subnet: Subnet unique identifier for the VPN service deployment :param router: Router unique identifier for the VPN service :param name: Set a name for the VPN service ...
351,134
def _parse_title_url(html_chunk): title = html_chunk.find("div", {"class": "comment"}) if not title: return _parse_alt_title(html_chunk), None title = title[0].find("h2") if not title: return _parse_alt_title(html_chunk), None url = None url_tag = title[0].find("a") ...
Parse title/name of the book and URL of the book. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: tuple: (title, url), both as strings.
351,135
def emit(self, record): try: msg = self.format(record) if record.levelno < self.splitLevel: stream = self.outStream else: stream = self.errStream stream.write(msg) stream.write(self.terminator) self....
Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an ...
351,136
def get_rich_events(self, item): if "version_downloads_data" not in item[]: return [] eitem = self.get_rich_item(item) for sample in item[]["version_downloads_data"]["version_downloads"]: event = deepcopy(eitem) event[] = sample[] ...
In the events there are some common fields with the crate. The name of the field must be the same in the create and in the downloads event so we can filer using it in crate and event at the same time. * Fields that don't change: the field does not change with the events in a create so t...
351,137
def FromTimeString( cls, time_string, dayfirst=False, gmt_as_timezone=True, timezone=pytz.UTC): if not gmt_as_timezone and time_string.endswith(): time_string = .format(time_string[:-3]) try: datetime_object = dateutil.parser.parse(time_string, dayfirst=dayfirst) except...
Converts a string containing a date and time value into a timestamp. Args: time_string: String that contains a date and time value. dayfirst: An optional boolean argument. If set to true then the parser will change the precedence in which it parses timestamps from MM-DD-...
351,138
def community_topic_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/topics api_path = "/api/v2/community/topics.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/help_center/topics#create-topic
351,139
def _err(self, msg, err=True): severity = "FATAL" if err else "NOTE" txt = "".join([self.objdoc.doc, "User's command-line:\n\n", " % go_plot.py {ARGS}\n\n".format(ARGS=" ".join(sys.argv[1:])), "**{SEV}: {MSG}\n".format(SEV=se...
Print useage and error before exiting.
351,140
def next_tzolkin_haab(tzolkin, haab, jd): in combination, and a Julian day count, find the next occurrance of the combination after the date-Tzolkt possible")
For a given haab-tzolk'in combination, and a Julian day count, find the next occurrance of the combination after the date
351,141
def loadmodules(self, modules=None, rel=None): result = [] if rel is None: rel = self.rel if modules is None: modules = self._modules for module in modules: if isinstance(module, string_types): name = module ...
ry to (re)load modules and return loaded modules. :param modules: list of module (name) to load. :param bool rel: flag for forcing reload of module. Default is this rel flag (false by default). :rtype: list :return: loaded modules.
351,142
def forward(self, data_batch, is_train=None): super(SVRGModule, self).forward(data_batch, is_train) if is_train: self._mod_aux.forward(data_batch, is_train)
Forward computation for both two modules. It supports data batches with different shapes, such as different batch sizes or different image sizes. If reshaping of data batch relates to modification of symbol or module, such as changing image layout ordering or switching from training to predictin...
351,143
def coordinates(self, x, y): state = self.state return state.mt.coord_from_area(x, y, state.lat, state.lon, state.width, state.ground_width)
return coordinates of a pixel in the map
351,144
def make_downsampled_type(cls, other_base): docstring = dedent( ).format(t=other_base.__name__) doc = format_docstring( owner_name=other_base.__name__, docstring=docstring, formatters={: PIPELINE_DOWNSAMPLING_FREQUENCY_DOC}, ) ...
Factory for making Downsampled{Filter,Factor,Classifier}.
351,145
def series_keys(self, flow_id, cache=True): cache_id = + flow_id if cache_id in self.cache: return self.cache[cache_id] else: resp = self.data(flow_id, params={: }) l = list(s.key for s in resp.data.series) df = PD.D...
Get an empty dataset with all possible series keys. Return a pandas DataFrame. Each column represents a dimension, each row a series key of datasets of the given dataflow.
351,146
def reasons_to_paths(reasons): blockers = set(reasons.keys()) - set(reasons.values()) paths = set() for blocker in blockers: path = [blocker] parent = reasons[blocker] while parent: if parent in path: raise CircularDependencyError(dict(parent=parent, ...
Calculate the dependency paths to the reasons of the blockers. Paths will be in reverse-dependency order (i.e. parent projects are in ascending order).
351,147
def get_args(self): return [ self.task_cls.__module__, self.task_cls.__name__, self.encode_list(self.task_params), self.encode_list(self.branches), self.encode_bool(self.auto_retry), self.encode_list(self.dashboard_data), ]
Returns the list of encoded job arguments. The order of this list corresponds to the arguments expected by the job wrapper script.
351,148
def gate(self, name, params, qubits): return self.inst(Gate(name, params, [unpack_qubit(q) for q in qubits]))
Add a gate to the program. .. note:: The matrix elements along each axis are ordered by bitstring. For two qubits the order is ``00, 01, 10, 11``, where the the bits **are ordered in reverse** by the qubit index, i.e., for qubits 0 and 1 the bitstring ``01`` indicates that ...
351,149
def predict(self, X, categorical=None): assert hasattr(self, ), "Model not yet fitted." if categorical is not None: assert isinstance(categorical, (int, list, tuple)), "The \ argument needs to be an integer with the index of the categorical \ column...
Predict the closest cluster each sample in X belongs to. Parameters ---------- X : array-like, shape = [n_samples, n_features] New data to predict. categorical : Indices of columns that contain categorical data Returns ------- labels : array, shape [...
351,150
def data_to_sys_base(self): if not self.n or self._flags[] is True: return self.copy_data_ext(model=, field=, dest=, idx=self.gen) super(GovernorBase, self).data_to_sys_base() self._store[] = self.R self.R = self.system.mva * div(self.R, self.Sn)
Custom system base conversion function
351,151
def get_metadata(filename, scan, paramfile=, **kwargs): d = {} d[] = os.path.abspath(filename.rstrip()) d[] = os.path.dirname(d[]) params = pp.Params(paramfile) for k in params.defined: d[k] = params[k] for key in kwargs.keys(): logger.info( % (key...
Function to scan data (a small read) and define parameters used elsewhere. filename needs full path. Examples include, read/bgsub windows, image grid, memory profile. If pickle file doesn't exist, it creates one. Either way, dictionary is returned with info.
351,152
def compare_models(dataset, models, model_names=None, user_sample=1.0, metric=, target=None, exclude_known_for_precision_recall=True, make_plot=False, verbose=True, **kwargs): num_models = len(mod...
Compare the prediction or recommendation performance of recommender models on a common test dataset. Models that are trained to predict ratings are compared separately from models that are trained without target ratings. The ratings prediction models are compared on root-mean-squared error, and the re...
351,153
def zpk2ss(z, p, k): import scipy.signal return scipy.signal.zpk2ss(z,p,k)
Zero-pole-gain representation to state-space representation :param sequence z,p: Zeros and poles. :param float k: System gain. :return: * A, B, C, D : ndarray State-space matrices. .. note:: wrapper of scipy function zpk2ss
351,154
def reset(self, iface=None, client_mac=None, xid=None, scriptfile=None): logger.debug() if iface is None: iface = conf.iface if client_mac is None: tempmac = get_if_raw_hwaddr(iface) if isinstance(tempmac, tuple) and len(tempmac) == 2: ...
Reset object attributes when state is INIT.
351,155
def from_(cls, gsim): ltbranch = N(, {: }, nodes=[N(, text=str(gsim)), N(, text=)]) lt = N(, {: }, nodes=[N(, {: }, nodes=[N(, {: , : , ...
Generate a trivial GsimLogicTree from a single GSIM instance.
351,156
def _extract_from_bundle(b, compute, times=None, allow_oversample=False, by_time=True, **kwargs): provided_times = times times = [] infolists = [] needed_syns = [] for dataset in b.fi...
Extract a list of sorted times and the datasets that need to be computed at each of those times. Any backend can then loop through these times and see what quantities are needed for that time step. Empty copies of synthetics for each applicable dataset are then created and returned so that they can be...
351,157
def write_to_file(self, path, filename): self.filename = filename categories_path = _generate_dir_structure(path) full_path =(categories_path + "\\" + self.notebook_type + "\\" + filename + ".ipynb").replace("\\", "/") nb.write(self.notebook, full...
Class method responsible for generating a file containing the notebook object data. ---------- Parameters ---------- path : str biosignalsnotebooks Root folder path (where the notebook will be stored). filename : str Defines the name of the notebook file...
351,158
def tasks(self): tasks = set() for ctrl in self.controllers.values(): tasks.update(ctrl.tasks) return tasks
Tasks in this exact group
351,159
def mnist_tutorial(train_start=0, train_end=60000, test_start=0, test_end=10000, nb_epochs=NB_EPOCHS, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, testing=False, label_smoothing=0.1): report = AccuracyReport() tf.set_random_seed(1234) c...
MNIST CleverHans tutorial :param train_start: index of first training set example :param train_end: index of last training set example :param test_start: index of first test set example :param test_end: index of last test set example :param nb_epochs: number of epochs to train model :param batch_size: size ...
351,160
def headers_to_dict(headers): hdrs = {} for h, v in headers: h = h.lower() if h in hdrs: if isinstance(hdrs[h], list): hdrs[h].append(v) else: hdrs[h] = [hdrs[h], v] else: hdrs[h] = v return hdrs
Converts a sequence of (name, value) tuples into a dict where if a given name occurs more than once its value in the dict will be a list of values.
351,161
def write_pretty_dict_str(out, obj, indent=2): json.dump(obj, out, indent=indent, sort_keys=True, separators=(, ), ensure_ascii=False, encoding="utf-8")
writes JSON indented representation of `obj` to `out`
351,162
async def addLayer(self, **info): identypeownerconfig iden = info.pop(, None) if iden is None: iden = s_common.guid() node = await self.hive.open((, , iden)) layrinfo = await node.dict() layrconf = await (await node.open((,))).dict() await layrinfo....
Add a Layer to the cortex. Notes: The addLayer ``**info`` arg is expected to be shaped like the following:: info = { 'iden': <str>, ( optional iden. default guid() ) 'type': <str>, ( optional type. default lmdb ) 'owner':...
351,163
def phasicNet(self,biggestEvent=50,m1=.5,m2=None): m1=0 if m1 is None else self.pointsPerSec*m1 m2=-1 if m2 is None else self.pointsPerSec*m2 Y=self.sweepYsmartbase()[int(m1):int(m2)] nBins=1000 hist,bins=np.histogram(Y,bins=nBins,range=[-bi...
Calculates the net difference between positive/negative phasic events Returns return the phasic difference value of the current sweep. Arguments: biggestEvent (int): the size of the largest event anticipated m1 (int, optional): the time (sec) to start analyzing m2 (i...
351,164
def set_to_restart(self, instance): self.to_restart.append(instance) if instance.is_external: instance.proc = None
Put an instance to the restart queue :param instance: instance to restart :type instance: object :return: None
351,165
def sorted(cls, items, orders): return sorted(items, cmp=cls.multipleOrderComparison(orders))
Returns the elements in `items` sorted according to `orders`
351,166
def from_string(cls, rgb_hex_str): r = int(rgb_hex_str[:2], 16) g = int(rgb_hex_str[2:4], 16) b = int(rgb_hex_str[4:], 16) return cls(r, g, b)
Return a new instance from an RGB color hex string like ``'3C2F80'``.
351,167
def jr6_jr6(mag_file, dir_path=".", input_dir_path="", meas_file="measurements.txt", spec_file="specimens.txt", samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt", specnum=1, samp_con=, location=, lat=, lon=, noave=False, meth_code="LP-NO", volume=12...
Convert JR6 .jr6 files to MagIC file(s) Parameters ---------- mag_file : str input file name dir_path : str working directory, default "." input_dir_path : str input file directory IF different from dir_path, default "" meas_file : str output measurement file nam...
351,168
def _parse_ams_netid(ams_netid): try: id_numbers = list(map(int, ams_netid.split("."))) except ValueError: raise ValueError("no valid netid") if len(id_numbers) != 6: raise ValueError("no valid netid") ams_netid_st = SAmsNetId() ams_netid_st.b = (c...
Parse an AmsNetId from *str* to *SAmsNetId*. :param str ams_netid: NetId as a string :rtype: SAmsNetId :return: NetId as a struct
351,169
def error(self, cmd, desc=): return self._label_desc(cmd, desc, self.error_color)
Style for an error message.
351,170
def update_ipaddress(self): self.old_ip = self.my_ip self.my_ip = try: obj = urllib.request.urlopen(settings.get(, )) results = self.ip_regex.findall(obj.read()) if len(results) > 0: self.my_...
Updates the scheduler so it knows its own ip address
351,171
def get_ticket(self, ticket_id): msg = self.__request(.format(str(ticket_id), )) status_code = self.__get_status_code(msg) if status_code == 200: pairs = {} msg = msg.split() if (len(msg) > 2) and self.RE_PATTERNS[].match(msg[2]): retu...
Fetch ticket by its ID. :param ticket_id: ID of demanded ticket :returns: Dictionary with key, value pairs for ticket with *ticket_id* or None if ticket does not exist. List of keys: * id * numerical_id * Queue ...
351,172
def to_str(self): return etree.tostring(self.root, xml_declaration=True, standalone=True, pretty_print=True)
Returns a string of the SVG figure.
351,173
def extract_from_system(cert_callback=None, callback_only_on_failure=False): certificates = {} processed = {} now = datetime.datetime.utcnow() for store in ["ROOT", "CA"]: store_handle = crypt32.CertOpenSystemStoreW(null(), store) handle_error(store_handle) context_point...
Extracts trusted CA certificates from the Windows certificate store :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate ...
351,174
def pop_message(self, wait=SECOND, till=None): if till is not None and not isinstance(till, Signal): Log.error("Expecting a signal") message = self.queue.read(wait_time_seconds=mo_math.floor(wait.seconds)) if not message: return None message.delete = lam...
RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE
351,175
def get_family(self, node): return set(p if c == node else c for p, c in self.get_edges(node))
RETURN ALL ADJACENT NODES
351,176
def is_editable(obj, request): if hasattr(obj, "is_editable"): return obj.is_editable(request) else: codename = get_permission_codename("change", obj._meta) perm = "%s.%s" % (obj._meta.app_label, codename) return (request.user.is_authenticated() and has_site_...
Returns ``True`` if the object is editable for the request. First check for a custom ``editable`` handler on the object, otherwise use the logged in user and check change permissions for the object's model.
351,177
def csvpatch_cmd(input_csv, input=None, output=None, strict=True): patch_stream = (sys.stdin if input is None else open(input)) tocsv_stream = (sys.stdout if output is None else open(output, )) fromcsv_stream = open(input_c...
Apply the changes from a csvdiff patch to an existing CSV file.
351,178
def close(self, end_time=None): self._check_ended() if end_time: self.end_time = end_time else: self.end_time = time.time() self.in_progress = False
Close the trace entity by setting `end_time` and flip the in progress flag to False. :param int end_time: Epoch in seconds. If not specified current time will be used.
351,179
def _apply_search_backrefs(pattern, flags=0): if isinstance(pattern, (str, bytes)): re_verbose = bool(VERBOSE & flags) re_unicode = None if bool((ASCII | LOCALE) & flags): re_unicode = False elif bool(UNICODE & flags): re_unicode = True if not (f...
Apply the search backrefs to the search pattern.
351,180
def get_token(self, lineno, col_offset): return self.get_token_from_offset(self._line_numbers.line_to_offset(lineno, col_offset))
Returns the token containing the given (lineno, col_offset) position, or the preceeding token if the position is between tokens.
351,181
def set_fen(self, fen: str) -> None: parts = fen.split() try: board_part = parts.pop(0) except IndexError: raise ValueError("empty fen") try: turn_part = parts.pop(0) except IndexError: turn = WHITE ...
Parses a FEN and sets the position from it. :raises: :exc:`ValueError` if the FEN string is invalid.
351,182
def mapFromChart( self, x, y ): grid = self.gridRect() hruler = self.horizontalRuler() vruler = self.verticalRuler() xperc = hruler.percentAt(x) yperc = vruler.percentAt(y) xoffset = grid.width() * xperc yo...
Maps a chart point to a pixel position within the grid based on the rulers. :param x | <variant> y | <variant> :return <QPointF>
351,183
def _control_resp(self, data, state): if _is_control_response(data): ack_state = bytes([data[22]]) if state == ack_state: _LOGGER.debug("Received state ack from %s, state: %s", self.host, ord(ack_state)) return ack_st...
Handle a control response. :param data: Payload. :param state: Requested state. :returns: Acknowledged state.
351,184
def _n_onset_midi(patterns): return len([o_m for pat in patterns for occ in pat for o_m in occ])
Computes the number of onset_midi objects in a pattern Parameters ---------- patterns : A list of patterns using the format returned by :func:`mir_eval.io.load_patterns()` Returns ------- n_onsets : int Number of onsets within the pattern.
351,185
def get(key, host=DEFAULT_HOST, port=DEFAULT_PORT): * conn = _connect(host, port) _check_stats(conn) return conn.get(key)
Retrieve value for a key CLI Example: .. code-block:: bash salt '*' memcached.get <key>
351,186
def __save_reference(self, o, cls, args, kwargs): if not o and cls: self[] = LazyBones( cls, args, kwargs ) else: while hasattr( o, ) and o.__class__ == Wrapper: o = o.wrapper__unwrap() self[] = o
Saves a reference to the original object Facade is passed. This will either be the object itself or a LazyBones instance for lazy-loading later :param mixed o: The original object :param class cls: The class definition for the original object :param tuple args: The positional arguments ...
351,187
def _match_minimum_decimal(self, match_key, decimal_value, match): if decimal_value is None: raise NullArgument() if match is None: match = True if match: gtelt = else: gtelt = if match_key in self._query_terms: ...
Matches a minimum decimal value
351,188
def cdhit_from_seqs(seqs, moltype, params=None): seqs = SequenceCollection(seqs, MolType=moltype) if params is None: params = {} if not in params: _, params[] = mkstemp() working_dir = mkdtemp() if moltype is PROTEIN: app = CD_HIT(WorkingDir=working_dir...
Returns the CD-HIT results given seqs seqs : dict like collection of sequences moltype : cogent.core.moltype object params : cd-hit parameters NOTE: This method will call CD_HIT if moltype is PROTIEN, CD_HIT_EST if moltype is RNA/DNA, and raise if any other moltype is passed.
351,189
def use(broker, debug=True, **kwargs): if not debug: log.setLevel(logging.INFO) if broker.lower() in ["xq", "雪球"]: return XueQiuTrader(**kwargs) if broker.lower() in ["yh_client", "银河客户端"]: from .yh_clienttrader import YHClientTrader return YHClientTrader() if broke...
用于生成特定的券商对象 :param broker:券商名支持 ['yh_client', '银河客户端'] ['ht_client', '华泰客户端'] :param debug: 控制 debug 日志的显示, 默认为 True :param initial_assets: [雪球参数] 控制雪球初始资金,默认为一百万 :return the class of trader Usage:: >>> import easytrader >>> user = easytrader.use('xq') >>> user.prepare('xq....
351,190
def describe_autocomplete(self, service, operation, param): service_index = self._index[service] LOG.debug(service_index) if param not in service_index.get(, {}).get(operation, {}): LOG.debug("param not in index: %s", param) return None p = service_index[...
Describe operation and args needed for server side completion. :type service: str :param service: The AWS service name. :type operation: str :param operation: The AWS operation name. :type param: str :param param: The name of the parameter being completed. This must ...
351,191
def diagonal_dot(a, b): a = np.asanyarray(a) result = np.dot(a * b, [1.0] * a.shape[1]) return result
Dot product by row of a and b. There are a lot of ways to do this though performance varies very widely. This method uses the dot product to sum the row and avoids function calls if at all possible. Comparing performance of some equivalent versions: ``` In [1]: import numpy as np; import t...
351,192
def main(argString=None): args = parseArgs(argString) checkArgs(args) logger.info("Options used:") for key, value in vars(args).iteritems(): logger.info(" --{} {}".format(key.replace("_", "-"), value)) logger.info("Reading MAP file") mapF = readMAP(args.tfile + ".map", ...
The main function of the module.. Here are the steps for duplicated samples: 1. Prints the options. 2. Reads the ``map`` file to gather marker's position (:py:func:`readMAP`). 3. Reads the ``tfam`` file (:py:func:`readTFAM`). 4. Finds the unique markers using the ``map`` file (...
351,193
def cylinders(shape: List[int], radius: int, ncylinders: int, phi_max: float = 0, theta_max: float = 90): r shape = sp.array(shape) if sp.size(shape) == 1: shape = sp.full((3, ), int(shape)) elif sp.size(shape) == 2: raise Exception("2D cylinders donphi_max must be betwen 0...
r""" Generates a binary image of overlapping cylinders. This is a good approximation of a fibrous mat. Parameters ---------- shape : list The size of the image to generate in [Nx, Ny, Nz] where N is the number of voxels. 2D images are not permitted. radius : scalar The ...
351,194
def create_exchange(self, vhost, name, xtype, auto_delete=False, durable=True, internal=False, arguments=None): vhost = quote(vhost, )...
Creates an exchange in the given vhost with the given name. As per the RabbitMQ API documentation, a JSON body also needs to be included that "looks something like this": {"type":"direct", "auto_delete":false, "durable":true, "internal":false, "arguments":[]} ...
351,195
def MoveDirectory(source_dir, target_dir): if not IsDir(source_dir): from ._exceptions import DirectoryNotFoundError raise DirectoryNotFoundError(source_dir) if Exists(target_dir): from ._exceptions import DirectoryAlreadyExistsError raise DirectoryAlreadyExistsError(target...
Moves a directory. :param unicode source_dir: :param unicode target_dir: :raises NotImplementedError: If trying to move anything other than: Local dir -> local dir FTP dir -> FTP dir (same host)
351,196
def contents(self): data = find_dataset_path( self.name, data_home=self.data_home, ext=None ) return os.listdir(data)
Contents returns a list of the files in the data directory.
351,197
def create_widget(self): d = self.declaration self.widget = RelativeLayout(self.get_context(), None, d.style)
Create the underlying widget.
351,198
def _check_elements_equal(lst): assert isinstance(lst, list), "Input value must be a list." return not lst or lst.count(lst[0]) == len(lst)
Returns true if all of the elements in the list are equal.
351,199
def load_foundation_sample_data(fd): fd.width = 16.0 fd.length = 18.0 fd.depth = 0.0 fd.mass = 0.0
Sample data for the Foundation object :param fd: Foundation Object :return: