Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
347,700
def iter_lines(f): linenum = 1 try: for text in f.readlines(): if text.isspace(): continue indent,value = parse_line(text) yield linenum,indent,value linenum += 1 except: raise ParserError(linenum, 0, , )
:param f: :type f: file :return:
347,701
def peek(self): peek_cursor = self.cursor + 1 if peek_cursor >= len(self.raw): return None else: return self.raw[peek_cursor]
Get the next character without moving the cursor.
347,702
def gfdist(target, abcorr, obsrvr, relate, refval, adjust, step, nintvls, cnfine, result=None): assert isinstance(cnfine, stypes.SpiceCell) assert cnfine.is_double() if result is None: result = stypes.SPICEDOUBLE_CELL(2000) else: assert isinstance(result, stypes.SpiceCell...
Return the time window over which a specified constraint on observer-target distance is met. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfdist_c.html :param target: Name of the target body. :type target: str :param abcorr: Aberration correction flag. :type abcorr: str :param o...
347,703
def connectAt(self, fromName, toName, position = None): fromLayer = self.getLayer(fromName) toLayer = self.getLayer(toName) if self.getLayerIndex(fromLayer) >= self.getLayerIndex(toLayer): raise NetworkError(, (fromLayer.name, toLayer.name)) if (fromLayer.type == )...
Connects two layers by instantiating an instance of Connection class. Allows a position number, indicating the ordering of the connection.
347,704
def registerRti(self, fullName, fullClassName, extensions=None, pythonPath=): check_is_a_sequence(extensions) extensions = extensions if extensions is not None else [] extensions = [prepend_point_to_extension(ext) for ext in extensions] regRti = RtiRegItem(fullName, fullClassNa...
Class that maintains the collection of registered inspector classes. Maintains a lit of file extensions that open the RTI by default.
347,705
def get_packaged_files(package_name): if not os.path.isdir(): return [] return [os.path.join(, filename) for filename in os.listdir()]
Collect relative paths to all files which have already been packaged
347,706
def get_diff(original, fixed, file_name, original_label=, fixed_label=): original, fixed = original.splitlines(True), fixed.splitlines(True) newline = from difflib import unified_diff diff = unified_diff(original, fixed, os.path.join(original_label, file_name)...
Return text of unified diff between original and fixed.
347,707
def sargasso_stats_table(self): headers = OrderedDict() headers[] = { : , : , : 100, : 0, : , : } headers[] = { : .format(config.read_count_prefix), : .format(config.read_count_desc...
Take the parsed stats from the sargasso report and add them to the basic stats table at the top of the report
347,708
def findrec(s, data): datablock = [] for rec in data: if s == rec[0]: datablock.append([rec[1], rec[2], rec[3], rec[4]]) return datablock
finds all the records belonging to s in data
347,709
def hyperparameters(self): hyperparameters = super(TensorFlow, self).hyperparameters() self.checkpoint_path = self.checkpoint_path or self._default_s3_path() mpi_enabled = False if self._script_mode_enabled(): additional_hyperparameters = {} if in sel...
Return hyperparameters used by your custom TensorFlow code during model training.
347,710
def reduce_freqs(freqlist): allfreqs = np.zeros_like(freqlist[0]) for f in freqlist: allfreqs += f return allfreqs
Add up a list of freq counts to get the total counts.
347,711
def fromJobGraph(cls, jobGraph): return cls(jobStoreID=jobGraph.jobStoreID, requirements=jobGraph._requirements, command=jobGraph.command, jobName=jobGraph.jobName, unitName=jobGraph.unitName, displayName=job...
Takes a job graph object and returns a job node object :param toil.jobGraph.JobGraph jobGraph: A job graph object to be transformed into a job node :return: A job node object :rtype: toil.job.JobNode
347,712
def preconstrain_file(self, content, simfile, set_length=False): repair_entry_state_opts = False if o.TRACK_ACTION_HISTORY in self.state.options: repair_entry_state_opts = True self.state.options -= {o.TRACK_ACTION_HISTORY} if set_length: simfile.ha...
Preconstrain the contents of a file. :param content: The content to preconstrain the file to. Can be a bytestring or a list thereof. :param simfile: The actual simfile to preconstrain
347,713
def _advance_frame(self): self.current_frame += 1 if self.current_frame == self.frame_len: self.current_frame = 0
Sets `self.current_frame` to the next frame, looping to the beginning if needed.
347,714
def position_with_ref(msg, lat_ref, lon_ref): tc = typecode(msg) if 5<=tc<=8: return surface_position_with_ref(msg, lat_ref, lon_ref) elif 9<=tc<=18 or 20<=tc<=22: return airborne_position_with_ref(msg, lat_ref, lon_ref) else: raise RuntimeError("incorrect or inconsistan...
Decode position with only one message, knowing reference nearby location, such as previously calculated location, ground station, or airport location, etc. Works with both airborne and surface position messages. The reference position shall be with in 180NM (airborne) or 45NM (surface) of the true p...
347,715
def handle_url(url, session, res): print("Parsing", url, file=sys.stderr) try: data = getPageContent(url, session) except IOError as msg: print("ERROR:", msg, file=sys.stderr) return for match in page_matcher.finditer(data): page_url = match.group(1) page_url...
Parse one search result page.
347,716
def choose(is_accepted, accepted, rejected, name=None): if not is_namedtuple_like(accepted): return _choose_base_case(is_accepted, accepted, rejected, name=name) if not isinstance(accepted, type(rejected)): raise TypeError( .format( type(accepted).__name__, ...
Helper which expand_dims `is_accepted` then applies tf.where.
347,717
def parse(self, path, args=None, unsaved_files=None, options = 0): return TranslationUnit.from_source(path, args, unsaved_files, options, self)
Load the translation unit from the given source code file by running clang and generating the AST before loading. Additional command line parameters can be passed to clang via the args parameter. In-memory contents for files can be provided by passing a list of pairs to as unsaved_files...
347,718
def listMigrationBlocks(self, migration_request_id=""): conn = self.dbi.connection() try: return self.mgrblklist.execute(conn, migration_request_id=migration_request_id) finally: if conn: conn.close()
get eveything of block that is has status = 0 and migration_request_id as specified.
347,719
def _sanitize_outputs(self): ret = {} if self.outputs is None: return if not isinstance(self.outputs, (list, tuple)): raise TypeError("Argument to outputs must be either list or tuple, given: %s" % str(type(self.outputs))) for output in self.outputs: if not...
Sanitizes output fields and returns a map <stream_id -> list of output fields>
347,720
def encode_async_options(async): options = copy.deepcopy(async._options) options[] = reference_to_path(async.__class__) return options
Encode Async options for JSON encoding.
347,721
def extra_prepare(self, configuration, args_dict): aws_syncr = args_dict.pop("aws_syncr") self.configuration.update( { "$@": aws_syncr.get("extra", "") , "aws_syncr": aws_syncr , "templates": {} , "config_folder": self.configuration_folder ...
Called before the configuration.converters are activated
347,722
def is_config(python2=None, python3=None, windows=None, linux=None, osx=None): return ( python2 in (None, is_python2) and python3 in (None, is_python3) and windows in (None, is_windows) and linux in (None, is_linux) and osx in (None, is_osx) )
Check if a specific configuration of Python version and operating system matches the user's setup. Mostly used to display targeted error messages. python2 (bool): spaCy is executed with Python 2.x. python3 (bool): spaCy is executed with Python 3.x. windows (bool): spaCy is executed on Windows. linu...
347,723
def delete_cached_branch_info(self): if os.path.isfile(constants.cached_branch_info): logger.debug() os.remove(constants.cached_branch_info) else: logger.debug()
Deletes cached branch_info file
347,724
def getMetricsColumnLengths(self): displayLen = 0 descLen = 0 for m in self.metrics: displayLen = max(displayLen, len(m[])) descLen = max(descLen, len(m[])) return (displayLen, descLen)
Gets the maximum length of each column
347,725
def find_split_node(mst_wood, i): for mst_index, mst in enumerate(mst_wood): if i in mst[]: return (mst_index, mst[].index(i)) raise ValueError( % i)
Parameters ---------- mst_wood : list of dictionarys i : int Number of the stroke where one mst gets split Returns ------- tuple : (mst index, node index)
347,726
def bar(self, serie, rescale=False): serie_node = self.svg.serie(serie) bars = self.svg.node(serie_node[], class_="histbars") points = serie.points for i, (y, x0, x1) in enumerate(points): if None in (x0, x1, y) or (self.logarithmic and y <= 0): cont...
Draw a bar graph for a serie
347,727
def src_process(state, input_data, output_data, ratio, end_of_input=0): input_frames, _ = _check_data(input_data) output_frames, _ = _check_data(output_data) data = ffi.new() data.input_frames = input_frames data.output_frames = output_frames data.src_ratio = ratio data.data_in = ffi.ca...
Standard processing function. Returns non zero on error.
347,728
def _add_dimensions(self, item, dims, constant_keys): if isinstance(item, Layout): item.fixed = False dim_vals = [(dim, val) for dim, val in dims[::-1] if dim not in self.drop] if isinstance(item, self.merge_type): new_item = item.clone(cdims...
Recursively descend through an Layout and NdMapping objects in order to add the supplied dimension values to all contained HoloMaps.
347,729
def SWAP(self, *operands): a = operands[0] b = operands[-1] return (b,) + operands[1:-1] + (a,)
Exchange 1st and 2nd stack items
347,730
def main(): parser = argparse.ArgumentParser( description=, epilog= ) parser.add_argument(, action=, version=.format(__version__)) parser.add_argument(, type=argparse.FileType(), nargs=, default=sys.stdin, help=) parser.add_argument(, , type=ar...
Execute command line interface.
347,731
def integrate_shown_data(scale=1, fyname=1, autozero=0, **kwargs): def I(x,y): xout, iout = _fun.integrate_data(x, y, autozero=autozero) print("Total =", scale*iout[-1]) return xout, scale*iout if fyname==1: fyname = "$"+str(scale)+"\\times \\int dx$" manipulate_shown_data(I,...
Numerically integrates the data visible on the current/specified axes using scale*fun.integrate_data(x,y). Modifies the visible data using manipulate_shown_data(**kwargs) autozero is the number of data points used to estimate the background for subtraction. If autozero = 0, no background subtraction is...
347,732
def update_running_pids(old_procs): new_procs = [] for proc in old_procs: if proc.poll() is None and check_pid(proc.pid): publisher.debug(str(proc.pid) + ) new_procs.append(proc) else: try: publisher.debug(str(proc.pid) + ) ...
Update the list of the running process and return the list
347,733
def create_marker_index(self): if not self.es.indices.exists(index=self.marker_index): self.es.indices.create(index=self.marker_index)
Create the index that will keep track of the tasks if necessary.
347,734
def output_sub_generic(gandi, data, output_keys, justify=10): for key in output_keys: if key in data: output_sub_line(gandi, key, data[key], justify)
Generic helper to output info from a data dict.
347,735
def get_value_at(all_info, current_path, key, to_string=False): keys = key.split() if keys[-1] == : target_obj = current_path[len(keys)-1] else: if key == : target_path = current_path elif in key: target_path = [] for i, key in enumerate(keys...
Get value located at a given path :param all_info: :param current_path: :param key: :param to_string: :return:
347,736
def DD_carrier_sync(z,M,BnTs,zeta=0.707,type=0): Ns = 1 Kp = np.sqrt(2.) z_prime = np.zeros_like(z) a_hat = np.zeros_like(z) e_phi = np.zeros(len(z)) theta_h = np.zeros(len(z)) theta_hat = 0 K0 = 1; K1 = 4*zeta/(zeta + 1/(4*zeta))*BnTs/Ns/Kp/K0; K2 = 4/(zeta + 1/(4*ze...
z_prime,a_hat,e_phi = DD_carrier_sync(z,M,BnTs,zeta=0.707,type=0) Decision directed carrier phase tracking z = complex baseband PSK signal at one sample per symbol M = The PSK modulation order, i.e., 2, 8, or 8. BnTs = time bandwidth product of loop bandwidth and the symbol period...
347,737
def init(name, config=None, cpuset=None, cpushare=None, memory=None, profile=None, network_profile=None, nic_opts=None, cpu=None, autostart=True, password=None, password_encrypted=None, users=None, dnsse...
Initialize a new container. This is a partial idempotent function as if it is already provisioned, we will reset a bit the lxc configuration file but much of the hard work will be escaped as markers will prevent re-execution of harmful tasks. name Name of the container image A tar...
347,738
def get_context_data(self, **kwargs): context = super(TabView, self).get_context_data(**kwargs) return context
Adds tab information to context. To retrieve a list of all group tab instances, use ``{{ tabs }}`` in your template. The id of the current tab is added as ``current_tab_id`` to the template context. If the current tab has a parent tab the parent's id is added to the te...
347,739
def duration(self): return max([x.comp_location + x.duration for x in self.segments])
Get duration of composition
347,740
def has_field(mc, field_name): try: mc._meta.get_field(field_name) except FieldDoesNotExist: return False return True
detect if a model has a given field has :param field_name: :param mc: :return:
347,741
def collect(path, no_input): if exists(path): msg = log.warning(msg, path) if not no_input: click.confirm(, abort=True) log.info(, path) shutil.rmtree(path) prefix = current_app.static_url_path or current_app.static_folder if prefix.startswith(): ...
Collect static files
347,742
def sqlvm_list( client, resource_group_name=None): if resource_group_name: return client.list_by_resource_group(resource_group_name=resource_group_name) return client.list()
Lists all SQL virtual machines in a resource group or subscription.
347,743
def write_to_file(self, fn): with open(fn, ) as f: f.write(.format(self.molecule.title)) f.write(.format(self.subtitle)) def write_grid_line(n, v): f.write( % (n, v[0], v[1], v[2])) write_grid_line(self.molecule.size, self.origin) ...
Write the cube to a file in the Gaussian cube format.
347,744
def _handle_eio_message(self, sid, data): if sid in self._binary_packet: pkt = self._binary_packet[sid] if pkt.add_attachment(data): del self._binary_packet[sid] if pkt.packet_type == packet.BINARY_EVENT: self._handle_event(sid...
Dispatch Engine.IO messages.
347,745
def add(self, *items): for item in items: self.unsorted.append(item) key = item[0] self.index[key] = item return self
Add items to be sorted. @param items: One or more items to be added. @type items: I{item} @return: self @rtype: L{DepList}
347,746
def plot_latent_scatter(self, labels=None, which_indices=None, legend=True, plot_limits=None, marker=, num_samples=1000, projection=, **kwargs): ...
Plot a scatter plot of the latent space. :param array-like labels: a label for each data point (row) of the inputs :param (int, int) which_indices: which input dimensions to plot against each other :param bool legend: whether to plot the legend on the figure :param plot_limits: the plot limits for the ...
347,747
def mag_pmf(matrix): nmags, ndists, nlons, nlats, neps = matrix.shape mag_pmf = numpy.zeros(nmags) for i in range(nmags): mag_pmf[i] = numpy.prod( [1. - matrix[i, j, k, l, m] for j in range(ndists) for k in range(nlons) for l in range(nlats) ...
Fold full disaggregation matrix to magnitude PMF. :returns: 1d array, a histogram representing magnitude PMF.
347,748
def transfer_credits(self, credits, can_use_my_credits_when_they_run_out): body = { "Credits": credits, "CanUseMyCreditsWhenTheyRunOut": can_use_my_credits_when_they_run_out} response = self._post(self.uri_for(), json.dumps(body)) return json_to_py(response)
Transfer credits to or from this client. :param credits: An Integer representing the number of credits to transfer. This value may be either positive if you want to allocate credits from your account to the client, or negative if you want to deduct credits from the client back int...
347,749
def _getStartRow(self, bookmark): bookMarkDict = json.loads(bookmark) realpath = os.path.realpath(self._filename) bookMarkFile = bookMarkDict.get(, None) if bookMarkFile != realpath: print ("Ignoring bookmark due to mismatch between FilecurrentRow']
Extracts start row from the bookmark information
347,750
def bsp_traverse_post_order( node: tcod.bsp.BSP, callback: Callable[[tcod.bsp.BSP, Any], None], userData: Any = 0, ) -> None: _bsp_traverse(node.post_order(), callback, userData)
Traverse this nodes hierarchy with a callback. .. deprecated:: 2.0 Use :any:`BSP.post_order` instead.
347,751
def _helper( self, host=None, port=None, debug=False, ssl=None, sock=None, workers=1, loop=None, protocol=HttpProtocol, backlog=100, stop_event=None, register_sys_signals=True, run_async=False, auto_reload=Fa...
Helper function used by `run` and `create_server`.
347,752
def registIssue(self, CorpNum, cashbill, Memo, UserID=None): if cashbill == None: raise PopbillException(-99999999, "현금영수증 정보가 입력되지 않았습니다.") postData = "" if Memo != None or Memo != : cashbill.memo = Memo postData = self._stringtify(cashbill)...
현금영수증 즉시발행 args CorpNum : 팝빌회원 사업자번호 cashbill : 등록할 현금영수증 object. made with Cashbill(...) UserID : 팝빌회원 아이디 return 처리결과. consist of code and message raise PopbillException
347,753
def build_parallel(parallel_mode, quiet=True, processes=4, user_modules=None, dispatcher_options=None): if user_modules is None: user_modules = [ ] if dispatcher_options is None: dispatcher_options = dict() dispatchers = (, ) parallel_modes = (, ) + dispatchers...
initializes `Parallel` Parameters ---------- parallel_mode : str "multiprocessing" (default), "htcondor" or "subprocess" quiet : bool, optional if True, progress bars will not be shown in the "multiprocessing" mode. process : int, optional The number of processes when ``para...
347,754
def intersection(self, *iterables): comb = self._set.intersection(*iterables) new_set = self.__class__(key=self._key, load=self._load, _set=comb) return new_set
Return a new set with elements common to the set and all *iterables*.
347,755
def get_stats(self): ostr = errtotal = self.deletions[]+self.insertions[]+self.mismatches ostr += "ALIGNMENT_COUNT\t"+str(self.alignment_count)+"\n" ostr += "ALIGNMENT_BASES\t"+str(self.alignment_length)+"\n" ostr += "ANY_ERROR\t"+str(errtotal)+"\n" ostr += "MISMATCHES\t"+str(self.mismatch...
Return a string describing the stats
347,756
def unescape( text ): if isinstance( text, basestring ): if in text: text = text.replace( , ) if in text: text = text.replace( , ) if in text: text = text.replace( , ) if in text: text = text.replace( , ) return t...
Inverse of escape.
347,757
def adapter(data, headers, table_format=, **kwargs): keys = (, , , , , , , ) if table_format == : delimiter = elif table_format == : delimiter = else: raise ValueError() ckwargs = {: delimiter, : } ckwargs.update(filter_dict_by_key(kwargs, keys)) ...
Wrap the formatting inside a function for TabularOutputFormatter.
347,758
def bookmark_show(bookmark_id_or_name): client = get_client() res = resolve_id_or_name(client, bookmark_id_or_name) formatted_print( res, text_format=FORMAT_TEXT_RECORD, fields=( ("ID", "id"), ("Name", "name"), ("Endpoint ID", "endpoint_id"), ...
Executor for `globus bookmark show`
347,759
def _get_possible_adapter_modes(interface, blacklist): adapter_modes = [] protocols = _load_config(, [])[].lower() sys_interface_path = os.readlink(.format(interface)) with salt.utils.files.fopen(.format(interface)) as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype =...
Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes
347,760
def off(self, name, callback): if callback not in self.__listeners[name]: raise InvalidListenerError self.__listeners[name].remove(callback)
Stop listening for the named event via the specified callback. :param name: the name of the event :type name: string :param callback: the callback that was originally used :type callback: callable
347,761
def _get_callable(self, func, *targets): if not callable(func): func_name = func func = next((getattr(obj, func, None) for obj in targets if func in dir(obj)), None) if not func: raise AttributeError( {}\ ...
If func is already a callable, it is returned directly. If it's a string, it is assumed to be a method on one of the objects supplied in targets and that is returned. If no method with the specified name is found, an AttributeError is raised. :param func: Callable or name of method on one objec...
347,762
def prepare(bedfile): pf = bedfile.rsplit(".", 1)[0] abedfile = pf + ".a.bed" bbedfile = pf + ".b.bed" fwa = open(abedfile, "w") fwb = open(bbedfile, "w") bed = Bed(bedfile) seen = set() for b in bed: accns = b.accn.split(";") new_accns = [] for accn in accn...
Remove prepended tags in gene names.
347,763
def get_metadata(self, filename): obj = self.bucket.Object(filename) checksum = .format(obj.e_tag[1:-1]) mime = obj.content_type.split(, 1)[0] if obj.content_type else None return { : checksum, : obj.content_length, : mime, : obj.l...
Fetch all availabe metadata
347,764
def random_product(*args, **kwds): pools = [tuple(pool) for pool in args] * kwds.get(, 1) return tuple(choice(pool) for pool in pools)
Draw an item at random from each of the input iterables. >>> random_product('abc', range(4), 'XYZ') # doctest:+SKIP ('c', 3, 'Z') If *repeat* is provided as a keyword argument, that many items will be drawn from each iterable. >>> random_product('abcd', range(4), repeat=2) # doctest...
347,765
def getResponse(self, http_request, amf_request): response = remoting.Envelope(amf_request.amfVersion) dl = [] def cb(body, name): response[name] = body for name, message in amf_request: processor = self.getProcessor(message) http_request.a...
Processes the AMF request, returning an AMF L{Response}. @param http_request: The underlying HTTP Request @type http_request: C{twisted.web.http.Request} @param amf_request: The AMF Request. @type amf_request: L{Envelope<pyamf.remoting.Envelope>}
347,766
def state(self): if self.humidity is None: return None humidity = round(float(self.humidity) / 100, 1) return humidity
Main state of sensor.
347,767
def meid(number, separator=u): 1B69B4BA630F34 if isinstance(number, six.string_types): number = re.sub(r, , number) try: number = % int(number, 16) except ValueError: if len(number) < 18 and number.isdigit(): return meid( % int(number), separato...
Printable Mobile Equipment Identifier (MEID) number. >>> print(meid(123456789012345678)) 1B 69B4BA 630F34 6 >>> print(meid('1B69B4BA630F34')) 1B 69B4BA 630F34 6
347,768
def indexables(self): if self._indexables is None: self._indexables = [] self._indexables.extend([ IndexCol(name=name, axis=axis, pos=i) for i, (axis, name) in enumerate(self.attrs.index_cols) ]) ...
create/cache the indexables if they don't exist
347,769
def timer(fun, *a, **k): @wraps(fun) def timer(*a, **k): start = arrow.now() ret = fun(*a, **k) end = arrow.now() print( % ( str(fun), str(start), str(end), str(end - start))) return ret return timer
define a timer for a rule function for log and statistic purposes
347,770
def getPID(self): if self._pid is not None: if not PlatformManager.isPIDValid(self._pid): self._pid = -1 return self._pid return -1
Returns the PID for the associated app (or -1, if no app is associated or the app is not running)
347,771
def load_manifest(app, filename=): if os.path.isabs(filename): path = filename else: path = pkg_resources.resource_filename(app, filename) with io.open(path, mode=, encoding=) as stream: data = json.load(stream) _registered_manifests[app] = path return data
Load an assets json manifest
347,772
def get_sample_window(self, type_tag, size): md5_list = self.data_store.get_sample_window(type_tag, size) return self.store_sample_set(md5_list)
Get a sample from the DataStore. Args: type_tag: the type of samples ('pcap','exe','pdf') size: the size of the window in MegaBytes (10 = 10MB) Returns: A sample_set handle which represents the newest samples within the size window
347,773
def split(nonce_string): timestamp_str = nonce_string[:time_str_len] try: timestamp = timegm(strptime(timestamp_str, time_fmt)) except AssertionError: timestamp = -1 if timestamp < 0: raise ValueError() return timestamp, nonce_string[time_str_len:]
Extract a timestamp from the given nonce string @param nonce_string: the nonce from which to extract the timestamp @type nonce_string: str @returns: A pair of a Unix timestamp and the salt characters @returntype: (int, str) @raises ValueError: if the nonce does not start with a correctly ...
347,774
def create_multidim_plot(parameters, samples, labels=None, mins=None, maxs=None, expected_parameters=None, expected_parameters_color=, plot_marginal=True, plot_scatter=True, marginal_percentiles=None, contour_percentiles...
Generate a figure with several plots and histograms. Parameters ---------- parameters: list Names of the variables to be plotted. samples : FieldArray A field array of the samples to plot. labels: dict, optional A dictionary mapping parameters to labels. If none provided, wi...
347,775
def show_orig(): if not nav: sys.exit(1) ecode = 0 try: image=contexts[][imagelist[0]] o = collections.OrderedDict() mymeta = {} mymeta.update(image.meta) o[] = mymeta.pop(, "N/A") o[] = image.get_alltags_current() o[] = image.get_distr...
Show image summary information
347,776
def on_exit(self): if not all([self.auto_write, self.commands, self.script, self.path]): return self.write()
atexit callback. If :attr:`Scrim.auto_write` is True write the scrim to :attr:`Scrim.path` as :attr:`Scrim.shell`
347,777
def concat(args): import pdb pdb.set_trace() t = [matlabarray(a) for a in args] return np.concatenate(t)
>>> concat([1,2,3,4,5] , [1,2,3,4,5]]) [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
347,778
def pauli(qubo): from blueqat.pauli import qubo_bit h = 0.0 assert all(len(q) == len(qubo) for q in qubo) for i in range(len(qubo)): h += qubo_bit(i) * qubo[i][i] for j in range(i + 1, len(qubo)): h += qubo_bit(i)*qubo_bit(j) * (qubo[i][j] + qubo[j][i]) return h
Convert to pauli operators of universal gate model. Requires blueqat.
347,779
def progress(self): total = len(self.all_jobs) remaining = total - len(self.active_jobs) if total > 0 else 0 percent = int(100 * (float(remaining) / total)) if total > 0 else 0 return percent
Returns the percentage, current and total number of jobs in the queue.
347,780
def _updateFilename(self): self._filename = self._filenameLineEdit.text() self._guessEncoding(self._filename) self._previewFile()
Calls several methods after the filename changed. This method is also a `SLOT`. It checks the encoding of the changed filename and generates a preview of the data.
347,781
def get_cluster_custom_object_scale(self, group, version, plural, name, **kwargs): kwargs[] = True if kwargs.get(): return self.get_cluster_custom_object_scale_with_http_info(group, version, plural, name, **kwargs) else: (data) = self.get_cluster_custom_objec...
get_cluster_custom_object_scale # noqa: E501 read scale of the specified custom object # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_cluster_custom_object_scale(group, version...
347,782
def doesIntersect(self, other): otherType = type(other) if issubclass(otherType, Ellipse): distance = self.center.distance(other.center) radiisum = self.radius + other.radius return distance <= radiisum if issubclass(otherType, Line): r...
:param: other - Circle class Returns True iff: self.center.distance(other.center) <= self.radius+other.radius
347,783
def get_droppables(self): droppables = [] for current_droppable in self.my_osid_object._my_map[]: droppables.append({ : current_droppable[], : self.get_matching_language_value(, dictionary=curre...
stub
347,784
def common_properties (self, build_request, requirements): assert isinstance(build_request, property_set.PropertySet) assert isinstance(requirements, property_set.PropertySet) free_unconditional = [] other = [] for p in requirements.al...
Given build request and requirements, return properties common to dependency build request and target build properties.
347,785
def purge(name, delete_key=True, quiet=False, path=None): data = _do_names(name, , path=path) if data is False: return data if delete_key: skey = salt.key.Key(__opts__) skey.delete_key(name) if data is None: return if not quiet: __jid_event__.fire_even...
Purge the named container and delete its minion key if present. WARNING: Destroys all data associated with the container. path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: bash salt-run lxc.purge name
347,786
def remove_genelist(self, list_id, case_obj=None): gene_list = self.gene_list(list_id) if case_obj: case_ids = [case_obj.id] else: case_ids = [case.id for case in gene_list.cases] self.session.delete(gene_list) case...
Remove a gene list and links to cases.
347,787
def like_hashtag(self, hashtag, amount=None): self.logger.info("Going to like media with hashtag medias = self.get_total_hashtag_medias(hashtag, amount) return self.like_medias(medias)
Likes last medias from hashtag
347,788
def zremrangebyrank(self, name, min, max): return self.execute_command(, name, min, max)
Remove all elements in the sorted set ``name`` with ranks between ``min`` and ``max``. Values are 0-based, ordered from smallest score to largest. Values can be negative indicating the highest scores. Returns the number of elements removed
347,789
def sinks(self): try: return self._sinks except AttributeError: self._sinks = find_sinks(self) return self._sinks
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.
347,790
def start_monitor(self): stdout_file, stderr_file = self.new_log_files("monitor") process_info = ray.services.start_monitor( self._redis_address, stdout_file=stdout_file, stderr_file=stderr_file, autoscaling_config=self._ray_params.autoscaling_con...
Start the monitor.
347,791
def drop_transcripts(self, build=None): if build: LOG.info("Dropping the transcripts collection, build %s", build) self.transcript_collection.delete_many({: build}) else: LOG.info("Dropping the transcripts collection") self.transcript_collection.d...
Delete the transcripts collection
347,792
def get_idd_code(self, ip): rec = self.get_all(ip) return rec and rec.idd_code
Get idd_code
347,793
def register_model(self, model): assert isinstance(model, str) if model not in self.all_models: self.all_models.append(model)
Register ``model`` to this group :param model: model name :return: None
347,794
def query(key, value=None, service=None, profile=None): comps = key.split() key = comps[0] key_vars = {} for pair in comps[1].split(): pair_key, pair_val = pair.split() key_vars[pair_key] = pair_val renderer = __opts__.get(, ) rend = salt.loader.render(__opts__, {}) b...
Get a value from the REST interface
347,795
def network_get(endpoint, relation_id=None): if not has_juju_version(): raise NotImplementedError(juju_version()) if relation_id and not has_juju_version(): raise NotImplementedError cmd = [, endpoint, , ] if relation_id: cmd.append() cmd.append(relation_id) ...
Retrieve the network details for a relation endpoint :param endpoint: string. The name of a relation endpoint :param relation_id: int. The ID of the relation for the current context. :return: dict. The loaded YAML output of the network-get query. :raise: NotImplementedError if request not supported by ...
347,796
def __encryptKeyTransportMessage( self, bare_jids, encryption_callback, bundles = None, expect_problems = None, ignore_trust = False ): yield self.runInactiveDeviceCleanup() if isinstance(bare_jids, string_type): ...
bare_jids: iterable<string> encryption_callback: A function which is called using an instance of cryptography.hazmat.primitives.ciphers.CipherContext, which you can use to encrypt any sort of data. You don't have to return anything. bundles: { [bare_jid: string] => { [device_id: int] => ExtendedPublicBu...
347,797
def save_sensors(self): if not self.need_save: return fname = os.path.realpath(self.persistence_file) exists = os.path.isfile(fname) dirname = os.path.dirname(fname) if (not os.access(dirname, os.W_OK) or exists and not os.access(fname, os.W_O...
Save sensors to file.
347,798
def median_mean(timeseries, segmentlength, noverlap=None, window=None, plan=None): return _lal_spectrum(timeseries, segmentlength, noverlap=noverlap, method=, window=window, plan=plan)
Calculate a PSD of this `TimeSeries` using a median-mean average method The median-mean average method divides overlapping segments into "even" and "odd" segments, and computes the bin-by-bin median of the "even" segments and the "odd" segments, and then takes the bin-by-bin average of these two median...
347,799
def add_from_names_to_locals(self, node): _key_func = lambda node: node.fromlineno def sort_locals(my_list): my_list.sort(key=_key_func) for (name, asname) in node.names: if name == "*": try: imported = node.do_import_module(...
Store imported names to the locals Resort the locals if coming from a delayed node