Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
348,800
def set_user_tags(name, tags, runas=None): * if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() if not isinstance(tags, (list, tuple)): tags = [tags] res = __salt__[]( [RABBITMQCTL, , name] + list(tags), reset_system_locale=Fal...
Add user tags via rabbitmqctl set_user_tags CLI Example: .. code-block:: bash salt '*' rabbitmq.set_user_tags myadmin administrator
348,801
def benchmark_file( filename, compiler, include_dirs, (progress_from, progress_to), iter_count, extra_flags = ): time_sum = 0 mem_sum = 0 for nth_run in xrange(0, iter_count): (time_spent, mem_used) = benchmark_command( .format( compiler, ...
Benchmark one file
348,802
def clearForm(self): self.logui.titleEntry.clear() self.logui.textEntry.clear() while self.logMenuCount > 1: self.removeLogbook(self.logMenus[-1])
Clear all form fields (except author).
348,803
def setFormatMetadata(self, format): assert((self.needMetadataUpdate(CoverImageMetadata.FORMAT)) or (self.format is format)) self.format = format self.check_metadata &= ~CoverImageMetadata.FORMAT
Set format image metadata to what has been reliably identified.
348,804
def reverseCommit(self): if self.markerPos is None: return col = min((self.markerPos[1], self.cursorPos[1])) for line in range(self.markerPos[0], self.cursorPos[0] + 1): self.qteWidget.setSelection(line, col, line, col + len(self.text)) ...
Re-insert the previously deleted line.
348,805
def get_hdu(uri, cutout=None): try: filename = os.path.basename(uri) if os.access(filename, os.F_OK) and cutout is None: logger.debug("File already on disk: {}".format(filename)) hdu_list = fits.open(filename, scale_back=True) hdu_list.verify() ...
Get a at the given uri from VOSpace, possibly doing a cutout. If the cutout is flips the image then we also must flip the datasec keywords. Also, we must offset the datasec to reflect the cutout area being used. @param uri: The URI in VOSpace of the image to HDU to retrieve. @param cutout: A CADC dat...
348,806
def normalize_query(text, encoding=): path = percent_encode_plus(text, encoding=encoding) return uppercase_percent_encoding(path)
Normalize a query string. Percent-encodes unacceptable characters and ensures percent-encoding is uppercase.
348,807
def pack_lob_data(remaining_size, payload, row_header_start_pos, row_lobs): unwritten_lobs = collections.deque() for lob_buffer in row_lobs: rel_lob_pos = payload.tell() - row_header_start_pos + 1 max_data_to_write = min(lob_buffer...
After parameter row has been written, append the lobs and update the corresponding lob headers with lob position and lob size: :param payload: payload object (io.BytesIO instance) :param row_header_start_pos: absolute position of start position of row within payload :param row_lobs: list...
348,808
def get_user_of_group(config, fas, groupname): if not _cache.is_configured: _cache.configure(**config[]) key = cache_key_generator(get_user_of_group, groupname) def creator(): if not fas: return set() return set([u.username for u in fas.group_members(groupname)]) ...
Return the list of users in the specified group. :arg config: a dict containing the fedmsg config :arg fas: a fedora.client.fas2.AccountSystem object instanciated and loged into FAS. :arg groupname: the name of the group for which we want to retrieve the members. :return: a list of FAS ...
348,809
def add_options(cls, manager): kw = {} if flake8.__version__ >= : kw[] = True manager.add_option( "--known-modules", action=, default="", help=( "User defined mapping between a project name and a list of" ...
Register plug-in specific options.
348,810
def controlMsg(self, requestType, request, buffer, value = 0, index = 0, timeout = 100): r return self.dev.ctrl_transfer( requestType, request, wValue = value, wIndex = index, data_or_wLength = buffer, ...
r"""Perform a control request to the default control pipe on a device. Arguments: requestType: specifies the direction of data flow, the type of request, and the recipient. request: specifies the request. buffer: if the transfer is a write transfer, ...
348,811
def imsave(filename, data, photometric=None, planarconfig=None, resolution=None, description=None, software=, byteorder=None, bigtiff=False): assert(photometric in (None, , , )) assert(planarconfig in (None, , )) assert(byteorder in (None, , )) if byteorder is None: b...
Write image data to TIFF file. Image data are written uncompressed in one stripe per plane. Dimensions larger than 2 or 3 (depending on photometric mode and planar configuration) are flattened and saved as separate pages. Parameters ---------- filename : str Name of file to write. ...
348,812
def cyclic_deps(options, **kwargs): call_graph = options[] call_result = _CallResult(cyclic_test(call_graph)) return call_result
Analysis function Check whether there are any cyclic dependencies in a call graph Cyclic dependencies in include graph are prevented at a parsing stage with FileIndex
348,813
def _to_list(var): if isinstance(var, list): return var elif var is None: return [] elif isinstance(var, str) or isinstance(var, dict): return [var] else: try: return list(var) except TypeError: return [var]
Make variable to list. >>> _to_list(None) [] >>> _to_list('whee') ['whee'] >>> _to_list([None]) [None] >>> _to_list((1, 2, 3)) [1, 2, 3] :param var: variable of any type :return: list
348,814
def _sendto(self, data, addr=None, attempts=10): tries = 0 slp_time = lambda: 0.5 / random.randint(10, 30) slp = slp_time() while tries < attempts: try: self.transport.sendto(data, addr=addr) self.log.debug() return ...
On multi-master environments, running on the same machine, transport sending to the destination can be allowed only at once. Since every machine will immediately respond, high chance to get sending fired at the same time, which will result to a PermissionError at socket level. We are att...
348,815
def delete_role(name, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not role_exists(name, region, key, keyid, profile): return True try: conn.delete_role(name) log.info(, name) return True ...
Delete an IAM role. CLI Example: .. code-block:: bash salt myminion boto_iam.delete_role myirole
348,816
def traverse(self, strategy="levelorder", is_leaf_fn=None): if strategy == "preorder": return self._iter_descendants_preorder(is_leaf_fn=is_leaf_fn) elif strategy == "levelorder": return self._iter_descendants_levelorder(is_leaf_fn=is_leaf_fn) elif strategy == "p...
Returns an iterator to traverse tree under this node. Parameters: ----------- strategy: set the way in which tree will be traversed. Possible values are: "preorder" (first parent and then children) 'postorder' (first children and the parent) and ...
348,817
def list_expiration_dates(self, base=): max_fn_len = 0 max_date_len = 0 data = [] for fn in os.listdir(base): fqfn = os.path.join(base, fn) if not os.path.isfile(fqfn): continue if not fn.endswith(): continue ...
Scans through all local .crt files and displays the expiration dates.
348,818
def get_fieldset_index(fieldsets, index_or_name): if isinstance(index_or_name, six.integer_types): return index_or_name for key, value in enumerate(fieldsets): if value[0] == index_or_name: return key raise KeyError("Key not found: .".format(index_or_name))
Return the index of a fieldset in the ``fieldsets`` list. Args: fieldsets (list): The original ``fieldsets`` list. index_or_name (int or str): The value of the reference element, or directly its numeric index. Returns: (int) The index of the fieldset in the ``fieldsets`` list.
348,819
def plot_pot(self, colorbar=True, cb_orientation=, cb_label=, ax=None, show=True, fname=None, **kwargs): if ax is None: fig, axes = self.pot.plot(colorbar=colorbar, cb_orientation=cb_orientation, ...
Plot the gravitational potential. Usage ----- x.plot_pot([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname, **kwargs]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Int...
348,820
def strip_dbm_tx_power(self, idx): idx = Radiotap.align(idx, 1) dbm_tx_power, = struct.unpack_from(, self._rtap, idx) return idx + 1, dbm_tx_power
strip(1 byte) dbm_tx_power :return: int idx :return: int
348,821
def search_dict(data, key): if isinstance(data, dict): for dkey, value in data.items(): if dkey == key: yield value for result in search_dict(value, key): yield result elif isinstance(data, list): for value in data: for res...
Search for a key in a nested dict, or list of nested dicts, and return the values. :param data: dict/list to search :param key: key to find :return: matches for key
348,822
def get_request(self, url): if isinstance(url, string_types): url = urllib2.Request(url, headers={: }) return url
Wraps the URL to retrieve to protects against "creative" interpretation of the RFC: http://bugs.python.org/issue8732
348,823
def is_sub_dict(sub_dict, dictionary): for key in sub_dict.keys(): if key not in dictionary: return False if (type(sub_dict[key]) is not dict) and (sub_dict[key] != dictionary[key]): return False if (type(sub_dict[key]) is dict) and (not is_sub_dict(sub_dict[key]...
Legacy filter for determining if a given dict is present.
348,824
def print_ast(ast, indent=, initlevel=0, newline=, file=sys.stdout): visitor = ASTPrinter(indent=indent, level=initlevel, newline=newline) visitor.visit(ast) visitor.dump(file=file)
Pretty print an ast node. :param ast: the ast to print. :param indent: how far to indent a newline. :param initlevel: starting indent level :param newline: The newline character. :param file: file object to print to To print a short ast you may want to use:: node = ast.par...
348,825
def _check_opts(self): for opt in self.opts.keys(): if opt not in self.__dict__: raise Exception(f"Unsupported option: {opt}")
Checks for unsupported opts, throws error if found NOTE: Must be called _after_ init()
348,826
def set_attr(self, name, value): if not is_valid_name(name): raise ValueError("Invalid name " % name) if name in self.namespace: if name in self.refs: if name in self.self_refs: self.new_ref(name, value) else: ...
Implementation of attribute setting ``space.name = value`` by user script Called from ``Space.__setattr__``
348,827
def _write_flush(self, fd, payload=None): try: if payload: fd.write(ensure_binary(payload)) fd.flush() except (IOError, OSError) as e: if e.errno == errno.EPIPE and self._exit_on_broken_pipe: sys.exit() raise
Write a payload to a given fd (if provided) and flush the fd.
348,828
def is_field_visible(self, field): context = self.context fieldname = field.getName() if fieldname == "Client" and context.portal_type in ("Client", ): return False if fieldname == "Batch" and context.portal_type in ("Batch", ): return...
Check if the field is visible
348,829
def replace(self, child, *nodes): r self.expr.insert( self.expr.remove(child.expr), *nodes)
r"""Replace provided node with node(s). :param TexNode child: Child node to replace :param TexNode nodes: List of nodes to subtitute in >>> from TexSoup import TexSoup >>> soup = TexSoup(r''' ... \begin{itemize} ... \item Hello ... \item Bye ... ...
348,830
def list_keys(hive, key=None, use_32bit_registry=False): *SOFTWARE return __utils__[](hive=hive, key=key, use_32bit_registry=use_32bit_registry)
Enumerates the subkeys in a registry key or hive. Args: hive (str): The name of the hive. Can be one of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU - HKEY_CLASSES_ROOT or HKCR ...
348,831
def get_index(self, name): catalog = self.get_catalog() index = catalog._catalog.getIndex(name) logger.debug("get_index={} of catalog --> {}".format( name, catalog.__name__, index)) return index
get an index by name TODO: Combine indexes of relevant catalogs depending on the portal_type which is searched for.
348,832
def findLorenzDistanceAtTargetKY(Economy,param_name,param_count,center_range,spread,dist_type): intermediateObjective = lambda center : getKYratioDifference(Economy = Economy, param_name = param_name, ...
Finds the sum of squared distances between simulated and target Lorenz points in an economy when a given parameter has heterogeneity according to some distribution. The class of distribution and a measure of spread are given as inputs, but the measure of centrality such that the capital to income ratio mat...
348,833
def keypress(self, viewer, event, data_x, data_y): keyname = event.key chname = self.get_channel_name(viewer) self.logger.debug("key press (%s) in channel %s" % ( keyname, chname)) if keyname == : self.ds.raise_tab() ...
Key press event in a channel window.
348,834
def init_patcher(app, db): app.config.setdefault(, ) app.config.setdefault(, ) if not hasattr(app, ): app.extensions = {} if not in app.extensions: mp = MongoPatcher(db=db, patches_dir=app.config[], collection=app.config[]) ...
Init mongopatcher for the application :param app: :class:`flask.Flask` app to initialize :param db: :class:`pymongo.MongoClient` to work on .. note: This function must be called before using ``patcher_manager``
348,835
def contents(self, f, text): text += self._read(f.abs_path) + "\r\n" return text
Called for each file Must return file content Can be wrapped :type f: static_bundle.files.StaticFileResult :type text: str|unicode :rtype: str|unicode
348,836
def IIR_filter_design(CentralFreq, bandwidth, transitionWidth, SampleFreq, GainStop=40, GainPass=0.01): NyquistFreq = SampleFreq / 2 if (CentralFreq + bandwidth / 2 + transitionWidth > NyquistFreq): raise ValueError( "Need a higher Sample Frequency for this Central Freq, Bandwidth and t...
Function to calculate the coefficients of an IIR filter, IMPORTANT NOTE: make_butterworth_bandpass_b_a and make_butterworth_b_a can produce IIR filters with higher sample rates and are prefereable due to this. Parameters ---------- CentralFreq : float Central frequency of the IIR filte...
348,837
def reclassify_value(one_value, ranges): if (one_value is None or (hasattr(one_value, ) and one_value.isNull())): return None for threshold_id, threshold in list(ranges.items()): value_min = threshold[0] value_max = threshold[1] if valu...
This function will return the classified value according to ranges. The algorithm will return None if the continuous value has not any class. :param one_value: The continuous value to classify. :type one_value: float :param ranges: Classes, following the hazard classification definitions. :type r...
348,838
def _process_incoming_iq(self, stanza_obj): self._logger.debug("incoming iq: %r", stanza_obj) if stanza_obj.type_.is_response: self._logger.debug("iq is response") keys = [(stanza_obj.from_, stanza_obj.id_)] if self._local_jid is not None: ...
Process an incoming IQ stanza `stanza_obj`. Calls the response handler, spawns a request handler coroutine or drops the stanza while logging a warning if no handler can be found.
348,839
def load_from_file_like(cls, flo, format=None): format = self.format if format is None else format load = getattr(cls, "load_%s" % format, None) if load is None: raise ValueError("Unknown format ." % format) return load(flo)
Load the object to a given file like object with the given protocol.
348,840
def filter_kwargs(keys, kwargs): for k in keys: if k in kwargs: yield (k, kwargs[k])
:param keys: A iterable key names to select items :param kwargs: A dict or dict-like object reprensents keyword args >>> list(filter_kwargs(("a", "b"), dict(a=1, b=2, c=3, d=4))) [('a', 1), ('b', 2)]
348,841
def _parse_programs(self, string, parent, filepath=None): moddocs = self.docparser.parse_docs(string) matches = self.RE_PROGRAM.finditer(string) result = [] for rmodule in matches: name = rmodule.group("name").lower() contents =...
Extracts a PROGRAM from the specified fortran code file.
348,842
def add_forbidden_path(self, forbidden): if isinstance(forbidden, six.string_types): forbidden = [forbidden] if self.use_sysroot(): forbidden = [self.join_sysroot(f) for f in forbidden] for forbid in forbidden: self._log_info("adding forbidden path ...
Specify a path, or list of paths, to not copy, even if it's part of a copy_specs[] entry.
348,843
def intialize(self): print % self.port try: self.deviceConnected = False self._connect() if self.deviceConnected: self.UIStatusMsg = self.getVersionNumber() if self.firmwarePrefix not in self.UIStatusMsg: ...
initialize the serial port with baudrate, timeout parameters
348,844
def rouge_2_fscore(logits, labels): predictions = tf.to_int32(tf.argmax(logits, axis=-1)) rouge_2_f_score = tf.py_func(rouge_n, (predictions, labels), tf.float32) return rouge_2_f_score, tf.constant(1.0)
ROUGE-2 F1 score computation between labels and predictions. This is an approximate ROUGE scoring method since we do not glue word pieces or decode the ids and tokenize the output. Args: logits: tensor, model predictions labels: tensor, gold output. Returns: rouge2_fscore: approx rouge-2 f1 score...
348,845
def attrgetrow(self, groupname, key, value=None): if not isinstance(key, str): return self._attrgetrow(groupname, key) rownrs = self.attrfindrows(groupname, key, value) if len(rownrs) == 0: raise IndexError("Image attribute " + key + " in group " + ...
Get the values of all attributes of a row in a group. If the key is an integer, the key is the row number for which the attribute values have to be returned. Otherwise the key has to be a string and it defines the name of an attribute. The attribute values of the row for which the key ...
348,846
def _close(self): if self.connection: with self.wrap_database_errors: self.connection.client.close()
Closes the client connection to the database.
348,847
def package_existent(name): try: response = requests.get(PYPI_URL.format(name)) if response.ok: msg = ( ).format(name) raise Conflict(msg) except (socket.gaierror, Timeout, ConnectionError, HTTPError) as exc: ...
Search package. * :class:`bootstrap_py.exceptions.Conflict` exception occurs when user specified name has already existed. * :class:`bootstrap_py.exceptions.BackendFailure` exception occurs when PyPI service is down. :param str name: package name
348,848
def flatten_binary_scores(scores, labels, ignore=None): scores = scores.view(-1) labels = labels.view(-1) if ignore is None: return scores, labels valid = (labels != ignore) vscores = scores[valid] vlabels = labels[valid] return vscores, vlabels
Flattens predictions in the batch (binary case) Remove labels equal to 'ignore'
348,849
def get_project(self, resource): self.project_service.set_auth(self._token_project) return self.project_service.get(resource)
Get attributes of the data model object named by the given resource. Args: resource (intern.resource.boss.BossResource): resource.name as well as any parents must be identified to succeed. Returns: (intern.resource.boss.BossResource): Returns resource of type ...
348,850
def to_gbq( dataframe, destination_table, project_id=None, chunksize=None, reauth=False, if_exists="fail", auth_local_webserver=False, table_schema=None, location=None, progress_bar=True, credentials=None, verbose=None, private_key=None, ): _test_google_api_...
Write a DataFrame to a Google BigQuery table. The main method a user calls to export pandas DataFrame contents to Google BigQuery table. This method uses the Google Cloud client library to make requests to Google BigQuery, documented `here <https://google-cloud-python.readthedocs.io/en/latest/bigq...
348,851
def open_url(url, retries=0, sleep=0.5): return open_conn(retries=retries, sleep=sleep, **parse_url(url))
Open a mysql connection to a url. Note that if your password has punctuation characters, it might break the parsing of url. url: A string in the form "mysql://username:password@host.domain/database"
348,852
def MSBuild(self): if self.vc_ver < 12.0: return [] elif self.vc_ver < 15.0: base_path = self.si.ProgramFilesx86 arch_subdir = self.pi.current_dir(hidex86=True) else: base_path = self.si.VSInstallDir arch_subdir = pat...
Microsoft Build Engine
348,853
def handle_input(self, input): dirs = { : (-1, 0), : (0, 1), : (0, -1), : (1, 0), : (-1, -1), : (1, -1), : (1, 1), : (-1, 1), } if input in dirs: new_self = (lens.player + dirs[...
Takes a single character string as input and alters the game state according to that input. Mostly, this means moving the player around. Returns a new game state and boolean indicating whether the input had an effect on the state.
348,854
def do_import(self, line): "import [:tablename] filename|list" table, line = self.get_table_params(line) if line[0] == : list = self.get_list(line) else: with open(line) as f: list = self.get_list(f.read()) items = 0 consumed = 0 ...
import [:tablename] filename|list
348,855
def build_and_train(iterations, log_stride, test=False): batch_size = 2 if test else FLAGS.batch_size num_mems = 2 if test else FLAGS.num_mems num_heads = 1 if test else FLAGS.num_mems num_blocks = 1 if test else FLAGS.num_mems head_size = 4 if test else FLAGS.head_size num_objects = 2 if test else F...
Construct the data, model, loss and optimizer then train.
348,856
def helical_turbulent_fd_Prasad(Re, Di, Dc,roughness=0): r fd = friction_factor(Re=Re, eD=roughness/Di) return fd*(1. + 0.18*(Re*(Di/Dc)**2)**0.25)
r'''Calculates Darcy friction factor for a fluid flowing inside a curved pipe such as a helical coil under turbulent conditions, using the method of Prasad [1]_, also shown in [2]_. .. math:: f_{curv} = f_{\text{str,turb}}\left[1 + 0.18\left[Re\left(\frac{D_i} {D_c}\right)^2\right...
348,857
def _set_all_axis_color(self, axis, color): for prop in [, , , , , ]: prop_set = getattr(axis.properties, prop) if color and prop in [, ]: prop_set.fill = ValueRef(value=color) elif color and prop in [, , , ...
Set axis ticks, title, labels to given color
348,858
def _canonicalize_fraction(cls, non_repeating, repeating): if repeating == []: return (non_repeating, repeating) repeat_len = len(repeating) indices = range(len(non_repeating), -1, -repeat_len) end = next( i for i in ...
If the same fractional value can be represented by stripping repeating part from ``non_repeating``, do it. :param non_repeating: non repeating part of fraction :type non_repeating: list of int :param repeating: repeating part of fraction :type repeating: list of int :ret...
348,859
def locateChild(self, ctx, segments): result = self._getAppStoreResource(ctx, segments[0]) if result is not None: child, segments = result, segments[1:] return child, segments if segments[0] == : result = self.child_(ctx) if result is not...
Look up children in the normal manner, but then customize them for the authenticated user if they support the L{ICustomizable} interface. If the user is attempting to access a private URL, redirect them.
348,860
def doc_unwrap(raw_doc): if raw_doc is None: return None docstring = consecutive_newlines = 0 for c in raw_doc.strip(): if c == : consecutive_newlines += 1 if consecutive_newlines > 1: docstring += c else: if consecut...
Applies two transformations to raw_doc: 1. N consecutive newlines are converted into N-1 newlines. 2. A lone newline is converted to a space, which basically unwraps text. Returns a new string, or None if the input was None.
348,861
def ok(self, event=None): if not self.validate(): self.initial_focus.focus_set() return self.entry_to_clear.delete(0, ) self.update_idletasks() try: self.apply() finally: ...
This method is identical to tkinter.simpledialog.Dialog.ok(), but with 'self.withdraw()' commented out.
348,862
def getParamsByName(elem, name): name = StripParamName(name) return elem.getElements(lambda e: (e.tagName == ligolw.Param.tagName) and (e.Name == name))
Return a list of params with name name under elem.
348,863
async def generate_proof(self, selected_creds: dict, self_attested_attrs: dict): if not hasattr(DisclosedProof.generate_proof, "cb"): self.logger.debug("vcx_disclosed_proof_generate_proof: Creating callback") DisclosedProof.generate_proof.cb = create_cb(CFUNCTYPE(None, c_uint32,...
Generates the proof Example: msg_id = '1' phone_number = '8019119191' connection = await Connection.create(source_id) await connection.connect(phone_number) disclosed_proof = await DisclosedProof.create_with_msgid(source_id, connection, msg_id) await disclosed_pro...
348,864
def shuffle(self): args = list(self) random.shuffle(args) self.clear() super(DogeDeque, self).__init__(args)
Shuffle the deque Deques themselves do not support this, so this will make all items into a list, shuffle that list, clear the deque, and then re-init the deque.
348,865
def update_ids(connection, xmldoc, verbose = False): table_elems = xmldoc.getElementsByTagName(ligolw.Table.tagName) for i, tbl in enumerate(table_elems): if verbose: print >>sys.stderr, "updating IDs: %d%%\r" % (100.0 * i / len(table_elems)), tbl.applyKeyMapping() if verbose: print >>sys....
For internal use only.
348,866
def truncated_pareto_expval(alpha, m, b): if alpha <= 1: return inf part1 = (m ** alpha) / (1. - (m / b) ** alpha) part2 = 1. * alpha / (alpha - 1) part3 = (1. / (m ** (alpha - 1)) - 1. / (b ** (alpha - 1.))) return part1 * part2 * part3
Expected value of truncated Pareto distribution.
348,867
def rulesdir(self, acc=None): rootdir = self.rootdir() rulesdir = self.get(, acc=acc, default=[]) return os.path.join(rootdir, rulesdir) \ if rootdir and rulesdir else None
Determine the rulesdir for the given account. Return None if not specified.
348,868
def Chen_1979(Re, eD): r A4 = eD**1.1098/2.8257 + (7.149/Re)**0.8981 ff = (-4*log10(eD/3.7065 - 5.0452/Re*log10(A4)))**-2 return 4*ff
r'''Calculates Darcy friction factor using the method in Chen (1979) [2]_ as shown in [1]_. .. math:: \frac{1}{\sqrt{f_f}} = -4\log\left[\frac{\epsilon}{3.7065D} -\frac{5.0452}{Re}\log A_4\right] .. math:: A_4 = \frac{(\epsilon/D)^{1.1098}}{2.8257} + \left(\frac{7.149}{Re}\...
348,869
def checksum_status(self, area_uuid, filename): url_safe_filename = urlparse.quote(filename) path = "/area/{uuid}/{filename}/checksum".format(uuid=area_uuid, filename=url_safe_filename) response = self._make_request(, path) return response.json()
Retrieve checksum status and values for a file :param str area_uuid: A RFC4122-compliant ID for the upload area :param str filename: The name of the file within the Upload Area :return: a dict with checksum information :rtype: dict :raises UploadApiException: if information coul...
348,870
def map_by(fn: Callable[[T1], T2]) -> Callable[[ActualIterable[T1]], Iterable[T2]]: return lambda collection: builtins.map(fn, collection)
when pycharm supports type hinting for any implementation of currying, map_with and map_on would be deprecated. >>> from Redy.Collections import Traversal, Flow >>> def double(x: int) -> int: return x * 2 >>> lst: Iterable[int] = [1, 2, 3] >>> x = Flow(lst)[Traversal.map_by(double)][Traversal.sum_fr...
348,871
def _split(self, string): for i in range(len(string) - self.N + 1): yield string[i:i + self.N]
Iterates over the ngrams of a string (no padding). >>> from ngram import NGram >>> n = NGram() >>> list(n._split("hamegg")) ['ham', 'ame', 'meg', 'egg']
348,872
def _serialiseEnv(self): with self._jobStore.writeSharedFileStream("environment.pickle") as fileHandle: pickle.dump(dict(os.environ), fileHandle, pickle.HIGHEST_PROTOCOL) logger.debug("Written the environment for the jobs to the environment file")
Puts the environment in a globally accessible pickle file.
348,873
def copy(self, o=None): if o is None: o = self.__class__(self.project) o.scripts = [s.copy() for s in self.scripts] o.variables = dict((n, v.copy()) for (n, v) in self.variables.items()) o.lists = dict((n, l.copy()) for (n, l) in self.lists.items()) o.costumes = [c.copy(...
Return a new instance, deep-copying all the attributes.
348,874
def _read_checkplot_picklefile(checkplotpickle): t compatible with Python 3. See here: http://stackoverflow.com/q/11305790 The workaround is noted in this answer: http://stackoverflow.com/a/41366785 Parameters ---------- checkplotpickle : str The path to a checkplot pickle file....
This reads a checkplot gzipped pickle file back into a dict. NOTE: the try-except is for Python 2 pickles that have numpy arrays in them. Apparently, these aren't compatible with Python 3. See here: http://stackoverflow.com/q/11305790 The workaround is noted in this answer: http://stackoverflow....
348,875
def usage(self): api_version = self._get_api_version() if api_version == : from .v2015_06_15.operations import UsageOperations as OperationClass elif api_version == : from .v2016_01_01.operations import UsageOperations as OperationClass elif api_version =...
Instance depends on the API version: * 2015-06-15: :class:`UsageOperations<azure.mgmt.storage.v2015_06_15.operations.UsageOperations>` * 2016-01-01: :class:`UsageOperations<azure.mgmt.storage.v2016_01_01.operations.UsageOperations>` * 2016-12-01: :class:`UsageOperations<azure.mgmt.stor...
348,876
def inject_basic_program(self, ascii_listing): program_start = self.cpu.memory.read_word( self.machine_api.PROGRAM_START_ADDR ) tokens = self.machine_api.ascii_listing2program_dump(ascii_listing) self.cpu.memory.load(program_start, tokens) log.critical("BASIC...
save the given ASCII BASIC program listing into the emulator RAM.
348,877
def create(self, name, backend_router_id, flavor, instances, test=False): args = (self.capacity_package, 0, [flavor]) extras = {"backendRouterId": backend_router_id, "name": name} kwargs = { : extras, : instances, : , : True ...
Orders a Virtual_ReservedCapacityGroup :param string name: Name for the new reserved capacity :param int backend_router_id: This selects the pod. See create_options for a list :param string flavor: Capacity KeyName, see create_options for a list :param int instances: Number of guest thi...
348,878
def logoNotebook(symbol, token=, version=): _raiseIfNotStr(symbol) url = logo(symbol, token, version)[] return ImageI(url=url)
This is a helper function, but the google APIs url is standardized. https://iexcloud.io/docs/api/#logo 8am UTC daily Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: image: result
348,879
def network_del_notif(self, tenant_id, tenant_name, net_id): if not self.fw_init: return self.network_delete_notif(tenant_id, tenant_name, net_id)
Network delete notification.
348,880
def remove_descendants_of(self, node): if isinstance(node, int): warnings.warn( , DeprecationWarning, 2) node = self._id_to_node[node] desc = nx.descendants(self._multi_graph, node) for desc_node in desc: ...
Remove all of the descendant operation nodes of node.
348,881
def create(data, cipher, key, flags=0): bio = Membio(data) ptr = libcrypto.CMS_EncryptedData_encrypt(bio.bio, cipher.cipher, key, len(key), flags) if ptr is None: raise CMSError("encrypt data") return EncryptedData(pt...
Creates an EncryptedData message. @param data data to encrypt @param cipher cipher.CipherType object represening required cipher type @param key - byte array used as simmetic key @param flags - OR-ed combination of Flags constant
348,882
def list_bzip2 (archive, compression, cmd, verbosity, interactive): return stripext(cmd, archive, verbosity)
List a BZIP2 archive.
348,883
def get_list_element_from_database(database=): _file_path = os.path.abspath(os.path.dirname(__file__)) _ref_data_folder = os.path.join(_file_path, ) _database_folder = os.path.join(_ref_data_folder, database) if not os.path.exists(_ref_data_folder): os.makedirs(_ref_data_folder) pr...
return a string array of all the element from the database Parameters: ========== database: string. Name of database Raises: ====== ValueError if database can not be found
348,884
def soap(func=None, name=None, returns=None, args=None, doc=None, target=): global __soap_functions__ returns = _fix_soap_kwargs(returns) args = _fix_soap_kwargs(args) if isinstance(func, str) and not name: return partial(soap, name=func, returns=returns, args=args, doc=doc, targe...
soap supports multiple SOAP function collections, it'll save functions to target dict, and you can give other target, but it should be keep up with SoapView.target definition.
348,885
def from_dict(cls, serialized): if serialized is None: return None macaroon = serialized.get() if macaroon is not None: macaroon = bakery.Macaroon.from_dict(macaroon) path = serialized.get() cookie_name_suffix = serialized.get() visit_url ...
Create a new ErrorInfo object from a JSON deserialized dictionary @param serialized The JSON object {dict} @return ErrorInfo object
348,886
def render_toctrees(kb_app: kb, sphinx_app: Sphinx, doctree: doctree, fromdocname: str): settings: KaybeeSettings = sphinx_app.config.kaybee_settings if not settings.articles.use_toctree: return builder: StandaloneHTMLBuilder = sphinx_app.builder env: Bu...
Look in doctrees for toctree and replace with custom render
348,887
def errorstack(self, tokens, i, full=False): print("\n-- Stacks of completed symbols:") states = [s for s in self.edges.values() if s] state_stack = set() for state in states: for rule, dot in self.states[state].items: ...
Show the stacks of completed symbols. We get this by inspecting the current transitions possible and from that extracting the set of states we are in, and from there we look at the set of symbols before the "dot". If full is True, we show the entire rule with the dot placement. ...
348,888
def traverse_postorder(self, leaves=True, internal=True): for node in self.root.traverse_postorder(leaves=leaves, internal=internal): yield node
Perform a postorder traversal of the ``Node`` objects in this ``Tree`` Args: ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
348,889
def injectable_definition(inj_name): inj_type = orca.injectable_type(inj_name) if inj_type == : return jsonify(type=) else: filename, lineno, source = \ orca.get_injectable_func_source_data(inj_name) html = highlight(source, PythonLexer(), HtmlFormatter()) r...
Get the source of an injectable function. If an injectable is a registered Python variable and not a function then all that is returned is {'type': 'variable'}. If the column is a registered function then the JSON returned has keys "type", "filename", "lineno", "text", and "html". "text" is the raw ...
348,890
def flip_ctrlpts_u(ctrlpts, size_u, size_v): new_ctrlpts = [] for i in range(0, size_u): for j in range(0, size_v): temp = [float(c) for c in ctrlpts[i + (j * size_u)]] new_ctrlpts.append(temp) return new_ctrlpts
Flips a list of 1-dimensional control points from u-row order to v-row order. **u-row order**: each row corresponds to a list of u values **v-row order**: each row corresponds to a list of v values :param ctrlpts: control points in u-row order :type ctrlpts: list, tuple :param size_u: size in u-d...
348,891
def extract_from_stack(stack, template, length, pre_pick, pre_pad, Z_include=False, pre_processed=True, samp_rate=None, lowcut=None, highcut=None, filt_order=3): new_template = stack.copy() mintime = min([tr.stats.starttime for tr in template]) ...
Extract a multiplexed template from a stack of detections. Function to extract a new template from a stack of previous detections. Requires the stack, the template used to make the detections for the \ stack, and we need to know if the stack has been pre-processed. :type stack: obspy.core.stream.Strea...
348,892
def stream_name(stream_id): name = _STREAM_NAME_MAP.get(stream_id) if name is None: name = str(DataStream.FromEncoded(stream_id)) return "{} (0x{:04X})".format(name, stream_id)
Map a stream id to a human readable name. The mapping process is as follows: If the stream id is globally known, its global name is used as <name> otherwise a string representation of the stream is used as <name>. In both cases the hex representation of the stream id is appended as a number: ...
348,893
def min_pos(self): if self.__len__() == 0: return ArgumentError() if self.contains(0): return None positive = [interval for interval in self.intervals if interval.left > 0] if len(positive) == 0: return None return ...
Returns minimal positive value or None.
348,894
def save_method_args(method): args_and_kwargs = collections.namedtuple(, ) @functools.wraps(method) def wrapper(self, *args, **kwargs): attr_name = + method.__name__ attr = args_and_kwargs(args, kwargs) setattr(self, attr_name, attr) return method(self, *args, **kwargs) return wrapper
Wrap a method such that when it is called, the args and kwargs are saved on the method. >>> class MyClass: ... @save_method_args ... def method(self, a, b): ... print(a, b) >>> my_ob = MyClass() >>> my_ob.method(1, 2) 1 2 >>> my_ob._saved_method.args (1, 2) >>> my_ob._saved_method.kwargs {}...
348,895
def cp_to_noexistent_destination(args, dest_path, dx_dest, dest_proj): if len(args.sources) != 1: {"project": dest_proj, "name": dest_name}) return except: err_exit()
Copy the source to a destination that does not currently exist. This involves creating the target file/folder.
348,896
def __construct_object(self, obj, exclude_list=[]): new_obj = {} for key, value in obj.items(): if str(key).startswith() or \ key is or key in exclude_list: continue new_obj[self.camel_case(key)] = self.__iterate_value(value) ...
Loop dict/class object and parse values
348,897
def editflags(fd, add_flags=0, remove_flags=0): if add_flags & remove_flags != 0: raise ValueError( t overlaps be explicit here. flags_ptr = ffi.new() flags_buf = ffi.buffer(flags_ptr) fcntl.ioctl(fd, lib.FS_IOC_GETFLAGS, flags_buf) prev_flags = flags_ptr[0] flags_ptr[0...
Sets and unsets per-file filesystem flags.
348,898
def home_page(self, tld_type: Optional[TLDType] = None) -> str: resource = self.random.choice(USERNAMES) domain = self.top_level_domain( tld_type=tld_type, ) return .format( resource, domain)
Generate a random home page. :param tld_type: TLD type. :return: Random home page. :Example: http://www.fontir.info
348,899
def write_memory_dump(): gc.collect() if gc.garbage: log.warn(LOG_CHECK, "Unreachabe objects: %s", pprint.pformat(gc.garbage)) from meliae import scanner fo, filename = get_temp_file(mode=, suffix=, prefix=) try: scanner.dump_all_objects(fo) finally: fo.close() ...
Dump memory to a temporary filename with the meliae package. @return: JSON filename where memory dump has been written to @rtype: string