Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
341,300
def chunks(iterator, size): for item in iterator: yield [item] + list(islice(iterator, size - 1))
Split an iterator into chunks with `size` elements each. Warning: ``size`` must be an actual iterator, if you pass this a concrete sequence will get you repeating elements. So ``chunks(iter(range(1000)), 10)`` is fine, but ``chunks(range(1000), 10)`` is not. Example: # si...
341,301
def _add_flow_v1_0(self, src, port, timeout, datapath): ofproto = datapath.ofproto parser = datapath.ofproto_parser match = parser.OFPMatch( in_port=port, dl_src=addrconv.mac.text_to_bin(src), dl_type=ether.ETH_TYPE_SLOW) actions = [parser.OFPActionOutpu...
enter a flow entry for the packet from the slave i/f with idle_timeout. for OpenFlow ver1.0.
341,302
def _SetTable(self, table): if not isinstance(table, TextTable): raise TypeError() self.Reset() self._table = copy.deepcopy(table._table) for row in self: row.table = self
Sets table, with column headers and separators.
341,303
def text_search(conn, search, *, language=, case_sensitive=False, diacritic_sensitive=False, text_score=False, limit=0, table=None): raise OperationError( )
Return all the assets that match the text search. The results are sorted by text score. For more information about the behavior of text search on MongoDB see https://docs.mongodb.com/manual/reference/operator/query/text/#behavior Args: search (str): Text search string to query the text index ...
341,304
def get_single_keywords(skw_db, fulltext): timer_start = time.clock() records = [] for single_keyword in skw_db.values(): for regex in single_keyword.regex: for match in regex.finditer(fulltext): span = (match.span()[0], match...
Find single keywords in the fulltext. :param skw_db: list of KeywordToken objects :param fulltext: string, which will be searched :return : dictionary of matches in a format { <keyword object>, [[position, position...], ], .. }
341,305
def hashes_get(versions_file, base_path): files = versions_file.files_get_all() result = {} for f in files: try: result[f] = functions.md5_file(base_path + f) except IOError: pass return result
Gets hashes for currently checked out version. @param versions_file: a common.VersionsFile instance to check against. @param base_path: where to look for files. e.g. './.update-workspace/silverstripe/' @return: checksums {'file1': 'hash1'}
341,306
def set_lowest_numeric_score(self, score): if self.get_lowest_numeric_score_metadata().is_read_only(): raise errors.NoAccess() try: score = float(score) except ValueError: raise errors.InvalidArgument() if not self._is_valid_decimal(s...
Sets the lowest numeric score. arg: score (decimal): the lowest numeric score raise: InvalidArgument - ``score`` is invalid raise: NoAccess - ``score`` cannot be modified *compliance: mandatory -- This method must be implemented.*
341,307
def _intersected_edge(self, edges, cut_edge): for edge in edges: if self._edges_intersect(edge, cut_edge): return edge
Given a list of *edges*, return the first that is intersected by *cut_edge*.
341,308
def edit(self, name, mark=False): self.api.edit(self, name, mark)
Edit this file or directory :param str name: new name for this entry :param bool mark: whether to bookmark this entry
341,309
def destroy(ctx, app, expire_hit, sandbox): if expire_hit: ctx.invoke(expire, app=app, sandbox=sandbox, exit=False) HerokuApp(app).destroy()
Tear down an experiment server.
341,310
def get(self, key, default=None): try: val = self if "." not in key: return self[key] for k in key.split(): if k.isdigit(): k = int(k) val = val[k] return val except (TypeError, K...
Access data via :param key: :param default: the default value :return:
341,311
def fromBasicServiceEndpoint(cls, endpoint): type_uris = endpoint.matchTypes(cls.openid_type_uris) if type_uris and endpoint.uri is not None: openid_endpoint = cls() openid_endpoint.parseService( endpoint.yadis_url, endp...
Create a new instance of this class from the endpoint object passed in. @return: None or OpenIDServiceEndpoint for this endpoint object
341,312
def auc(targets, predictions, average=, index_map=None): r _supervised_evaluation_error_checking(targets, predictions) _check_categorical_option_type(, average, [, None]) _check_prob_and_prob_vector(predictions) _check_target_not_float(targets) _check_index_map(index_map...
r""" Compute the area under the ROC curve for the given targets and predictions. Parameters ---------- targets : SArray An SArray containing the observed values. For binary classification, the alpha-numerically first category is considered the reference category. prediction...
341,313
def convert_kv_to_dict(data): output = {} for line in data.split("\n"): stripped = line.strip() if stripped: key, value = stripped.split("=", 1) output[key] = value return output
convert text values in format: key1=value1 key2=value2 to dict {'key1':'value1', 'key2':'value2'} :param data: string containing lines with these values :return: dict
341,314
def remove(self, value, _sa_initiator=None): key = self.keyfunc(value) if not self.__contains__(key) or value not in self[key]: raise sa_exc.InvalidRequestError( "Can not remove : collection holds for key . " "Possible cause: is th...
Remove an item by value, consulting the keyfunc for the key.
341,315
def filter_gaussian(self,sigmaMs=100,applyFiltered=False,applyBaseline=False): if sigmaMs==0: return self.dataY filtered=cm.filter_gaussian(self.dataY,sigmaMs) if applyBaseline: self.dataY=self.dataY-filtered elif applyFiltered: self.dataY=fil...
RETURNS filtered trace. Desn't filter it in place.
341,316
def die(exc: Exception = None, exit_code: int = 1) -> None: if exc: lines = traceback.format_exception( None, exc, exc.__traceback__) msg = "".join(lines) log.critical(msg) log.critical("Exiting with exit code {}",...
It is not clear that Python guarantees to exit with a non-zero exit code (errorlevel in DOS/Windows) upon an unhandled exception. So this function produces the usual stack trace then dies with the specified exit code. See http://stackoverflow.com/questions/9555133/e-printstacktrace-equivalent-in-python...
341,317
def encrypt_password(self, email, password): res = self.session.http.get(self._get_rsa_key_url, params=dict(username=email, donotcache=self.donotcache)) rsadata = self.session.http.json(res, schema=self._rsa_key_schema) rsa = RSA.construct((rsadata["publickey_mod"], rsadata["publickey_...
Get the RSA key for the user and encrypt the users password :param email: steam account :param password: password for account :return: encrypted password
341,318
def _GetActualName(name): if _allowCapitalizedNames: name = UncapitalizeVmodlName(name) for defMap in _dataDefMap, _managedDefMap, _enumDefMap: dic = defMap.get(name) if dic: return dic[0] return None
Note: Must be holding the _lazyLock
341,319
def update(self, level): sl = level + 1 stack = inspect.stack() try: self._get_vars(stack[:sl], scopes=[]) finally: del stack[:], stack
Update the current scope by going back `level` levels. Parameters ---------- level : int or None, optional, default None
341,320
def infer_transportation_mode(self, clf, min_time): for segment in self.segments: segment.infer_transportation_mode(clf, min_time) return self
In-place transportation mode inferring of segments Returns: This track
341,321
def create_timezone(tz, first_date=None, last_date=None): if isinstance(tz, pytz.tzinfo.StaticTzInfo): return _create_timezone_static(tz) first_date = dt.datetime.today() if not first_date else to_naive_utc(first_date) last_date = dt.datetime.today() if not last_date else to_naive_utc(la...
create an icalendar vtimezone from a pytz.tzinfo object :param tz: the timezone :type tz: pytz.tzinfo :param first_date: the very first datetime that needs to be included in the transition times, typically the DTSTART value of the (first recurring) event :type first_date: datetime.datetime ...
341,322
def checks(self): condition = lambda a: a.startswith() return (getattr(self, a) for a in dir(self) if condition(a))
Return the list of all check methods.
341,323
def V_vertical_conical(D, a, h): r if h < a: Vf = pi/4*(D*h/a)**2*(h/3.) else: Vf = pi*D**2/4*(h - 2*a/3.) return Vf
r'''Calculates volume of a vertical tank with a convex conical bottom, according to [1]_. No provision for the top of the tank is made here. .. math:: V_f = \frac{\pi}{4}\left(\frac{Dh}{a}\right)^2\left(\frac{h}{3}\right),\; h < a .. math:: V_f = \frac{\pi D^2}{4}\left(h - \frac{2a}{3}\rig...
341,324
def main(argv=sys.argv[1:]): usage = + __doc__ parser = OptionParser(usage) parser.add_option("-f", "--force", action=, default=False, help="make changes even if they cannot undone before saving the new file") parser.add_option("-m", "--min_level",...
Parses the command line comments.
341,325
def metta_config(quarter, num_dimensions): first_day, last_day = quarter_boundaries(quarter) return { : first_day, : last_day, : 3, : , : , : .format(quarter), : [.format(i) for i in range(num_dimensions)], }
Returns metta metadata for a quarter's SOC code classifier matrix Args: quarter (str) quarter, in format '2015Q1' num_dimensions (int) Number of features in matrix Returns: (dict) metadata suitable for metta.archive_train_test
341,326
def _copy_config_template(name, title, template, path, key, settings): puts("\nCopying configuration file") context = settings.config context.update({ "default_context": { "name": name, "title": title, }, "name": name, ...
Get and render tarbell_config.py.template from Tarbell default.
341,327
def _Pcn_zm(x, dsz, Nv, dimN=2, dimC=1): return normalise(zeromean(zpad(bcrop(x, dsz, dimN), Nv), dsz), dimN + dimC)
Projection onto dictionary update constraint set: support projection, mean subtraction, and normalisation. The result has the full spatial dimensions of the input. Parameters ---------- x : array_like Input array dsz : tuple Filter support size(s), specified using the same format ...
341,328
def stop_process(process): process.terminate() process.join(3) if process.is_alive() and os.name != : try: os.kill(process.pid, signal.SIGKILL) process.join() except OSError: return if process.is_alive(): raise RuntimeError("Unable to te...
Does its best to stop the process.
341,329
def split_by_list(self, train, valid): "Split the data between `train` and `valid`." return self._split(self.path, train, valid)
Split the data between `train` and `valid`.
341,330
def _check_column_lengths(self): column_lengths_dict = { name: len(xs) for (name, xs) in self.columns_dict.items() } unique_column_lengths = set(column_lengths_dict.values()) if len(unique_column_lengths) != 1: raise ValueError( ...
Make sure columns are of the same length or else DataFrame construction will fail.
341,331
def set_format_key_value(self, key, value): if self.format_keys is None: self.format_keys = [] self.FORMAT = {} if key not in self.FORMAT: self.format_keys.append(key) self.FORMAT[key] = value
Add a new key/value pair. Key in column 9 (FORMAT) and value in column 10. If key already exists, then updates the value to the new given value
341,332
def add_key(self, key, label, notes=None): order = { : key, : label, : notes, } return self.sshkey.createObject(order)
Adds a new SSH key to the account. :param string key: The SSH key to add :param string label: The label for the key :param string notes: Additional notes for the key :returns: A dictionary of the new key's information.
341,333
def concatenate(self, tup, axis=0): if not isinstance(tup, Sequence): tup = (tup,) if tup is (None,) or len(tup) is 0: return self tup = (self,) + tuple(tup) new_array = np.concatenate(tup, axis) if not all(hasattr(ts, ) and ha...
Join a sequence of Timeseries to this one Args: tup (sequence of Timeseries): timeseries to be joined with this one. They must have the same shape as this Timeseries, except in the dimension corresponding to `axis`. axis (int, optional): The axis along which timeseri...
341,334
def create_new_reference(self, obj, global_ref=False): opaque_ref = self.state.project.loader.extern_object.allocate() l.debug("Map %s to opaque reference 0x%x", obj, opaque_ref) if global_ref: self.global_refs[opaque_ref] = obj else: se...
Create a new reference thats maps to the given object. :param obj: Object which gets referenced. :param bool global_ref: Whether a local or global reference is created.
341,335
def do_diff(self, params): count = 0 for count, (diff, path) in enumerate(self._zk.diff(params.path_a, params.path_b), 1): if diff == -1: self.show_output("-- %s", path) elif diff == 0: self.show_output("-+ %s", path) elif diff...
\x1b[1mNAME\x1b[0m diff - Display the differences between two paths \x1b[1mSYNOPSIS\x1b[0m diff <src> <dst> \x1b[1mDESCRIPTION\x1b[0m The output is interpreted as: -- means the znode is missing in /new-configs ++ means the znode is new in /new-configs +- means the...
341,336
def process_format(self, kind, context): result = None while True: chunk = yield result if chunk is None: return split = -1 line = chunk.line try: ast.parse(line) except SyntaxError as e:
Handle transforming format string + arguments into Python code.
341,337
def timeout_process_add_queue(self, module, cache_time): if module in self.timeout_update_due: return key = self.timeout_queue_lookup.get(module) if key: queue_item = self.timeout_queue[key] queue_item.remove(module) if ...
Add a module to the timeout_queue if it is scheduled in the future or if it is due for an update immediately just trigger that. the timeout_queue is a dict with the scheduled time as the key and the value is a list of module instance names due to be updated at that point. An ordered lis...
341,338
def linear_sym(target, X, A1=, A2=): r A = _parse_args(target=target, key=A1, default=1.0) B = _parse_args(target=target, key=A2, default=0.0) X = target[X] a, b, x = _syp.symbols() y = a*x + b r, s1, s2 = _build_func(eq=y, a=a, b=b, x=x) r_val = r(A, B, X) s1_va...
r""" Calculates the rate, as well as slope and intercept of the following function at the given value of *x*: .. math:: r = A_{1} x + A_{2} Parameters ---------- A1 -> A2 : string The dictionary keys on the target object containing the coefficients values to...
341,339
def setField(self, new_value): self.field_strength = self.field_strength._replace( val=new_value )
Adjust the field of the magnet by the value of ``scalingFactor``. The adjustment is multiplicative, so a value of ``scalingFactor = 1.0`` will result in no change of the field.
341,340
def angsep(lon1, lat1, lon2, lat2): lon1,lat1 = np.radians([lon1,lat1]) lon2,lat2 = np.radians([lon2,lat2]) sdlon = np.sin(lon2 - lon1) cdlon = np.cos(lon2 - lon1) slat1 = np.sin(lat1) slat2 = np.sin(lat2) clat1 = np.cos(lat1) clat2 = np.cos(lat2) num1 = clat2 * sdlon ...
Angular separation (deg) between two sky coordinates. Borrowed from astropy (www.astropy.org) Notes ----- The angular separation is calculated using the Vincenty formula [1], which is slighly more complex and computationally expensive than some alternatives, but is stable at at all distances, in...
341,341
def _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, os_type, arch, graphics=None, loader=None, **kwargs): mem = int(mem) * 1024 context = { : hypervisor, : n...
Generate the XML string to define a libvirt VM
341,342
def logical_path(self): format_extension = self.format_extension or self.compiler_format_extension if format_extension is None: return self.path return self.path_without_suffix + format_extension
The logical path to asset. Example:: >>> attrs = AssetAttributes(environment, 'js/models.js.coffee') >>> attrs.logical_path 'js/models.js'
341,343
def invert(self): for poly in self.polygons: poly.flip() self.plane.flip() if self.front: self.front.invert() if self.back: self.back.invert() temp = self.front self.front = self.back self.back = temp
Convert solid space to empty space and empty space to solid space.
341,344
def _soup_strings(soup): paragraph_tags = set([ "caption", "details", "h1", "h2", "h3", "h4", "h5", "h6", "li", "p", "td", "div", "span" ]) skip_children = None for descendant in soup.descendants: if skip_children is not None: try: in_skip = descendant in skip_childre...
Return text strings in soup.
341,345
def toggle_line_numbers(self, checked): if self.tabwidget is None: return for editor in self.editors: editor.toggle_line_numbers(linenumbers=checked, markers=False) self.set_option(, checked)
Toggle line numbers.
341,346
def __get_by_info(post_id, catalog_id): recs = TabPost2Tag.select().where( (TabPost2Tag.post_id == post_id) & (TabPost2Tag.tag_id == catalog_id) ) if recs.count() == 1: return recs.get() elif recs.count() > 1: out_rec...
Geo the record by post and catalog.
341,347
def create_placement_group(self, name, strategy=): params = {:name, :strategy} group = self.get_status(, params, verb=) return group
Create a new placement group for your account. This will create the placement group within the region you are currently connected to. :type name: string :param name: The name of the new placement group :type strategy: string :param strategy: The placement strategy of th...
341,348
def affinity(self,affinity): with self.__lock: old_affinities = {} try: for thread in self.__threads: old_affinities[thread] = thread.affinity thread.affinity = affinity except Exception: for (th...
Set the affinity for all threads in this group. If setting affinity fails on any thread, the affinity of all threads is restored to its previous value.
341,349
def register_plugins(): if pkg_resources: for ep in pkg_resources.iter_entry_points(): plugin = ep.load() if hasattr(plugin, ) and hasattr(plugin.init, ): for arg in plugin.init._arguments: init.parser.add_argument(*arg[0], **a...
find any installed plugins and register them.
341,350
def invert(self): with self._cache: if in self._cache: self.face_normals *= -1.0 if in self._cache: self.vertex_normals *= -1.0 self.faces = np.fliplr(self.faces) self._cache.clear(exclude=[, ...
Invert the mesh in- place by reversing the winding of every face and negating normals without dumping the cache. Alters --------- self.faces : columns reversed self.face_normals : negated if defined self.vertex_normals : negated if defined
341,351
def read_magic_file(self, path, sort_by_this_name): DATA = {} try: with open(path, ) as finput: lines = list(finput.readlines()[1:]) except FileNotFoundError: return [] line = lines[0] header = line.strip().split(...
reads a magic formated data file from path and sorts the keys according to sort_by_this_name Parameters ---------- path : path to file to read sort_by_this_name : variable to sort data by
341,352
def add_enclosure(self, left_char, right_char): assert len(left_char) == 1, \ "Parameter left_char must be character not string" assert len(right_char) == 1, \ "Parameter right_char must be character not string" self._enclosure.add((left_char, right_char)) ...
Add new enclosure pair of characters. That and should be removed when their presence is detected at beginning and end of found URL :param str left_char: left character of enclosure pair - e.g. "(" :param str right_char: right character of enclosure pair - e.g. ")"
341,353
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): to_dir = os.path.abspath(to_dir) tgz_name = "setuptools-%s.tar.gz" % version url = download_base + tgz_na...
Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the nu...
341,354
def delete(self, table, where, values = ()) : sql = % (table, where) return self.execute(sql, values)
where is a string of condictions without the sql 'WHERE'. ex: deleteRabaObject('Gene', where = raba_id = ?, values = (33,))
341,355
def last_instr(self, start, end, instr, target=None, exact=True): code = self.code if not (start >= 0 and end <= len(code)): return None try: None in instr except: instr = [instr] result_offset = None curre...
Find the last <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be specified which must match precisely if exact is True, or if exact is False, the instruct...
341,356
def check_and_postprocess(args): with open(args.process_config) as in_handle: config = yaml.safe_load(in_handle) setup_local_logging(config) for dname in _find_unprocessed(config): lane_details = nglims.get_runinfo(config["galaxy_url"], config["galaxy_apikey"], dname, ...
Check for newly dumped sequencer output, post-processing and transferring.
341,357
def expand_braces(pattern): res = set() def remove_outer_braces(s): if s[0] == and s[-1] == : return s[1:-1] return s match = EXPAND_BRACES_RE.search(pattern) if match is not None: sub = match.group(1) v1, v2 = match.span(1) if "," in...
Find the rightmost, innermost set of braces and, if it contains a comma-separated list, expand its contents recursively (any of its items may itself be a list enclosed in braces). Return the full list of expanded strings.
341,358
def _potential_cross_partial_w(moment_index: int, op: ops.Operation, state: _OptimizerState) -> None: a = state.held_w_phases.get(op.qubits[0]) if a is None: return exponent, phase_exponent = cast(Tuple[float, float], ...
Cross the held W over a partial W gate. [Where W(a) is shorthand for PhasedX(phase_exponent=a).] Uses the following identity: ───W(a)───W(b)^t─── ≡ ───Z^-a───X───Z^a───W(b)^t────── (expand W(a)) ≡ ───Z^-a───X───W(b-a)^t───Z^a──── (move Z^a across, phasing axis) ≡ ───Z^-a───W(a-...
341,359
def detectFirefoxOSTablet(self): if self.detectIos() \ or self.detectAndroid() \ or self.detectSailfish(): return False if UAgentInfo.engineFirefox in self.__userAgent \ and UAgentInfo.deviceTablet in self.__userAgent: return True ...
Return detection of a Firefox OS tablet Detects a tablet (probably) running the Firefox OS.
341,360
def compute_gzip_md5(file_name): md5 = hashlib.md5() file_obj = gzip.open(file_name, ) for chunk in iter(lambda: file_obj.read(8192), ): md5.update(chunk) file_obj.close() return md5.hexdigest()
method traverses compressed file and calculates its MD5 checksum
341,361
def get_total_kl_cost(name="total_kl_cost", filter_by_name_substring=None): all_variable_metadata = get_variable_metadata(filter_by_name_substring) if not all_variable_metadata: tf.logging.warning("No Bayes by Backprop variables found!") return tf.constant(0.0, shape=()) return tf.add_n([md.kl_cost for...
Get the total cost for all (or a subset of) the stochastic variables. Args: name: A name for the tensor representing the total kl cost. filter_by_name_substring: A string used to filter which variables count toward the total KL cost. By default, this argument is `None`, and all variables trained ...
341,362
def _series_shaped(self): pages = self.pages pages.useframes = True lenpages = len(pages) def append_series(series, pages, axes, shape, reshape, name, truncated): page = pages[0] if not axes: shape = page.shape ...
Return image series in "shaped" file.
341,363
def use_economic_dtype(data3d, slope=1, inter=0, dtype=None): if dtype is None: dtype = data3d.dtype if issubclass(dtype.type, np.integer): mn = data3d.min() * slope + inter mx = data3d.max() * slope + inter if suits_with_dtype(mn, mx, dtype=np.uint8): ...
Use more economic integer-like dtype if it is possible. :param data3d: :param dtype: if dtype is not used, the automatic is used :return:
341,364
def get_parser(cls): organizer = cls() organizer.setup_parser() organizer._finish_parser() return organizer.parser
Function returning the command line parser for this class
341,365
def keys(self, prefix=None): query = Setting.query if prefix: query = query.filter(Setting.key.startswith(prefix)) return [i[0] for i in query.yield_per(1000).values(Setting.key)]
List all keys, with optional prefix filtering.
341,366
def erase_in_display(self, how=0, *args, **kwargs): if how == 0: interval = range(self.cursor.y + 1, self.lines) elif how == 1: interval = range(self.cursor.y) elif how == 2 or how == 3: interval = range(self.lines) self.dirty.update(interval...
Erases display in a specific way. Character attributes are set to cursor attributes. :param int how: defines the way the line should be erased in: * ``0`` -- Erases from cursor to end of screen, including cursor position. * ``1`` -- Erases from beginning of scree...
341,367
def pageNames(matching=False,workbooks=True,graphs=True): pages=[] if workbooks: pages.extend(PyOrigin.WorksheetPages()) if graphs: pages.extend(PyOrigin.GraphPages()) pages = [x.GetName() for x in pages] if matching: pages=[x for x in pages if matching ...
Returns the names of everything (books, notes, graphs, etc.) in the project. Args: matching (str, optional): if given, only return names with this string in it workbooks (bool): if True, return workbooks graphs (bool): if True, return workbooks Returns: A list of the names of w...
341,368
def _is_significant(stats, metrics=None): if metrics is None: metrics = (("max_enrichment", 3), ("roc_auc", 0.55), ("enr_at_fpr", 0.55)) for stat_name, min_value in metrics: if stats.get(stat_name, 0) < min_value: return False return True
Filter significant motifs based on several statistics. Parameters ---------- stats : dict Statistics disctionary object. metrics : sequence Metric with associated minimum values. The default is (("max_enrichment", 3), ("roc_auc", 0.55), ("enr_at_fpr", 0.55)) Return...
341,369
def GetRadioButtonSelect(selectList, title="Select", msg=""): root = tkinter.Tk() root.title(title) val = tkinter.IntVar() val.set(0) if msg != "": tkinter.Label(root, text=msg).pack() index = 0 for item in selectList: tkinter.Radiobutton(root, text=item, variable=val,...
Create radio button window for option selection title: Window name mag: Label of the radio button return (seldctedItem, selectedindex)
341,370
def bookmark_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/bookmarks api_path = "/api/v2/bookmarks.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/bookmarks#create-bookmark
341,371
def grep_full_py_identifiers(tokens): global py_keywords tokens = list(tokens) i = 0 while i < len(tokens): token_type, token = tokens[i] i += 1 if token_type != "id": continue while i+1 < len(tokens) and tokens[i] == ("op", ".") and tokens[i+1][0] == "id...
:param typing.Iterable[(str,str)] tokens: :rtype: typing.Iterator[str]
341,372
def stream(self, device=values.unset, sim=values.unset, status=values.unset, direction=values.unset, limit=None, page_size=None): limits = self._version.read_limits(limit, page_size) page = self.page( device=device, sim=sim, status=status, ...
Streams CommandInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param unicode device: The device :param...
341,373
def uniqify(cls, seq): seen = set() seen_add = seen.add return [ x for x in seq if x not in seen and not seen_add(x)]
Returns a unique list of seq
341,374
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs): * cache_valid_time = kwargs.pop(, 0) if salt.utils.data.is_true(refresh): refresh_db(cache_valid_time) return _get_upgradable(dist_upgrade, **kwargs)
List all available package upgrades. refresh Whether to refresh the package database before listing upgrades. Default: True. cache_valid_time .. versionadded:: 2016.11.0 Skip refreshing the package database if refresh has already occurred within <value> seconds d...
341,375
def _check_fpos(self, fp_, fpos, offset, block): if (fp_.tell() + offset != fpos): warnings.warn("Actual "+block+" header size does not match expected") return
Check file position matches blocksize
341,376
def parse( bin_payload, sender_script, recipient_address ): if len(bin_payload) < MIN_OP_LENGTHS[]: raise AssertionError("Payload is too short to be a namespace reveal") off = 0 life = None coeff = None base = None bucket_hex = None buckets = [] discount_hex = None nonalph...
NOTE: the first three bytes will be missing
341,377
def delete_cookie(self, cookie_name=None): if cookie_name is None: cookie_name = self.default_value[] return self.create_cookie("", "", cookie_name=cookie_name, kill=True)
Create a cookie that will immediately expire when it hits the other side. :param cookie_name: Name of the cookie :return: A tuple to be added to headers
341,378
def uptime_check_config_path(cls, project, uptime_check_config): return google.api_core.path_template.expand( "projects/{project}/uptimeCheckConfigs/{uptime_check_config}", project=project, uptime_check_config=uptime_check_config, )
Return a fully-qualified uptime_check_config string.
341,379
def _double_single_alleles(df, chrom): single_alleles = np.where( (df["chrom"] == chrom) & (df["genotype"].str.len() == 1) )[0] df.ix[single_alleles, "genotype"] = df.ix[single_alleles, "genotype"] * 2 return df
Double any single alleles in the specified chromosome. Parameters ---------- df : pandas.DataFrame SNPs chrom : str chromosome of alleles to double Returns ------- df : pandas.DataFrame SNPs with specified chromosome's single ...
341,380
def plot(x, y, rows=None, columns=None): if not rows or not columns: rows, columns = get_terminal_size() rows -= 4 x_scaled = scale(x, columns) y_scaled = scale(y, rows) canvas = [[ for _ in range(columns)] for _ in range(rows)] for ix, iy in zip(x_scaled, y_s...
x, y list of values on x- and y-axis plot those values within canvas size (rows and columns)
341,381
def _parse_file_usage(cls, action_class, args): fixed_files = {} variable_files = [] if not hasattr(action_class, ): return fixed_files, variable_files for file_arg in action_class.FILES: arg_value = args.get(file_arg) if arg_value is None:...
Find all external files referenced by an action.
341,382
def all_keys(self): keys = self.list_keys() keys.update(self.local_keys()) return keys
Merge managed keys with local keys
341,383
def geo_distance_range(cls, field, center, from_distance, to_distance, distance_type=None): instance = cls(geo_distance_range={: from_distance, : to_distance, field: center}) if distance_type is not None: instance[][] = distance_type return instance
http://www.elasticsearch.org/guide/reference/query-dsl/geo-distance-range-filter.html Filters documents that exists within a range from a specific point
341,384
def _read_frame(self): size = self.read_size() title = self._f.readline()[:-1] if self.symbols is None: symbols = [] coordinates = np.zeros((size, 3), float) for counter in range(size): line = self._f.readline() if len(line) == 0: ...
Read a frame from the XYZ file
341,385
def receive_information_confirmation(self, message): if message.api_version_is_supported(): self._next(InitializingMachine) else: self._next(UnsupportedApiVersion) self._communication.controller = message
A InformationConfirmation is received. If :meth:`the api version is supported <AYABInterface.communication.Communication.api_version_is_supported>`, the communication object transitions into a :class:`InitializingMachine`, if unsupported, into a :class:`UnsupportedApiVersion`
341,386
def _check_superbox_for_top_levels(self, boxes): self._check_superbox_for_top_levels(box.box)
Several boxes can only occur at the top level.
341,387
def hexdump(buf, num_bytes, offset=0, width=32): ind = offset end = offset + num_bytes lines = [] while ind < end: chunk = buf[ind:ind + width] actual_width = len(chunk) hexfmt = blocksize = 4 blocks = [hexfmt * blocksize for _ in range(actual_width // block...
Perform a hexudmp of the buffer. Returns the hexdump as a canonically-formatted string.
341,388
def start(self): if threading.current_thread().name == : signal.signal(signal.SIGINT, self.stop) logging.info(.format(self.address)) while True: self.process()
Start and listen for calls
341,389
def draw_slide(self, slide): image = Image.new(, (WIDTH, HEIGHT), ) draw = ImageDraw.Draw(image) draw.font = self.font self.draw_slide_text(draw, slide) self.draw_slide_images(draw, slide, image) return image
Return layout information for slide
341,390
def delete(self, remove_tombstone=True): response = self.repo.api.http_request(, self.uri) if response.status_code == 204: self._empty_resource_attributes() if remove_tombstone: self.repo.api.http_request(, % self.uri) return True
Method to delete resources. Args: remove_tombstone (bool): If True, will remove tombstone at uri/fcr:tombstone when removing resource. Returns: (bool)
341,391
def _commandline(self, *args, **kwargs): return [self.command_name] + self.transform_args(*args, **kwargs)
Returns the command line (without pipes) as a list.
341,392
def main_btn_clicked(self, widget, data=None): self.remove_link_button() data = dict() data[] = self.debugging self.run_window.hide() self.parent.open_window(widget, data)
Button switches to Dev Assistant GUI main window
341,393
def array_to_img(x, dim_ordering=(0, 1, 2), scale=True): x = x.transpose(dim_ordering) if scale: x += max(-np.min(x), 0) x_max = np.max(x) if x_max != 0: x = x / x_max x *= 255 if x.shape[2] == 3: ...
Converts a numpy array to PIL image object (uint8 format). Parameters ---------- x : numpy.array An image with dimension of 3 and channels of 1 or 3. dim_ordering : tuple of 3 int Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0). scale : boolean If True...
341,394
def get_first_post(self): cache_key = if not hasattr(self, cache_key): item = None res = self.post_set.all().order_by()[0:1] if len(res)>0: item = res[0] setattr(self, cache_key, item) return getattr(self, cache_key)
Retourne le premier post en date, celui créé lors de la création du fil
341,395
def parse(bin_payload, recipient, update_hash ): fqn = bin_payload if not is_name_valid( fqn ): log.warning("Name is invalid" % fqn) return None return { : , : fqn, : recipient, : update_hash }
# NOTE: first three bytes were stripped
341,396
def load_and_process_igor_model(self, marginals_file_name): raw_model = read_igor_marginals_txt(marginals_file_name) self.PV = raw_model[0][] self.PinsVD = raw_model[0][] self.PinsDJ = raw_model[0][] self.PdelV_given_V = raw_model[0][].T ...
Set attributes by reading a generative model from IGoR marginal file. Sets attributes PV, PdelV_given_V, PDJ, PdelJ_given_J, PdelDldelDr_given_D, PinsVD, PinsDJ, Rvd, and Rdj. Parameters ---------- marginals_file_name : str File name for a IGoR mode...
341,397
def registerThread(self, name, thread): if not isinstance(thread, threading.Thread): self.logger.error("Thread {0} is not actually a Thread!".format(name)) raise Exception("Thread {0} is not actually a Thread!".format(name)) if name in self.thread_list: self.logger.error("Thread {0} already registered!...
Register a new Thread , under the given descriptive name. Trying to register multiple threads under the same name will raise an Exception. Parameters ---------- name: string Name to register the given thread under. thread: threading.Thread, or a subclass Thread object to register.
341,398
def find_sinks(obj): SINK_ARGSPEC = [, ] return { n: m for n, m in inspect.getmembers(obj, inspect.ismethod) if inspect.getargspec(m)[0] == SINK_ARGSPEC }
Returns a dictionary of sink methods found on this object, keyed on method name. Sink methods are identified by (self, context) arguments on this object. For example: def f(self, context): ... is a sink method, but def f(self, ctx): ... is not.
341,399
def check_dependencies(self): "Checks if the test program is available in the python environnement" if self.test_program == : try: import nose except ImportError: sys.exit() if self.test_program == : try: import ...
Checks if the test program is available in the python environnement