text
stringlengths
78
104k
score
float64
0
0.18
def check_runner(self): """Make sure there is a runner.""" if os.getcwd() not in sys.path: sys.path.append(os.getcwd()) if self.runner is None: self.runner = Runner(self.comp, exit=self.exit_runner, store=self.mypy)
0.011407
def load_nameserver_credentials(self, working_directory, num_tries=60, interval=1): """ loads the nameserver credentials in cases where master and workers share a filesystem Parameters ---------- working_directory: str the working directory for the HPB run (see master) num_tries: int number of at...
0.037628
def to_element(self, include_namespaces=False): """Return an ElementTree Element representing this instance. Args: include_namespaces (bool, optional): If True, include xml namespace attributes on the root element Return: ~xml.etree.ElementTree.Element: ...
0.000975
def get_utc_timestamp(self, handle): """Return the UTC timestamp.""" fpath = self._fpath_from_handle(handle) datetime_obj = datetime.datetime.utcfromtimestamp( os.stat(fpath).st_mtime ) return timestamp(datetime_obj)
0.007463
def _find_function(name, region=None, key=None, keyid=None, profile=None): ''' Given function name, find and return matching Lambda information. ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) for funcs in __utils__['boto3.paged_call'](conn.list_functio...
0.002208
def get_characters(self, *args, **kwargs): """ Returns a full CharacterDataWrapper object for this story. /stories/{storyId}/characters :returns: CharacterDataWrapper -- A new request to API. Contains full results set. """ from .character import Character, CharacterDat...
0.009615
def check_log_files_and_publish_updates(self): """Get any changes to the log files and push updates to Redis. Returns: True if anything was published and false otherwise. """ anything_published = False for file_info in self.open_file_infos: assert not fil...
0.001037
def process(meta): """Saves metadata fields in global variables and returns a few computed fields.""" # pylint: disable=global-statement global capitalize global use_cleveref_default global plusname global starname global numbersections # Read in the metadata fields and do some che...
0.001154
def decode_jwt(encoded_token): """ Returns the decoded token from an encoded one. This does all the checks to insure that the decoded token is valid before returning it. """ secret = config.decode_key algorithm = config.algorithm audience = config.audience return jwt.decode(encoded_token...
0.005376
def validate(self): """ Validate filter condition (template method). """ super(NumericFilterBase, self).validate() self.not_null = False if self._value.startswith('+'): self._cmp = operator.gt self._rt_cmp = 'greater' self._value = self._valu...
0.003546
def ok_check(function, *args, **kwargs): '''Ensure that the response body is OK''' req = function(*args, **kwargs) if req.content.lower() != 'ok': raise ClientException(req.content) return req.content
0.004464
def get_alias(self): """ Gets the alias for the table or the auto_alias if one is set. If there isn't any kind of alias, None is returned. :returns: The table alias, auto_alias, or None :rtype: str or None """ alias = None if self.alias: alias...
0.004751
def aes_b64_encrypt(value, secret, block_size=AES.block_size): """ AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt ...
0.001082
def fix_multiple_files(filenames, options, output=None): """Fix list of files. Optionally fix files recursively. """ results = [] filenames = find_files(filenames, options.recursive, options.exclude) if options.jobs > 1: import multiprocessing pool = multiprocessing.Pool(option...
0.001008
def extract(self, item): """Runs the HTML-response trough a list of initialized extractors, a cleaner and compares the results. :param item: NewscrawlerItem to be processed. :return: An updated NewscrawlerItem including the results of the extraction """ article_candidates = [] ...
0.004242
def sync_subscriber(subscriber): """Sync a Customer with Stripe api data.""" customer, _created = Customer.get_or_create(subscriber=subscriber) try: customer.sync_from_stripe_data(customer.api_retrieve()) customer._sync_subscriptions() customer._sync_invoices() customer._sync_cards() customer._sync_charges...
0.029925
def set_remote_addr(self, dst_mac, dst_ip): """ Configure remote ethernet and IP addresses. """ self.dst_mac = dst_mac self.dst_ip = dst_ip if not (dst_mac == "FF:FF:FF:FF:FF:FF" or dst_ip == "255.255.255.255"): self._remote_addr_config = True LOG.in...
0.004484
def save_to_npy_file(self, parameter_space, result_parsing_function, filename, runs): """ Save results to a numpy array file format. """ np.save(filename, self.get_results_as_numpy_array( parameter_space, result_parsing_functi...
0.01194
def GetKey(self, path, cycle=9999, rootpy=True, **kwargs): """ Override TDirectory's GetKey and also handle accessing keys nested arbitrarily deep in subdirectories. """ key = super(_DirectoryBase, self).GetKey(path, cycle) if not key: raise DoesNotExist ...
0.005063
def _walk(top, topdown=True, onerror=None, followlinks=False): """Like Python 3.5's implementation of os.walk() -- faster than the pre-Python 3.5 version as it uses scandir() internally. """ dirs = [] nondirs = [] # We may not have read permission for top, in which case we can't # get a lis...
0.00036
def draw_default(self, inside=5, outside=15): """ Draw suggested sun disk, limb, and empty background :param inside: how many pixels from the calculated solar disk edge to go inward for the limb :param outside: how many pixels from the calculated solar disk edge to go outward for the lim...
0.004905
def set_oauth_client(self, consumer_key, consumer_secret): """Sets the oauth_client attribute """ self.oauth_client = oauth1.Client(consumer_key, consumer_secret)
0.010753
def urls(self): """ The decoded URL list for this MIME::Type. The special URL value IANA will be translated into: http://www.iana.org/assignments/media-types/<mediatype>/<subtype> The special URL value RFC### will be translated into: http://www.rfc-editor.org/rfc/rfc#...
0.005535
def get_permissions(self): """ :returns: list of dicts, or an empty list if there are no permissions. """ path = Client.urls['all_permissions'] conns = self._call(path, 'GET') return conns
0.008475
def create(self, resource_class, content_type): """ Creates a representer for the given combination of resource and content type. This will also find representer factories that were registered for a base class of the given resource. """ rpr_fac = self.__find_representer_f...
0.002591
def _soup_strings(soup): """Return text strings in soup.""" paragraph_tags = set([ "caption", "details", "h1", "h2", "h3", "h4", "h5", "h6", "li", "p", "td", "div", "span" ]) skip_children = None for descendant in soup.descendants: # If we've treated a tag as a contiguous paragraph, don't re-...
0.012475
def start(self): """ Start the daemon """ # Check for a pidfile to see if the daemon already runs pid = None if os.path.exists(self.pidfile): try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close...
0.004847
def K(self, X, X2, target): """Compute the covariance matrix between X and X2.""" if X2 is None: X2 = X # i1 = X[:,1] # i2 = X2[:,1] # X = X[:,0].reshape(-1,1) # X2 = X2[:,0].reshape(-1,1) dist = np.abs(X - X2.T) ly=1/self.lengthscaleY lu=np.s...
0.023876
def modify_prefix(arg, opts, shell_opts): """ Modify the prefix 'arg' with the options 'opts' """ modify_confirmed = shell_opts.force spec = { 'prefix': arg } v = get_vrf(opts.get('vrf_rt'), abort=True) spec['vrf_rt'] = v.rt res = Prefix.list(spec) if len(res) == 0: print("Pre...
0.004021
def set_key(self, key='C'): """Add a key signature event to the track_data.""" if isinstance(key, Key): key = key.name[0] self.track_data += self.key_signature_event(key)
0.009709
def send(self, command): """ Sends commands to this hypervisor. :param command: a uBridge hypervisor command :returns: results as a list """ # uBridge responses are of the form: # 1xx yyyyyy\r\n # 1xx yyyyyy\r\n # ... # 100-yyyy\...
0.004184
def parse_tibia_date(date_str) -> Optional[datetime.date]: """Parses a date from the format used in Tibia.com Accepted format: - ``MMM DD YYYY``, e.g. ``Jul 23 2015`` Parameters ----------- date_str: :class:`str` The date as represented in Tibia.com Returns ----------- :c...
0.001832
def count_names_by_namespace(graph, namespace): """Get the set of all of the names in a given namespace that are in the graph. :param pybel.BELGraph graph: A BEL graph :param str namespace: A namespace keyword :return: A counter from {name: frequency} :rtype: collections.Counter :raises IndexE...
0.003436
def has_perm(self, user, perm, obj=None): """Returns True if the given user has the specified permission.""" if not user.is_active: return False return perm in self.get_all_permissions(user, obj)
0.008658
def pretty_plot_two_axis(x, y1, y2, xlabel=None, y1label=None, y2label=None, width=8, height=None, dpi=300): """ Variant of pretty_plot that does a dual axis plot. Adapted from matplotlib examples. Makes it easier to create plots with different axes. Args: x (np.ndarray...
0.000363
def GenerarPDF(self, archivo="", dest="F"): "Generar archivo de salida en formato PDF" try: self.template.render(archivo, dest=dest) return True except Exception, e: self.Excepcion = str(e) return False
0.007299
def to_dict(self): "Post as a dict, for serializing" d = self.metadata.copy() d['content'] = self.content return d
0.013699
def update_cookies(self, cookies: Optional[LooseCookies]) -> None: """Update request cookies header.""" if not cookies: return c = SimpleCookie() if hdrs.COOKIE in self.headers: c.load(self.headers.get(hdrs.COOKIE, '')) del self.headers[hdrs.COOKIE] ...
0.002176
def _verify_temperature(self, temp): """Verifies that the temperature is valid. :raises TemperatureException: On invalid temperature. """ if temp < self.min_temp or temp > self.max_temp: raise TemperatureException('Temperature {} out of range [{}, {}]' ...
0.007813
def get_topic(self, topic_name): """Get a client for a topic entity. :param topic_name: The name of the topic. :type topic_name: str :rtype: ~azure.servicebus.servicebus_client.TopicClient :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not...
0.00438
def user_session_info_output_user_role(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") user_session_info = ET.Element("user_session_info") config = user_session_info output = ET.SubElement(user_session_info, "output") user_role = ET.SubEl...
0.004115
def set( string, target_level, indent_string=" ", indent_empty_lines=False ): """ Sets indentation of a single/multi-line string. """ lines = string.splitlines() set_lines( lines, target_level, indent_string=indent_string, indent_empty_lines=indent_empty_lines ) result = "\n".join(lines) r...
0.021084
def create_schema(self, connection): """ Will create the schema in the database """ if '.' not in self.table: return query = 'CREATE SCHEMA IF NOT EXISTS {schema_name};'.format(schema_name=self.table.split('.')[0]) connection.cursor().execute(query)
0.009677
def get_file_hash(fpath, blocksize=65536, hasher=None, stride=1, hexdigest=False): r""" For better hashes use hasher=hashlib.sha256, and keep stride=1 Args: fpath (str): file path string blocksize (int): 2 ** 16. Affects speed of reading file hasher (None): defau...
0.00038
def save_fits(self, data, name): """ This method simply saves the model components and the residual. INPUTS: data (no default) Data which is to be saved. name (no default) File name for new .fits file. Will overwrite. """ data = data.reshape(1, 1, dat...
0.006289
def volume_up(self): """Increasing volume of the device.""" self._volume_level += self._volume_step / self._max_volume self._device.vol_up(num=self._volume_step)
0.010811
def iter_trees(self, *args, **kwargs): """:return: Iterator yielding Tree objects :note: Takes all arguments known to iter_commits method""" return (c.tree for c in self.iter_commits(*args, **kwargs))
0.008929
def _layout(self): """ Creates the grid layout for the joint plot, adding new axes for the histograms if necessary and modifying the aspect ratio. Does not modify the axes or the layout if self.hist is False or None. """ # Ensure the axes are created if not hist, then ret...
0.005199
def processString(inptStr): ''' inptStr may be a string of the following forms: * 'meme: text0 | text1' * 'gif: search_keywords' If not, it returns an appropriate error message, stating an improperly formatted <magic> tag. Fails gracefully when it can't find or generate a meme or ...
0.003575
def get_config(name, region=None, key=None, keyid=None, profile=None): ''' Get the configuration for a cache cluster. CLI example:: salt myminion boto_elasticache.get_config myelasticache ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: r...
0.000413
def parse_template(template): """returns a 2-tuple of (template_name, number_of_priors)""" m = TEMPLATE_OVERRIDE_RE.match(template) if not m: return template, 0 return m.group('template'), int(m.group('depth'))
0.004274
def operate(self, left, right, operation): """ Do operation on colors args: left (str): left side right (str): right side operation (str): Operation returns: str """ operation = { '+': operator.add, '-': oper...
0.004376
def universal_transformer_with_lstm_as_transition_function( layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """Universal Transformer which uses a lstm as transition function. It's kind of like having a lstm, filliped vertically next to the Universal Transformer that controls the flo...
0.004202
def _get_remote_ontology(onto_url, time_difference=None): """Check if the online ontology is more recent than the local ontology. If yes, try to download and store it in Invenio's cache directory. Return a boolean describing the success of the operation. :return: path to the downloaded ontology. ...
0.000609
def Deserialize(self, reader): """ Deserialize full object. Args: reader (neo.IO.BinaryReader): """ self.__hash = None self.DeserializeUnsigned(reader) byt = reader.ReadByte() if int(byt) != 1: raise Exception('Incorrect format') ...
0.004843
def closed(self) -> bool: '''Return whether the connection is closed.''' return not self.writer or not self.reader or self.reader.at_eof()
0.012987
def flatten(lol): """Flatten a list of lists to a list. :param lol: A list of lists in arbitrary depth. :type lol: list of list. :returns: flat list of elements. """ new_list = [] for element in lol: if element is None: continue elif not isinstance(element, list...
0.002037
def fill_series(x, year): """Returns the value of a timeseries (indexed over years) for a year by linear interpolation. Parameters ---------- x: pandas.Series a timeseries to be interpolated year: int year of interpolation """ x = x.dropna() if year in x.index and no...
0.001531
def change_settings(self, bio=None, public_images=None, messaging_enabled=None, album_privacy=None, accepted_gallery_terms=None): """ Update the settings for the user. :param bio: A basic description filled out by the user, is displayed in ...
0.003962
def do_plugins(self, args, arguments): """ :: Usage: plugins add COMMAND [--dryrun] [-q] plugins delete COMMAND [--dryrun] [-q] plugins list [--output=FORMAT] [-q] plugins activate Arguments: FORMA...
0.001787
def get_assets_by_genus_type(self, asset_genus_type): """Gets an ``AssetList`` corresponding to the given asset genus ``Type`` which does not include assets of types derived from the specified ``Type``. In plenary mode, the returned list contains all known assets or an error results. Otherwise,...
0.002772
def publish(self, load): ''' Publish "load" to minions. This send the load to the publisher daemon process with does the actual sending to minions. :param dict load: A load to be sent across the wire to minions ''' payload = {'enc': 'aes'} crypticle = salt.crypt....
0.002698
def _mutate(self): ''' Mutate enclosed fields ''' for i in range(self._field_idx, len(self._fields)): self._field_idx = i if self._current_field().mutate(): return True self._current_field().reset() return False
0.006601
def _StartSshd(self): """Initialize the SSH daemon.""" # Exit as early as possible. # Instance setup systemd scripts block sshd from starting. if os.path.exists(constants.LOCALBASE + '/bin/systemctl'): return elif (os.path.exists('/etc/init.d/ssh') or os.path.exists('/etc/init/ssh.co...
0.009494
def _resolve_input(variable, variable_name, config_key, config): """ Resolve input entered as option values with config values If option values are provided (passed in as `variable`), then they are returned unchanged. If `variable` is None, then we first look for a config value to use. If no ...
0.000917
def get(self): '''xxxxx.xxxxx.campaign.areaoptions.get =================================== 取得推广计划的可设置投放地域列表''' request = TOPRequest('xxxxx.xxxxx.campaign.areaoptions.get') self.create(self.execute(request), fields=['success','result'], models={'result':AreaOption}) return...
0.01506
def _parseRequestValues(self, request, command): """Parses all the values in the request that are in a form specific to the JSON AMP dialect. """ for key, ampType in command.arguments: ampClass = ampType.__class__ if ampClass is exposed.ExposedResponderLocator: ...
0.003546
def set_value(self, value): """ Sets the user value of the symbol. Equal in effect to assigning the value to the symbol within a .config file. For bool and tristate symbols, use the 'assignable' attribute to check which values can currently be assigned. Setting values outside ...
0.00248
def read_private_key_file(pkey_file, pkey_password=None, key_type=None, logger=None): """ Get SSH Public key from a private key file, given an optional password Arguments: pkey_file (str): ...
0.002924
def _get_private_room(self, invitees: List[User]): """ Create an anonymous, private room and invite peers """ return self._client.create_room( None, invitees=[user.user_id for user in invitees], is_public=False, )
0.007326
def raw_value(self): """ Property to return the variable defined in ``django.conf.settings``. Returns: object: the variable defined in ``django.conf.settings``. Raises: AttributeError: if the variable is missing. KeyError: if the item is missing from...
0.003817
def open(self, path, mode='r'): """Open stream, returning ``Stream`` object""" entry = self.find(path) if entry is None: if mode == 'r': raise ValueError("stream does not exists: %s" % path) entry = self.create_dir_entry(path, 'stream', None) els...
0.003538
def __look_up_geom(self, geomType): """ compares the geometry object's type verse the JSOn specs for geometry types Inputs: geomType - string - geometry object's type Returns: string JSON geometry type or None if not an allowed type """ ...
0.002865
def _create_api_call(self, method, _url, kwargs): """ This will create an APICall object and return it :param method: str of the html method ['GET','POST','PUT','DELETE'] :param _url: str of the sub url of the api call (ex. g/device/list) :param kwargs: dict of additional ar...
0.001842
def load_state(self, state_id, delete=True): """ Load a state from storage identified by `state_id`. :param state_id: The state reference of what to load :return: The deserialized state :rtype: State """ return self._store.load_state(f'{self._prefix}{state_id:08x...
0.008523
def image(name, data, step=None, max_outputs=3, description=None): """Write an image summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes. data: A `Tensor` representing pixe...
0.003066
def start(client, container, interactive=True, stdout=None, stderr=None, stdin=None, logs=None): """ Present the PTY of the container inside the current process. This is just a wrapper for PseudoTerminal(client, container).start() """ operation = RunOperation(client, container, interactive=interac...
0.006593
def get_crl(self, expires=86400, encoding=None, algorithm=None, password=None, scope=None, **kwargs): """Generate a Certificate Revocation List (CRL). The ``full_name`` and ``relative_name`` parameters describe how to retrieve the CRL and are used in the `Issuing Distribution Point extension <h...
0.004893
def format_messages(self, messages): """ Formats several messages with :class:Look, encodes them with :func:vital.tools.encoding.stdout_encode """ mess = "" for message in self.message: if self.pretty: mess = "{}{}".format(mess, self.format_message(message...
0.003584
def dist_iter(self, g_nums, ats_1, ats_2, invalid_error=False): """ Iterator over selected interatomic distances. Distances are in Bohrs as with :meth:`dist_single`. See `above <toc-generators_>`_ for more information on calling options. Parameters ---------- g...
0.001737
def init_sqlite_db(path, initTime=False): """ Initialize SQLite Database Args: path(str): Path to database (Ex. '/home/username/my_sqlite.db'). initTime(Optional[bool]): If True, it will print the amount of time to generate database. Example:: from gsshapy.lib.db_tools...
0.014199
def elliot_function( signal, derivative=False ): """ A fast approximation of sigmoid """ s = 1 # steepness abs_signal = (1 + np.abs(signal * s)) if derivative: return 0.5 * s / abs_signal**2 else: # Return the activation signal return 0.5*(signal * s) / abs_signal + 0.5
0.015674
def nvmlDeviceSetComputeMode(handle, mode): r""" /** * Set the compute mode for the device. * * For all products. * Requires root/admin permissions. * * The compute mode determines whether a GPU can be used for compute operations and whether it can * be shared across contexts....
0.005552
def save_profile_as(self): """Save the minimum needs under a new profile name. """ # noinspection PyCallByClass,PyTypeChecker file_name_dialog = QFileDialog(self) file_name_dialog.setAcceptMode(QFileDialog.AcceptSave) file_name_dialog.setNameFilter(self.tr('JSON files (*....
0.001334
def print_options(self): """ print description of the component options """ summary = [] for opt_name, opt in self.options.items(): if opt.hidden: continue summary.append(opt.summary()) print("\n".join(summary))
0.006873
def visitInlineShapeOrRef(self, ctx: ShExDocParser.InlineShapeOrRefContext): """ inlineShapeOrRef: inlineShapeDefinition | shapeRef """ if ctx.inlineShapeDefinition(): from pyshexc.parser_impl.shex_shape_definition_parser import ShexShapeDefinitionParser shdef_parser = ShexShapeD...
0.005618
def _convert_operator(op_name, attrs, identity_list=None, convert_map=None): """Convert from onnx operator to mxnet operator. The converter must specify conversions explicitly for incompatible name, and apply handlers to operator attributes. Parameters ---------- op_name : str Operator ...
0.002278
def finalize_block(self, block: BaseBlock) -> BaseBlock: """ Perform any finalization steps like awarding the block mining reward, and persisting the final state root. """ if block.number > 0: self._assign_block_rewards(block) # We need to call `persist` here...
0.00565
def get(self, request, *args, **kwargs): """ Main entry. This View only responds to GET requests. """ context = self.chart_instance.chartjs_configuration(*args, **kwargs) return self.render_json_response(context)
0.007937
def add_nodes_from(self, nodes, weights=None): """ Add multiple nodes to the Graph. **The behviour of adding weights is different than in networkx. Parameters ---------- nodes: iterable container A container of nodes (list, dict, set, or any hashable python ...
0.001422
def hvals(self, key, *, encoding=_NOTSET): """Get all the values in a hash.""" return self.execute(b'HVALS', key, encoding=encoding)
0.013514
def assert_not_present(self, selector, testid=None, **kwargs): """Assert that the element is not present in the dom Args: selector (str): the selector used to find the element test_id (str): the test_id or a str Kwargs: wait_until_not_present (bool) ...
0.001571
def do_dir(self, args, unknown): """List contents of current directory.""" # No arguments for this command if unknown: self.perror("dir does not take any positional arguments:", traceback_war=False) self.do_help('dir') self._last_result = cmd2.CommandResult(''...
0.004478
def decoded_output_boxes(self): """ Returns: Nx#classx4 """ ret = self._cascade_boxes[-1] ret = tf.expand_dims(ret, 1) # class-agnostic return tf.tile(ret, [1, self.num_classes, 1])
0.008163
def set_properties(self, pathobj, props, recursive): """ Set artifact properties """ url = '/'.join([pathobj.drive, 'api/storage', str(pathobj.relative_to(pathobj.drive)).strip('/')]) params = {'properties': encode_properties(props...
0.002398
def commit_transaction(self): """ Commit the current transaction. :returns: the bookmark returned from the server, if any :raise: :class:`.TransactionError` if no transaction is currently open """ self._assert_open() if not self._transaction: raise Transactio...
0.002857
def defUtilityFuncs(self): ''' Defines CRRA utility function for this period (and its derivatives, and their inverses), saving them as attributes of self for other methods to use. Parameters ---------- none Returns ------- none ''...
0.022523
def get_imports(fname): """ get a list of imports from a Python program """ txt = '' with open(fname, 'r') as f: for line in f: if line[0:6] == 'import': txt += '<PRE>' + strip_text_after_string(line[7:], ' as ') + '</PRE>\n' return txt + '<BR>'
0.006734
def savefig(self, output_path, **kwargs): """Save figure during generation. This method is used to save a completed figure during the main function run. It represents a call to ``matplotlib.pyplot.fig.savefig``. # TODO: Switch to kwargs for matplotlib.pyplot.savefig Args: ...
0.005019
def formvalue (form, key): """Get value with given key from WSGI form.""" field = form.get(key) if isinstance(field, list): field = field[0] return field
0.011299