text
stringlengths
78
104k
score
float64
0
0.18
def fix_abicritical(self): """ method to fix crashes/error caused by abinit Returns: 1 if task has been fixed else 0. """ event_handlers = self.event_handlers if not event_handlers: self.set_status(status=self.S_ERROR, msg='Empty list of event han...
0.003841
def point(self, t): """returns the coordinates of the Bezier curve evaluated at t.""" distance = self.end - self.start return self.start + distance*t
0.011561
def getColors(self): """ Overrideable function that generates the colors to be used by various styles. Should return a 5-tuple of ``(bg,o,i,s,h)``\ . ``bg`` is the base color of the background. ``o`` is the outer color, it is usually the same as the bac...
0.03183
def predict(self, x_test): """Returns the prediction of the model on the given test data. Args: x_test : array-like, shape = (n_samples, sent_length) Test samples. Returns: y_pred : array-like, shape = (n_smaples, sent_length) Prediction labels f...
0.004471
def stop(self, timeout: int = 5) -> None: """ Try to stop the transaction store in the given timeout or raise an exception. """ self.running = False start = time.perf_counter() while True: if self.getsCounter == 0: return True ...
0.003552
def clean_dataset_tags(self): # type: () -> Tuple[bool, bool] """Clean dataset tags according to tags cleanup spreadsheet and return if any changes occurred Returns: Tuple[bool, bool]: Returns (True if tags changed or False if not, True if error or False if not) """ ...
0.00263
def update(self, other, inplace=True): """Update this series by appending new data from an other and dropping the same amount of data off the start. This is a convenience method that just calls `~Series.append` with `resize=False`. """ return self.append(other, inplace=i...
0.005865
def _set_traffic_state(self, v, load=False): """ Setter method for traffic_state, mapped from YANG variable /traffic_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_traffic_state is considered as a private method. Backends looking to populate this v...
0.005609
def comunicar_certificado_icpbrasil(self, certificado): """Função ``ComunicarCertificadoICPBRASIL`` conforme ER SAT, item 6.1.2. Envio do certificado criado pela ICP-Brasil. :param str certificado: Conteúdo do certificado digital criado pela autoridade certificadora ICP-Brasil. ...
0.005425
def remove_sentence_boundaries(tensor: torch.Tensor, mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ Remove begin/end of sentence embeddings from the batch of sentences. Given a batch of sentences with size ``(batch_size, timesteps, dim)`` this returns a tens...
0.003827
def images_to_matrix(image_list, mask=None, sigma=None, epsilon=0.5 ): """ Read images into rows of a matrix, given a mask - much faster for large datasets as it is based on C++ implementations. ANTsR function: `imagesToMatrix` Arguments --------- image_list : list of ANTsImage types ...
0.003636
def is_in_bounds(self, width, height) -> bool: """ Check if this entire region is contained within the bounds of a given stage size.""" if self._top < 0 \ or self._bottom > height \ or self._left < 0 \ or self._right > width: return False ...
0.008982
def repeat(mode): """Change repeat mode of current player.""" message = command(protobuf.CommandInfo_pb2.ChangeShuffleMode) send_command = message.inner() send_command.options.externalPlayerCommand = True send_command.options.repeatMode = mode return message
0.003546
def _xls2code(self, worksheet, tab): """Updates code in xls code_array""" def xlrddate2datetime(xlrd_date): """Returns datetime from xlrd_date""" try: xldate_tuple = xlrd.xldate_as_tuple(xlrd_date, self.workboo...
0.001712
def ask_bool(question: str, default: bool = True) -> bool: """Asks a question yes no style""" default_q = "Y/n" if default else "y/N" answer = input("{0} [{1}]: ".format(question, default_q)) lower = answer.lower() if not lower: return default return lower == "y"
0.00339
def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None): """ Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure wi...
0.007731
def itemFromIndex(self, index): """ Gets the item given the model index """ sourceIndex = self.mapToSource(index) return self.sourceModel().itemFromIndex(sourceIndex)
0.010101
def renderJsonReadsSince(self, timestamp, meter): """ Simple since Time_Stamp query returned as JSON records. Args: timestamp (int): Epoch time in seconds. meter (str): 12 character meter address to query Returns: str: JSON rendered read records. ""...
0.005252
def _repopulate_pool(self): """ Bring the number of pool processes up to the specified number, for use after reaping workers which have exited. """ for i in range(self._processes - len(self._pool)): w = self.Process(target=worker, args=(se...
0.002347
def _try_coerce_args(self, values, other): """ localize and return i8 for the values Parameters ---------- values : ndarray-like other : ndarray-like or scalar Returns ------- base-type values, base-type other """ # asi8 is a view...
0.001412
def get_info(self): """Return a list with all information available about this process""" return [self.display_name.encode(), self.enabled and b'enabled' or b'disabled', STATE_NAMES[self.state].encode() + b':', self.last_printed_line.strip()]
0.006536
def rlist_classes(module, cls_filter=None): """ Attempts to list all of the classes within a given module namespace. This method, unlike list_classes, will recurse into discovered submodules. If a type filter is set, it will be called with each class as its parameter. This filter's return value...
0.001159
def patch_anchors(parser, show_progressbar): """ Consume ``ParseEntry``s then patch docs for TOCs by calling *parser*'s ``find_and_patch_entry``. """ files = defaultdict(list) try: while True: pentry = (yield) try: fname, anchor = pentry.path.split...
0.000624
def scale_geom_opt_threshold(self, gradient=0.1, displacement=0.1, energy=0.1): """ Adjust the convergence criteria of geometry optimization. Args: gradient: the scale factor for gradient criteria. If less than 1.0, you are tightening...
0.002311
def curve_specialize(curve, new_curve): """Image for :meth`.Curve.specialize` docstring.""" if NO_IMAGES: return ax = curve.plot(256) interval = r"$\left[0, 1\right]$" line = ax.lines[-1] line.set_label(interval) color1 = line.get_color() new_curve.plot(256, ax=ax) interval ...
0.001081
def result(self, timeout=None): """Return the result of the call that the future represents. Args: timeout: The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time. Returns: The result of th...
0.002643
def free_numeric(self): """Free numeric data""" if self._numeric is not None: self.funs.free_numeric(self._numeric) self._numeric = None self.free_symbolic()
0.009569
def add_static_route(self, gateway, destination, network=None): """ Add a static route to this route table. Destination can be any element type supported in the routing table such as a Group of network members. Since a static route gateway needs to be on the same network as the i...
0.003858
def check_exec_installed(exec_list): """ Check the required programs are installed. PARAM exec_list: list of programs to check RETURN: True if all installed else False """ all_installed = True for exe in exec_list: if not is_tool(exe): print("Executable: " + e...
0.002475
def get_env_variable(var_name, default=None): """Get the environment variable or raise exception.""" try: return os.environ[var_name] except KeyError: if default is not None: return default else: error_msg = 'The environment variable {} was missing, abort...'\...
0.002451
def create_all(self, progress_callback: Optional[callable] = None) -> Dict[str, object]: """ Creates all the models discovered from fixture files in :attr:`fixtures_dir`. :param progress_callback: An optional function to track progress. It must take three paramete...
0.004852
def _observed_name(field, name): """Adjust field name to reflect `dump_to` and `load_from` attributes. :param Field field: A marshmallow field. :param str name: Field name :rtype: str """ if MARSHMALLOW_VERSION_INFO[0] < 3: # use getattr in case we're running...
0.005386
def _compute_mean(self, C, mag, rrup, hypo_depth, delta_R, delta_S, delta_V, delta_I, vs30): """ Compute MMI Intensity Value as per Equation in Table 5 and Table 7 pag 198. """ # mean is calculated for all the 4 classes using the same equation. # Fo...
0.003367
def tunnel_to_kernel(self, connection_info, hostname, sshkey=None, password=None, timeout=10): """ Tunnel connections to a kernel via ssh. Remote ports are specified in the connection info ci. """ lports = zmqtunnel.select_random_ports(4) ...
0.00428
def set_(name, value, profile=None, **kwargs): ''' Set a key in etcd name The etcd key name, for example: ``/foo/bar/baz``. value The value the key should contain. profile Optional, defaults to ``None``. Sets the etcd profile to use which has been defined in the Sal...
0.000946
def end_date(self): """账户的交易结束日期(只在回测中使用) Raises: RuntimeWarning -- [description] Returns: [type] -- [description] """ if self.start_==None: if len(self.time_index_max) > 0: return str(max(self.time_index_max))[0:10] ...
0.007366
def _trim_files(files, trim_output): ''' Trim the file list for output. ''' count = 100 if not isinstance(trim_output, bool): count = trim_output if not(isinstance(trim_output, bool) and trim_output is False) and len(files) > count: files = files[:count] files.append("Li...
0.005249
def get_all(content, container, object_type): ''' Get all items of a certain type Example: get_all(content, vim.Datastore) return all datastore objects ''' obj_list = list() view_manager = content.viewManager object_view = view_manager.CreateContainerView( container, [object_type], T...
0.002075
def remove_link(self, obj, attr=None): """ removes link from obj.attr """ name = repr(self) if not name: return self l = self.__class__._get_links() v = WeakAttrLink(None, obj) if attr is None else WeakAttrLink(obj, attr) if name in l: ...
0.008889
def _draw_ellipse(data, obj, draw_options): """Return the PGFPlots code for ellipses. """ if isinstance(obj, mpl.patches.Circle): # circle specialization return _draw_circle(data, obj, draw_options) x, y = obj.center ff = data["float format"] if obj.angle != 0: fmt = "ro...
0.001416
def to_bed(call, sample, work_dir, calls, data): """Create a simplified BED file from caller specific input. """ out_file = os.path.join(work_dir, "%s-%s-flat.bed" % (sample, call["variantcaller"])) if call.get("vrn_file") and not utils.file_uptodate(out_file, call["vrn_file"]): with file_transa...
0.005376
def possible_import_patterns(modname): """ does not support from x import * does not support from x import z, y Example: >>> # DISABLE_DOCTEST >>> import utool as ut >>> modname = 'package.submod.submod2.module' >>> result = ut.repr3(ut.possible_import_patterns(modname))...
0.000833
def output_tree_ensemble(tree_ensemble_obj, output_filename, attribute_names=None): """ Write each decision tree in an ensemble to a file. Parameters ---------- tree_ensemble_obj : sklearn.ensemble object Random Forest or Gradient Boosted Regression object output_filename : str ...
0.004706
def _use_inf_as_na(key): """Option change callback for na/inf behaviour Choose which replacement for numpy.isnan / -numpy.isfinite is used. Parameters ---------- flag: bool True means treat None, NaN, INF, -INF as null (old way), False means None and NaN are null, but INF, -INF are ...
0.001332
def search_nn_dist(self, point, distance, best=None): """ Search the n nearest nodes of the given point which are within given distance point must be a location, not a node. A list containing the n nearest nodes to the point within the distance will be returned. """ ...
0.006397
def get_file_named(self, fldr, xtn): """ scans a directory for files like *.GZ or *.ZIP and returns the filename of the first one found (should only be one of each file here """ res = [] # list of Sample objects for root, _, files in os.walk(fldr): ...
0.005085
def checkAndCreate(self, key, payload, hostgroupConf, hostgroupParent, puppetClassesId): """ Function checkAndCreate check And Create procedure for an hostgroup - check the hostgroup is not existing - create the hostgro...
0.003205
def add(self, **kwargs): """Returns a new MayaDT object with the given offsets.""" return self.from_datetime( pendulum.instance(self.datetime()).add(**kwargs) )
0.010204
def create_model(samples_x, samples_y_aggregation, percentage_goodbatch=0.34): ''' Create the Gaussian Mixture Model ''' samples = [samples_x[i] + [samples_y_aggregation[i]] for i in range(0, len(samples_x))] # Sorts so that we can get the top samples samples = sorted(samples, key=itemgetter(-1...
0.006517
def _table_attrs(table): ''' Helper function to find valid table attributes ''' cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)] res = __salt__['cmd.run_all'](cmd) if res['retcode'] == 0: attrs = [] text = salt.utils.json.loads(res['stdout']) for...
0.002433
def _parse(template): """Parse a top-level template string Expression. Any extraneous text is considered literal text. """ parser = Parser(template) parser.parse_expression() parts = parser.parts remainder = parser.string[parser.pos:] if remainder: parts.append(remainder) re...
0.002924
def wait_until_page_does_not_contain_element(self, locator, timeout=None, error=None): """Waits until element specified with `locator` disappears from current page. Fails if `timeout` expires before the element disappears. See `introduction` for more information about `timeout` and its ...
0.005353
def set_np_compat(active): """ Turns on/off NumPy compatibility. NumPy-compatibility is turned off by default in backend. Parameters ---------- active : bool Indicates whether to turn on/off NumPy compatibility. Returns ------- A bool value indicating the previous state of ...
0.006148
def unique(self, token_list_x, token_list_y): ''' Remove duplicated elements. Args: token_list_x: [token, token, token, ...] token_list_y: [token, token, token, ...] Returns: Tuple(token_list_x, token_list_y) ''' x = set...
0.007538
def get(self, key, index=None): """Retrieves a value associated with a key from the database Args: key (str): The key to retrieve """ records = self.get_multi([key], index=index) try: return records[0][1] # return the value from the key/value tuple ...
0.005464
def add_site_states(self, site, states): """Create new states on an agent site if the state doesn't exist.""" for state in states: if state not in self.site_states[site]: self.site_states[site].append(state)
0.007968
def global_variable_dictionary(self): """Property for the _global_variable_dictionary field""" dict_copy = {} for key, value in self.__global_variable_dictionary.items(): if key in self.__variable_references and self.__variable_references[key]: dict_copy[key] = value ...
0.007194
def refresh_token(self, client_id, client_secret, refresh_token, grant_type='refresh_token'): """Calls oauth/token endpoint with refresh token grant type Use this endpoint to refresh an access token, using the refresh token you got during authorization. Args: grant_type (str): Deno...
0.004803
def decode_list_oov(self, ids, source_oov_id_to_token): """decode ids back to tokens, considering OOVs temporary IDs. Args: ids: vocab ids. Could possibly include source temporary OOV ID starting from vocab_size. source_oov_id_to_token: a list of source OOV tokens, with the order the sa...
0.004208
def mass_fractions(self): r'''Dictionary of atom:mass-weighted fractional occurence of elements. Useful when performing mass balances. For atom-fraction occurences, see :obj:`atom_fractions`. Examples -------- >>> Chemical('water').mass_fractions {'H': 0.11189834...
0.005263
def parameters(self): """Get dict with all set parameters.""" parameters = {} for name in self.PARAMETERS: try: parameters[name] = self.get_parameter(name) except AttributeError: pass return parameters
0.00692
def get(self, key): """Get an item from the cache Args: key: item key Returns: the value of the item or None if the item isn't in the cache """ data = self._store.get(key) if not data: return None value, expire = dat...
0.004515
def _load_cell(args, schema): """Implements the BigQuery load magic used to load data from GCS to a table. The supported syntax is: %bigquery load -S|--source <source> -D|--destination <table> <other_args> Args: args: the arguments following '%bigquery load'. schema: a JSON schema for the dest...
0.011983
def nodes(self, tree): """ Returns the relevant nodes for the spec's frequency """ # Run the match against the tree if self.frequency == 'per_session': nodes = [] for subject in tree.subjects: for sess in subject.sessions: ...
0.002861
def set_orient(self): """ Return the computed orientation based on CD matrix. """ self.orient = RADTODEG(N.arctan2(self.cd12,self.cd22))
0.019737
def _initialize(self, runtime): """Common initializer for OsidManager and OsidProxyManager""" if runtime is None: raise NullArgument() if self._my_runtime is not None: raise IllegalState('this manager has already been initialized.') self._my_runtime = runtime ...
0.005521
def _add_unknown_char(self, string): ''' Adds an unknown character to the stack. ''' if self.has_xvowel: # Ensure an xvowel gets printed if we've got an active # one right now. self._promote_solitary_xvowel() self.unknown_char = string ...
0.0059
def disambiguate_url(url, location=None): """turn multi-ip interfaces '0.0.0.0' and '*' into connectable ones, based on the location (default interpretation is localhost). This is for zeromq urls, such as tcp://*:10101.""" try: proto,ip,port = split_url(url) except AssertionError: ...
0.020833
def change_vlan_id(self, vlan_id): """ Change a VLAN id :param str vlan_id: new vlan """ first, _ = self.nicid.split('.') self.update(nicid='{}.{}'.format(first, str(vlan_id)))
0.012876
def _e(op, inv=False): """ Lightweight factory which returns a method that builds an Expression consisting of the left-hand and right-hand operands, using `op`. """ def inner(self, rhs): if inv: return Expression(rhs, op, self) return Expre...
0.00554
def sendContact(self, context={}): """ Send contact form message to single or multiple recipients """ for recipient in self.recipients: super(ContactFormMail, self).__init__(recipient, self.async) self.sendEmail('contactForm', 'New contact form message', context)
0.013746
def yaml2tree(cls, yamltree): """Class method that creates a tree from YAML. | # Example yamltree data: | - !Node &root | name: "root node" | parent: null | data: | testpara: 111 | - !Node &child1 | name: "child node" | paren...
0.004845
def cspace_converter(start, end): """Returns a function for converting from colorspace ``start`` to colorspace ``end``. E.g., these are equivalent:: out = cspace_convert(arr, start, end) :: start_to_end_fn = cspace_converter(start, end) out = start_to_end_fn(arr) If you ...
0.001274
def _format_num(self, value): """Return the number value for value, given this field's `num_type`.""" # (value is True or value is False) is ~5x faster than isinstance(value, bool) if value is True or value is False: raise TypeError('value must be a Number, not a boolean.') r...
0.008671
def messages(self, query, **kwargs): """ https://api.slack.com/methods/search.messages """ self.url = 'https://slack.com/api/search.messages' return super(Search, self).search_from_url(query, **kwargs)
0.008584
def _set_TS_index(self, data): """ Convert index to datetime and all other columns to numeric Parameters ---------- data : pd.DataFrame() Input dataframe. Returns ------- pd.DataFrame() Modified dataframe. """ ...
0.009042
def repair_broken_bonds(self, slab, bonds): """ This method will find undercoordinated atoms due to slab cleaving specified by the bonds parameter and move them to the other surface to make sure the bond is kept intact. In a future release of surface.py, the ghost_sites will be ...
0.000898
def get_dev_interface(devid, auth, url): """ Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device interfaces :param devid: requires devid as the only input :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base u...
0.004979
def diff_bearing(b1, b2): ''' Compute difference between two bearings ''' d = abs(b2 - b1) d = 360 - d if d > 180 else d return d
0.006536
def cross(series, cross=0, direction='cross'): """ From http://stackoverflow.com/questions/10475488/calculating-crossing-intercept-points-of-a-series-or-dataframe Given a Series returns all the index values where the data values equal the 'cross' value. Direction can be 'rising' (for rising edge...
0.005431
def previous_obj(self): """Returns a model obj that is the first occurrence of a previous obj relative to this object's appointment. Override this method if not am EDC subject model / CRF. """ previous_obj = None if self.previous_visit: try: p...
0.003683
def defaults(values={}): """Returns a once-assembled dict of this module's storable attributes.""" if values: return values save_types = basestring, int, float, tuple, list, dict, type(None) for k, v in globals().items(): if isinstance(v, save_types) and not k.startswith("_"): values[k] = v...
0.00885
def profiler(sorting=('tottime',), stripDirs=True, limit=20, path='', autoclean=True): """ Creates a profile wrapper around a method to time out all the operations that it runs through. For more information, look into the hotshot Profile documentation online for the built-in Python...
0.00312
def visit_Subscript(self, node): """ >>> import gast as ast >>> from pythran import passmanager, backend >>> pm = passmanager.PassManager("test") >>> node = ast.parse("def foo(a): a[1:][3]") >>> _, node = pm.apply(PartialConstantFolding, node) >>> _, node = pm.ap...
0.001104
def get(self, path_info): """Gets the checksum for the specified path info. Checksum will be retrieved from the state database if available. Args: path_info (dict): path info to get the checksum for. Returns: str or None: checksum for the specified path info or ...
0.001978
def mtf_transformer_tiny(): """Catch bugs locally...""" hparams = mtf_transformer_base() hparams.d_model = 128 hparams.d_ff = 512 hparams.batch_size = 8 hparams.encoder_layers = ["att", "drd"] * 2 hparams.decoder_layers = ["att", "enc_att", "drd"] * 2 hparams.num_heads = 8 # data parallelism and model...
0.030303
def jobSetCompleted(self, jobID, completionReason, completionMsg, useConnectionID = True): """ Change the status on the given job to completed Parameters: ---------------------------------------------------------------- job: jobID of the job to mark as completed ...
0.005788
def extract_library_properties_from_selected_row(self): """ Extracts properties library_os_path, library_path, library_name and tree_item_key from tree store row """ (model, row) = self.view.get_selection().get_selected() tree_item_key = model[row][self.ID_STORAGE_ID] library_item = mode...
0.004768
def build_job_configs(self, args): """Hook to build job configurations """ job_configs = {} ttype = args['ttype'] (targets_yaml, sim) = NAME_FACTORY.resolve_targetfile(args) if sim is not None: raise ValueError("Found 'sim' argument on AnalyzeROI_SG config.")...
0.002157
def disable(self, idx): """Disable an element and reset the outputs""" if idx not in self.uid.keys(): self.log('Element index {0} does not exist.'.format(idx)) return self.u[self.uid[idx]] = 0
0.008333
def get_template_name(self): """ Get the template name of this page if defined or if a closer parent has a defined template or :data:`pages.settings.PAGE_DEFAULT_TEMPLATE` otherwise. """ template = self.get_template() page_templates = settings.get_page_templates()...
0.004566
def getSolution(self): """ Find and return a solution to the problem Example: >>> problem = Problem() >>> problem.getSolution() is None True >>> problem.addVariables(["a"], [42]) >>> problem.getSolution() {'a': 42} @return: Solution for ...
0.003431
def collapsed_dependencies(self): """ Accessess collapsed dependencies for this sentence :getter: Returns the dependency graph for collapsed dependencies :type: corenlp_xml.dependencies.DependencyGraph """ if self._basic_dependencies is None: deps = self._el...
0.005803
def _update(self, request, *args, **kwargs): """Update a resource.""" partial = kwargs.pop('partial', False) # NOTE: The line below was changed. instance = self.get_object_with_lock() serializer = self.get_serializer(instance, data=request.data, partial=partial) serialize...
0.005427
def _check_values(self, values): """Check values whenever they come through the values setter.""" assert isinstance(values, Iterable) and not isinstance( values, (str, dict, bytes, bytearray)), \ 'values should be a list or tuple. Got {}'.format(type(values)) if self.head...
0.004717
def rebuildDays( self ): """ Rebuilds the interface as a week display. """ time = QTime(0, 0, 0) hour = True x = 6 y = 6 + 24 w = self.width() - 12 - 25 dh = 48 indent = 58 text_d...
0.0125
def interpol_hist2d(h2d, oversamp_factor=10): """Sample the interpolator of a root 2d hist. Root's hist2d has a weird internal interpolation routine, also using neighbouring bins. """ from rootpy import ROOTError xlim = h2d.bins(axis=0) ylim = h2d.bins(axis=1) xn = h2d.nbins(0) yn ...
0.001449
def gatk_germline_pipeline(job, samples, config): """ Runs the GATK best practices pipeline for germline SNP and INDEL discovery. Steps in Pipeline 0: Generate and preprocess BAM - Uploads processed BAM to output directory 1: Call Variants using HaplotypeCaller - Uploads GVCF 2:...
0.003595
def _trim_base64(s): """Trim and hash base64 strings""" if len(s) > 64 and _base64.match(s.replace('\n', '')): h = hash_string(s) s = '%s...<snip base64, md5=%s...>' % (s[:8], h[:16]) return s
0.004545
def send_requests(self, *args): """ Send a set of requests. Each request is sent over its own connection and the function will return when all the requests have been fulfilled. """ threads = [ClientThread(self, req) for req in args] for t in threads: ...
0.00365