text
stringlengths
78
104k
score
float64
0
0.18
def Davis_David(m, x, D, rhol, rhog, Cpl, kl, mul): r'''Calculates the two-phase non-boiling heat transfer coefficient of a liquid and gas flowing inside a tube of any inclination, as in [1]_ and reviewed in [2]_. .. math:: \frac{h_{TP} D}{k_l} = 0.060\left(\frac{\rho_L}{\rho_G}\right)^{0.28}...
0.005484
def init(self, value): ''' hash passwords given in the constructor ''' value = self.value_or_default(value) if value is None: return None if is_hashed(value): return value return make_password(value)
0.011811
def register_new(self, entity_class, entity): """ Registers the given entity for the given class as NEW. :raises ValueError: If the given entity already holds state that was created by another Unit Of Work. """ EntityState.manage(entity, self) EntityState.get_s...
0.004819
def trim_tree_after(element, include_element=True): """ Removes the document tree following the given element. If include_element is True, the given element is kept in the tree, otherwise it is removed. """ el = element for parent_el in element.iterancestors(): el.tail = None if ...
0.001876
def get_current_bios_settings(self, only_allowed_settings=True): """Get current BIOS settings. :param: only_allowed_settings: True when only allowed BIOS settings are to be returned. If False, All the BIOS settings supported by iLO are returned. :return: a dictio...
0.001554
def open(self): """ Open system file """ self.device = open(self.devfile, "wb") if self.device is None: print("Could not open the specified file {0}".format(self.devfile))
0.009615
def train(input_dir, batch_size, max_steps, output_dir, checkpoint, cloud_train_config): """Train model in the cloud with CloudML trainer service.""" import google.datalab.ml as ml if checkpoint is None: checkpoint = _util._DEFAULT_CHECKPOINT_GSURL staging_package_url = _util.repackage_to_staging...
0.007597
def season_date_range(start, stop, freq='D'): """ Return array of datetime objects using input frequency from start to stop Supports single datetime object or list, tuple, ndarray of start and stop dates. freq codes correspond to pandas date_range codes, D daily, M monthly, S secondly """...
0.006024
def shift(self, periods=1, freq=None, axis=0, fill_value=None): """ Shift each group by periods observations. Parameters ---------- periods : integer, default 1 number of periods to shift freq : frequency string axis : axis to shift, default 0 ...
0.002165
def get_channelstate_filter( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, filter_fn: Callable, ) -> List[NettingChannelState]: """ Return the state of channels that match the condition in `filter_fn` """ token_network = get_token_net...
0.002899
def _fetch_seq_ncbi(ac, start_i=None, end_i=None): """Fetch sequences from NCBI using the eutils interface. An interbase interval may be optionally provided with start_i and end_i. NCBI eutils will return just the requested subsequence, which might greatly reduce payload sizes (especially with chro...
0.002222
def randbelow(num: int) -> int: """Return a random int in the range [0,num). Raises ValueError if num <= 0, and TypeError if it's not an integer. >>> randbelow(16) #doctest:+SKIP 13 """ if not isinstance(num, int): raise TypeError('number must be an integer') if num <= 0: ...
0.001429
def _filter_repeating_items(download_list): """ Because of data_filter some requests in download list might be the same. In order not to download them again this method will reduce the list of requests. It will also return a mapping list which can be used to reconstruct the previous list of down...
0.004669
def parseErrorAndResponse(self, data): """Parse returned XML for errors, then convert into appropriate Python objects.""" xml = fromstring(data) error = xml.find('.//ERROR') if error is None: self.deferred.callback(self.parseResponse(xml)) return ...
0.00404
def _unescape(self, value): ''' Recursively unescape values. Though slower, this doesn't require the user to know anything about the escaping when writing their own custom fetch functions. ''' if isinstance(value, (str,unicode)): return value.replace(self._escape_character, '.') elif isins...
0.025
def quasiparticle_weight(self): """Calculates quasiparticle weight""" return np.array([self.expected(op)**2 for op in self.oper['O']])
0.013333
def col(self): """Gives direct access to the columns only (useful for tab completion). Convenient when working with ipython in combination with small DataFrames, since this gives tab-completion. Columns can be accesed by there names, which are attributes. The attribues are currently expression...
0.004896
def lhs(n, samples=None, criterion=None, iterations=None): """ Generate a latin-hypercube design Parameters ---------- n : int The number of factors to generate samples for Optional -------- samples : int The number of samples to generate for each fa...
0.007435
def get_execution_role(sagemaker_session=None): """Return the role ARN whose credentials are used to call the API. Throws an exception if Args: sagemaker_session(Session): Current sagemaker session Returns: (str): The role ARN """ if not sagemaker_session: sagemaker_sessi...
0.003378
def get_console_logger(): """ just for kkconst demos """ global __console_logger if __console_logger: return __console_logger logger = logging.getLogger("kkconst") logger.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = loggi...
0.00404
def fit_transform(self, X, y=None): """Encode categorical columns into label encoded columns Args: X (pandas.DataFrame): categorical columns to encode Returns: X (pandas.DataFrame): label encoded columns """ self.label_encoders = [None] * X.shape[1] ...
0.004747
def autogroups_states_changed(sender, instance, action, reverse, model, pk_set, *args, **kwargs): """ Trigger group membership update when a state is added or removed from an autogroup config. """ if action.startswith('post_'): for pk in pk_set: try: state = State...
0.003745
def _maybe_extract(compressed_filename, directory, extension=None): """ Extract a compressed file to ``directory``. Args: compressed_filename (str): Compressed file. directory (str): Extract to directory. extension (str, optional): Extension of the file; Otherwise, attempts to extract e...
0.0022
def lag(col, offset=1, default=None): """ Window function: returns the value that is `offset` rows before the current row, and `defaultValue` if there is less than `offset` rows before the current row. For example, an `offset` of one will return the previous row at any given point in the window partitio...
0.006359
def _get_filter(self, features): """ Gets the filter for the features in the object :param features: The features of the syslog file """ # This chops the features up into smaller lists so the api can handle them for ip_batch in (features['ips'][pos:pos + self.ip_query_b...
0.006309
def was_active(reference_date_value, asset): """ Whether or not `asset` was active at the time corresponding to `reference_date_value`. Parameters ---------- reference_date_value : int Date, represented as nanoseconds since EPOCH, for which we want to know if `asset` was alive. ...
0.001422
def compile_template(template, renderers, default, blacklist, whitelist, saltenv='base', sls='', input_data='', **kwargs): ''' Take the path to ...
0.000974
def to_raw_text_markupless(text, keep_whitespace=False, normalize_ascii=True): """ A generator to convert raw text segments, without xml to a list of words without any markup. Additionally dates are replaced by `7777` for normalization. Arguments --------- text: str, input text to token...
0.001236
def get_authenticated_connection(self, user, passwd, db='admin', ssl=True): """Get an authenticated connection to this instance. :param str user: The username to use for authentication. :param str passwd: The password to use for authentication. :param str db: The name of the database to...
0.005336
def labels(self) -> Set[TransitionLabel]: """Return the set of transition labels to examine for this queue state. This is the union of the transition label sets for both states. However, if one of the states is fixed, it is excluded from this union and a wildcard transition is included ...
0.003996
def clearForm(self): """Clear all form fields (except author).""" self.logui.titleEntry.clear() self.logui.textEntry.clear() # Remove all log selection menus except the first while self.logMenuCount > 1: self.removeLogbook(self.logMenus[-1])
0.009901
def adjust_weights(self,obs_dict=None, obsgrp_dict=None): """reset the weights of observation groups to contribute a specified amount to the composite objective function Parameters ---------- obs_dict : dict dictionary of obs name,new co...
0.006694
def events(self, institute, case=None, variant_id=None, level=None, comments=False, panel=None): """Fetch events from the database. Args: institute (dict): A institute case (dict): A case variant_id (str, optional): global variant id leve...
0.007897
def _deref(self) -> List["InstanceNode"]: """XPath: return the list of nodes that the receiver refers to.""" return ([] if self.is_internal() else self.schema_node.type._deref(self))
0.009346
def serialize_on_parent( self, parent, # type: ET.Element value, # type: Any state # type: _ProcessorState ): # type: (...) -> None """Serialize the value and add it to the parent element.""" # Note that falsey values are not treated as miss...
0.008889
def class_name_to_resource_name(class_name: str) -> str: """Converts a camel case class name to a resource name with spaces. >>> class_name_to_resource_name('FooBarObject') 'Foo Bar Object' :param class_name: The name to convert. :returns: The resource name. """ s = re.sub('(.)([A-Z][a-z]+...
0.002519
def cast_scalar(method): """ Cast scalars to constant interpolating objects """ @wraps(method) def new_method(self, other): if np.isscalar(other): other = type(self)([other],self.domain()) return method(self, other) return new_method
0.007018
def get_interims_data(self): """Returns a dictionary with the interims data """ form = self.request.form if 'item_data' not in form: return {} item_data = {} if type(form['item_data']) == list: for i_d in form['item_data']: for i, ...
0.004338
def get_domains(self): """ Returns domains affected by operation. @rtype: list """ if self.domains is None: self.domains = list( set(self.source.get_domains() + self.target.get_domains())) return self.domains
0.007042
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url return _d...
0.006192
def fit_polynomial(pixel_data, mask, clip=True): '''Return an "image" which is a polynomial fit to the pixel data Fit the image to the polynomial Ax**2+By**2+Cxy+Dx+Ey+F pixel_data - a two-dimensional numpy array to be fitted mask - a mask of pixels whose intensities should be considered ...
0.017949
def from_credentials_db(client_secrets, storage, api_version="v3", readonly=False, http_client=None, ga_hook=None): """Create a client for a web or installed application. Create a client with a credentials stored in stagecraft db. Args: client_secrets: dict, client secrets ...
0.001098
def find_N_peaks(array, N=4, max_iterations=100, rec_max_iterations=3, recursion=1): """ This will run the find_peaks algorythm, adjusting the baseline until exactly N peaks are found. """ if recursion<0: return None # get an initial guess as to the baseline ymin = min(array) ymax = max(ar...
0.011251
def set_dtreat_interp_indt(self, indt=None): """ Set the indices of the times for which to interpolate data The index can be provided as: - A 1d np.ndarray of boolean or int indices => interpolate data at these times for all channels - A dict with: ...
0.007699
def compute_venn2_colors(set_colors): ''' Given two base colors, computes combinations of colors corresponding to all regions of the venn diagram. returns a list of 3 elements, providing colors for regions (10, 01, 11). >>> compute_venn2_colors(('r', 'g')) (array([ 1., 0., 0.]), array([ 0. , 0.5...
0.007326
def get_huisnummer_by_id(self, id): ''' Retrieve a `huisnummer` by the Id. :param integer id: the Id of the `huisnummer` :rtype: :class:`Huisnummer` ''' def creator(): res = crab_gateway_request( self.client, 'GetHuisnummerWithStatusByHuisnumm...
0.004344
def wrapped_target(target, q_stdout, q_stderr, q_error, robust, name, *args, **kwargs): # pragma: no cover """ Wraps a target with queues replacing stdout and stderr """ import sys sys.stdout = IOQueue(q_stdout) sys.stderr = IOQueue(q_stderr) try: target(*args, **kwargs) except...
0.00692
def show_xticklabels(self, row, column): """Show the x-axis tick labels for a subplot. :param row,column: specify the subplot. """ subplot = self.get_subplot_at(row, column) subplot.show_xticklabels()
0.008264
def _check_last_arg_pattern(self, current_arg_pattern, last_arg_pattern): """Given a "current" arg pattern (that was used to match the last actual argument of an expression), and another ("last") argument pattern, raise a ValueError, unless the "last" argument pattern is a "zero or more"...
0.001712
def delete_index_files(self): """ Delete all data aside from source GTF and FASTA files """ self.clear_cache() db_path = self.db.local_db_path() if exists(db_path): remove(db_path)
0.008333
def retrieve_authorization_code(self, redirect_func=None): """ retrieve authorization code to get access token """ request_param = { "client_id": self.client_id, "redirect_uri": self.redirect_uri, } if self.scope: request_param['s...
0.004592
def get_times_covered_by_files(self): """ Find the coalesced intersection of the segments of all files in the list. """ times = segments.segmentlist([]) for entry in self: times.extend(entry.segment_list) times.coalesce() return times
0.006452
def _buildNewKeyname(self,key,prepend): """ Builds a new keyword based on original keyword name and a prepend string. """ if len(prepend+key) <= 8: _new_key = prepend+key else: _new_key = str(prepend+key)[:8] return _new_key
0.021583
def copy_func(f, name=None, sinceversion=None, doc=None): """ Returns a function with same code, globals, defaults, closure, and name (or provide a new name). """ # See # http://stackoverflow.com/questions/6527633/how-can-i-make-a-deepcopy-of-a-function-in-python fn = types.FunctionType(f.__...
0.003044
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ result = None teeoff = True cond = self.storagehandler.expand(str(self.resolve_option("condition"))) if len(cond) > 0...
0.0053
def get_default_config(self): """ Return the default config for the handler """ config = super(LibratoHandler, self).get_default_config() config.update({ 'user': '', 'apikey': '', 'apply_metric_prefix': False, 'queue_max_size': 300...
0.004619
def evaluate_min_coverage(coverage_opt, assembly_coverage, assembly_size): """ Evaluates the minimum coverage threshold from the value provided in the coverage_opt. Parameters ---------- coverage_opt : str or int or float If set to "auto" it will try to automatically determine the coverage ...
0.000631
def outbound_sizes(cls, original_width, original_height, target_width, target_height): """ Calculate new image sizes for outbound mode :param original_width: int :param original_height: int :param target_width: int :param target_height: int :return: tuple(int, int...
0.003417
def get_index_type(self, loop_nest=None): """ Return index type used in loop nest. If index type between loops differ, an exception is raised. """ if loop_nest is None: loop_nest = self.get_kernel_loop_nest() if type(loop_nest) is c_ast.For: loop_...
0.003222
def to_cryptography_key(self): """ Export as a ``cryptography`` key. :rtype: One of ``cryptography``'s `key interfaces`_. .. _key interfaces: https://cryptography.io/en/latest/hazmat/\ primitives/asymmetric/rsa/#key-interfaces .. versionadded:: 16.1.0 """ ...
0.003831
def last_midnight(): """ return a datetime of last mid-night """ now = datetime.now() return datetime(now.year, now.month, now.day)
0.006623
def haarpsi_similarity_map(img1, img2, axis, c, a): r"""Local similarity map for directional features along an axis. Parameters ---------- img1, img2 : array-like The images to compare. They must have equal shape. axis : {0, 1} Direction in which to look for edge similarities. c...
0.000202
def preload_defs(self): """Preload all top-level definitions.""" for d in (self.module.search("grouping") + self.module.search("typedef")): uname, dic = self.unique_def_name(d) self.install_def(uname, d, dic)
0.007519
def get_process_properties(self, pid=None, name=None): ''' get_process_properties(self, pid=None, name=None) Get process properties (both input and output properties) :Parameters: * *pid* (`string`) -- Identifier of an existing process * *name* (`string`) -- optional - ...
0.006906
def visgrep(scr: str, pat: str, tolerance: int = 0) -> int: """ visgrep(scr: str, pat: str, tolerance: int = 0) -> int Visual grep of scr for pattern pat. Requires xautomation (http://hoopajoo.net/projects/xautomation.html). visgrep("screen.png", "pat.png") Exceptions raised: ValueError, Pattern...
0.003881
def path(self): "Return a list of nodes forming the path from the root to this node." node, path_back = self, [] while node: path_back.append(node) node = node.parent return list(reversed(path_back))
0.007843
def to_header(self): """Convert the stored values into a WWW-Authenticate header.""" d = dict(self) auth_type = d.pop("__auth_type__", None) or "basic" return "%s %s" % ( auth_type.title(), ", ".join( [ "%s=%s" ...
0.003215
def get_qualification_score(self, qualification_type_id, worker_id): """TODO: Document.""" params = {'QualificationTypeId' : qualification_type_id, 'SubjectId' : worker_id} return self._process_request('GetQualificationScore', params, [('Qualification', Qual...
0.018018
def load_data(filename, format_file='cloudupdrs'): """ This is a general load data method where the format of data to load can be passed as a parameter, :param str filename: The path to load data from :param str format_file: format of the file. Default is CloudUPDRS ('cloudu...
0.010127
def ProcessClients(self, responses): """Does the work.""" del responses end = rdfvalue.RDFDatetime.Now() - db.CLIENT_STATS_RETENTION client_urns = export_utils.GetAllClients(token=self.token) for batch in collection.Batch(client_urns, 10000): with data_store.DB.GetMutationPool() as mutation_...
0.008484
def update_hidden_property(self, name, old_value, new_value): # type: (str, Any, Any) -> None """ Handles an hidden property changed event :param name: The changed property name :param old_value: The previous property value :param new_value: The new property value ...
0.006263
def comment_vote(self, comment_id, score): """Lets you vote for a comment (Requires login). Parameters: comment_id (int): score (str): Can be: up, down. """ params = {'score': score} return self._get('comments/{0}/votes.json'.format(comment_id), params, ...
0.00542
def colors( self, name ): """ Returns all the colors in order for the inputed color name. :return [<QColor>, ..] """ output = [] colors = self._colors.get(name, {}) for colorType in self._colorGroups: output.append(colors.get(colorType, QC...
0.014286
def is_kde_desktop(): """Detect if we are running in a KDE desktop""" if sys.platform.startswith('linux'): xdg_desktop = os.environ.get('XDG_CURRENT_DESKTOP', '') if xdg_desktop: if 'KDE' in xdg_desktop: return True else: return False ...
0.002604
def statistics(self): """ Access the statistics :returns: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList :rtype: twilio.rest.autopilot.v1.assistant.task.task_statistics.TaskStatisticsList """ if self._statistics is None: self._stat...
0.007463
def reassign_port(self, port): """ Reassign this HBA to a new underlying :term:`FCP port`. This method performs the HMC operation "Reassign Storage Adapter Port". Authorization requirements: * Object-access permission to the Partition containing this HBA. * Object-acce...
0.001887
def list(cls, vrf=None): """ List VRFs. Maps to the function :py:func:`nipap.backend.Nipap.list_vrf` in the backend. Please see the documentation for the backend function for information regarding input arguments and return values. """ if vrf is None: ...
0.002639
def remove_listener(self, func, name=None): """Removes a listener from the pool of listeners. Parameters ----------- func The function that was used as a listener to remove. name: :class:`str` The name of the event we want to remove. Defaults to ...
0.003509
def fit_transform(self, raw_documents, y=None): """ Learn the vocabulary dictionary and return term-document matrix. This is equivalent to fit followed by transform, but more efficiently implemented. Parameters ---------- raw_documents : iterable An iterable ...
0.002481
def assert_dimensionless(value): """ Tests for dimensionlessness of input. If input is dimensionless but expressed as a Quantity, it returns the bare value. If it not, it raised an error. """ if isinstance(value, Quantity): value = value.simplified if value.dimensionality == Di...
0.002075
def flush(self): """Flush message queue if there's an active connection running""" self._pending_flush = False if self.handler is None or not self.handler.active or not self.send_queue: return self.handler.send_pack('a[%s]' % self.send_queue) self.send_queue = ''
0.009464
def shutdown(self): """ Signals worker to shutdown (via sentinel) then cleanly joins the thread """ self.shutdownLocal() newJobsQueue = self.newJobsQueue self.newJobsQueue = None newJobsQueue.put(None) self.worker.join()
0.007018
def prepare_page_attributes(self, page): """ Banana banana """ self._current_page = page page.output_attrs['html']['scripts'] = OrderedSet() page.output_attrs['html']['stylesheets'] = OrderedSet() page.output_attrs['html']['extra_html'] = [] page.output_at...
0.003559
def get_dataset(self, key, info): """Get the dataset designated by *key*.""" res = super(HRITJMAFileHandler, self).get_dataset(key, info) # Filenames of segmented data is identical for MTSAT-1R, MTSAT-2 # and Himawari-8/9. Make sure we have the correct reader for the data # at h...
0.004624
def AddUser(self, uid, username, active): '''Convenience method to add a user. Return the object path of the new user. ''' user_path = '/org/freedesktop/login1/user/%i' % uid if user_path in mockobject.objects: raise dbus.exceptions.DBusException('User %i already exists' % uid, ...
0.000687
def match(self, data, threshold=0.5, generator=False): # pragma: no cover """Identifies records that all refer to the same entity, returns tuples containing a set of record ids and a confidence score as a float between 0 and 1. The record_ids within each set should refer to the...
0.001471
def get_install_requires(): """return package's install requires""" base = os.path.abspath(os.path.dirname(__file__)) requirements_file = os.path.join(base, 'requirements.txt') if not os.path.exists(requirements_file): return [] with open(requirements_file, mode='rt', encoding='utf-8') as f:...
0.002801
def get_qtls_from_mapqtl_data(matrix, threshold, inputfile): """Extract the QTLs found by MapQTL reading its file. This assume that there is only one QTL per linkage group. :arg matrix, the MapQTL file read in memory :arg threshold, threshold used to determine if a given LOD value is reflective...
0.000886
def reweight(self, weight, edges=None, copy=False): '''Replaces existing edge weights. weight may be a scalar or 1d array. edges is a mask or index array that specifies a subset of edges to modify''' if not self.is_weighted(): warnings.warn('Cannot supply weights for unweighted graph; ' ...
0.008977
def partition(predicate, iterable): """Use a predicate to partition true and false entries. Reference --------- Python itertools documentation. """ t1, t2 = tee(iterable) return filterfalse(predicate, t1), filter(predicate, t2)
0.003876
def get_hostmap(profile): ''' We abuse the profile combination to also derive a pilot-host map, which will tell us on what exact host each pilot has been running. To do so, we check for the PMGR_ACTIVE advance event in agent_0.prof, and use the NTP sync info to associate a hostname. ''' # F...
0.001639
def stop(self): """ Method for shutting down the watcher. All config file observers are stopped and their threads joined, along with the worker thread pool. """ self.shutdown.set() for monitor in self.observers: monitor.stop() self.wind_down...
0.004
def compose(self, data): """ condense reaction container to CGR. see init for details about cgr_type :param data: ReactionContainer :return: CGRContainer """ g = self.__separate(data) if self.__cgr_type in (1, 2, 3, 4, 5, 6) else self.__condense(data) g.meta.upda...
0.008571
def upgrade(): """Upgrade database.""" op.create_table( 'access_actionsroles', sa.Column('id', sa.Integer(), nullable=False), sa.Column('action', sa.String(length=80), nullable=True), sa.Column('exclude', sa.Boolean(name='exclude'), server_default='0', nullable=...
0.000532
def pave_community(self): """ Usage: containment pave_community """ settings.project_config.path.mkdir() settings.project_config.base.write_text(self.context.base_text) settings.project_config.os_packages.write_text("[]") settings.project_config.lang_pac...
0.005848
def tabLayout(self): ''' For all tabs, specify the number of buttons in a row ''' self.childWindow.column += 1 if self.childWindow.column > Layout.BUTTONS_NUMBER: self.childWindow.column = 0 self.childWindow.row += 1
0.007576
def up_capture(self, benchmark, threshold=0.0, compare_op="ge"): """Upside capture ratio. Measures the performance of `self` relative to benchmark conditioned on periods where `benchmark` is gt or ge to `threshold`. Upside capture ratios are calculated by taking the fund's ...
0.001435
def watch_from_file(connection, file_name): """ Start watching a new volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type file_name: str :param file_name: path to config file :returns: None """ with open(file_name, 'r') as filehandle:...
0.001764
def parse(self, filepath, dependencies=False, recursive=False, greedy=False): """Parses the fortran code in the specified file. :arg dependencies: if true, all folder paths will be searched for modules that have been referenced but aren't loaded in the parser. :arg greedy: if true, when...
0.006595
def all(cls, **kwargs): """Return a `Page` of instances of this `Resource` class from its general collection endpoint. Only `Resource` classes with specified `collection_path` endpoints can be requested with this method. Any provided keyword arguments are passed to the API endpo...
0.003724