text
stringlengths
78
104k
score
float64
0
0.18
def flush_evicted_objects_unsafe(): """This removes some critical state from the Redis shards. In a multitenant environment, this will flush metadata for all jobs, which may be undesirable. This removes all of the metadata for objects that have been evicted. This can be used to try to address out-...
0.001531
def _lenstr(ins): ''' Returns string length ''' (tmp1, output) = _str_oper(ins.quad[2], no_exaf=True) if tmp1: output.append('push hl') output.append('call __STRLEN') output.extend(_free_sequence(tmp1)) output.append('push hl') REQUIRES.add('strlen.asm') return output
0.003195
def do_action(self, action): """Execute action, add a new tile, update the score & return the reward.""" temp_state = np.rot90(self._state, action) reward = self._do_action_left(temp_state) self._state = np.rot90(temp_state, -action) self._score += reward self.add_rando...
0.008547
def get_function_spec(name): """Return a dictionary with the specification of a function: parameter names and defaults (value, bounds, scale, etc.). Returns ------- par_names : list List of parameter names for this function. norm_par : str Name of normalization parameter. ...
0.002488
def _calc(self, x, y): """ List based implementation of binary tree algorithm for concordance measure after :cite:`Christensen2005`. """ x = np.array(x) y = np.array(y) n = len(y) perm = list(range(n)) perm.sort(key=lambda a: (x[a], y[a])) ...
0.000675
def def_cmd(name=None, short=None, fn=None, usage=None, help=None): """ Define a command. """ command = Command(name=name, short=short, fn=fn, usage=usage, help=help) Command.register(command)
0.004717
def restore_memory_snapshot(self, snapshot, bSkipMappedFiles = True, bSkipOnError = False): """ Attempts to restore the memory state as it was when the given snapshot was taken. @warning: Currently only the memory contents,...
0.004265
def _check_curtailment_target(curtailment, curtailment_target, curtailment_key): """ Raises an error if curtailment target was not met in any time step. Parameters ----------- curtailment : :pandas:`pandas:DataFrame<dataframe>` Dataframe containing the curtailm...
0.000882
def show_all(key): ''' Context: - abbr - metadata - bill - sources - nav_active Templates: - billy/web/public/bill_all_{key}.html - where key is passed in, like "actions", etc. ''' def func(request, abbr, session, bill_id, key): # ...
0.000803
def intersection(self, other): """ Return the intersection between this time interval and the given time interval, or ``None`` if the two intervals do not overlap. :rtype: :class:`~aeneas.exacttiming.TimeInterval` or ``NoneType`` """ relative_position = self.rela...
0.001223
def num_to_var_int(x): """ (bitcoin-specific): convert an integer into a variable-length integer """ x = int(x) if x < 253: return from_int_to_byte(x) elif x < 65536: return from_int_to_byte(253) + encode(x, 256, 2)[::-1] elif x < 4294967296: return from_int_to_byte...
0.002353
def alignments(self): """ Get alignments from the SAM/BAM file, subject to filtering. """ referenceIds = self.referenceIds dropUnmapped = self.dropUnmapped dropSecondary = self.dropSecondary dropSupplementary = self.dropSupplementary dropDuplicates = self....
0.000466
def format_volume(citation_elements): """format volume number (roman numbers to arabic) When the volume number is expressed in roman numbers (CXXII), they are converted to their equivalent in arabic numbers (42) """ re_roman = re.compile(re_roman_numbers + u'$', re.UNICODE) for el in citation_e...
0.002028
def ensure_indirect_subclass(class_, of): """Check whether given is an indirect subclass of another, i.e. there exists at least intermediate base between ``of`` and ``class_``. :param class_: Class to check :param of: Superclass to check against :return: ``class_``, if the check succeeds :rais...
0.001706
def can_pp_seq_no_be_in_view(self, view_no, pp_seq_no): """ Checks if the `pp_seq_no` could have been in view `view_no`. It will return False when the `pp_seq_no` belongs to a later view than `view_no` else will return True :return: """ if view_no > self.viewNo: ...
0.005571
def _get_field_comment(field, separator=' - '): """ Create SQL comment from field's title and description :param field: tableschema-py Field, with optional 'title' and 'description' values :param separator: :return: >>> _get_field_comment(tableschema.Field({'title': 'my_title', 'description': ...
0.006211
def save_chkpt_vars(dic, path): """ Save variables in dic to path. Args: dic: {name: value} path: save as npz if the name ends with '.npz', otherwise save as a checkpoint. """ logger.info("Variables to save to {}:".format(path)) keys = sorted(list(dic.keys())) logger.info(pp...
0.00237
def write_module_code(self, module_code): """write module-level template code, i.e. that which is enclosed in <%! %> tags in the template.""" for n in module_code: self.printer.start_source(n.lineno) self.printer.write_indented_block(n.text)
0.00692
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ if isinstance(self.input.payload, Instances): inst = None data = self.input.payload elif isinstance(self.inpu...
0.002141
def query(self, query=None, callback=None): """Performs a query against the index using the passed lunr.Query object. If performing programmatic queries against the index, this method is preferred over `lunr.Index.search` so as to avoid the additional query parsing overhead. ...
0.001076
def token(self) -> str: """ Return token identifying role to indy-sdk. :return: token: 'STEWARD', 'TRUSTEE', 'TRUST_ANCHOR', or None (for USER) """ return self.value[0] if self in (Role.USER, Role.ROLE_REMOVE) else self.name
0.015038
def call(self, fn, *args, **kwargs): """ Like :meth:`call_async`, but block until the return value is available. Equivalent to:: call_async(fn, *args, **kwargs).get().unpickle() :returns: The function's return value. :raises mitogen.core.CallError: ...
0.003883
def poll(self, batch_id, retry_seconds=None, back_off=None, timeout=None, halt_on_error=True): """Poll Batch status to ThreatConnect API. .. code-block:: javascript { "status": "Success", "data": { "batchStatus": { ...
0.004387
def _report_container_count(self, containers_by_id): """Report container count per state""" m_func = FUNC_MAP[GAUGE][self.use_histogram] per_state_count = defaultdict(int) filterlambda = lambda ctr: not self._is_container_excluded(ctr) containers = list(filter(filterlambda, con...
0.006494
def Cross(width=3, color=0): """Draws a cross centered in the target area :param width: width of the lines of the cross in pixels :type width: int :param color: color of the lines of the cross :type color: pygame.Color """ return Overlay(Line("h", width, color), Line("v", width, color))
0.003165
def copy_contents_to(self, destination): """ Copies the contents of this directory to the given destination. Returns a Folder object that represents the moved directory. """ logger.info("Copying contents of %s to %s" % (self, destination)) target = Folder(destination) ...
0.004386
def get_xdg_home(self): # type: () -> str """ Returns the value specified in the XDG_CONFIG_HOME environment variable or the appropriate default. """ config_home = getenv('XDG_CONFIG_HOME', '') if config_home: self._log.debug('XDG_CONFIG_HOME is set to...
0.008016
def load_bytecode(self, f): """Loads bytecode from a file or file like object.""" # make sure the magic header is correct magic = f.read(len(bc_magic)) if magic != bc_magic: self.reset() return # the source code of the file changed, we need to reload ...
0.004292
def _feature_most_population(self, results): """ Find the placename with the largest population and return its country. More population is a rough measure of importance. Paramaters ---------- results: dict output of `query_geonames` Returns -...
0.004032
def _addToBuffers(self, logname, data): """ Add data to the buffer for logname Start a timer to send the buffers if BUFFER_TIMEOUT elapses. If adding data causes the buffer size to grow beyond BUFFER_SIZE, then the buffers will be sent. """ n = len(data) ...
0.003247
def is_file(self, follow_symlinks=True): """ Return True if this entry is a file or a symbolic link pointing to a file; return False if the entry is or points to a directory or other non-file entry, or if it doesn’t exist anymore. The result is cached on the os.DirEntry object. ...
0.003241
def play_env_problem_randomly(env_problem, num_steps): """Plays the env problem by randomly sampling actions for `num_steps`.""" # Reset all environments. env_problem.reset() # Play all environments, sampling random actions each time. for _ in range(num_steps): # Sample batc...
0.008547
def save_all(self): """ Save all editors. """ initial_index = self.currentIndex() for i in range(self.count()): try: self.setCurrentIndex(i) self.save_current() except AttributeError: pass self.setCur...
0.005814
def context_loader(self, callback): """ Decorate a method that receives a key id and returns an object or dict that will be available in the request context as g.cavage_context """ if not callback or not callable(callback): raise Exception("Please pass in a callable t...
0.007194
def update(self, a, b, c, d): """ Update contingency table with new values without creating a new object. """ self.table.ravel()[:] = [a, b, c, d] self.N = self.table.sum()
0.009434
def get_target_state(): """SDP target State. Returns the target state; allowed target states and time updated """ sdp_state = SDPState() errval, errdict = _check_status(sdp_state) if errval == "error": LOG.debug(errdict['reason']) return dict( current_target_state="u...
0.001312
def _loop_wrapper_func(func, args, shared_mem_run, shared_mem_pause, interval, sigint, sigterm, name, logging_level, conn_send, func_running, log_queue): """ to be executed as a separate process (that's why this functions is declared static) """ prefix = get_identifier(name) +...
0.005671
def _smooth_hpx_map(hpx_map, sigma): """ Smooth a healpix map using a Gaussian """ if hpx_map.hpx.ordering == "NESTED": ring_map = hpx_map.swap_scheme() else: ring_map = hpx_map ring_data = ring_map.data.copy() nebins = len(hpx_map.data) sm...
0.002649
def add_config(self, cfg_or_file=None, **kw_conf): """ Add a configuration entry to this ingredient/experiment. Can be called with a filename, a dictionary xor with keyword arguments. Supported formats for the config-file so far are: ``json``, ``pickle`` and ``yaml``. T...
0.002291
def generic_export(request, model_name=None): """ Generic view configured through settings.TABLIB_MODELS Usage: 1. Add the view to ``urlpatterns`` in ``urls.py``:: url(r'export/(?P<model_name>[^/]+)/$', "django_tablib.views.generic_export"), 2. Create the ``setti...
0.000494
def findConfigFile(cls, filename): """ Search the configuration path (specified via the NTA_CONF_PATH environment variable) for the given filename. If found, return the complete path to the file. :param filename: (string) name of file to locate """ paths = cls.getConfigPaths() for p in pat...
0.006787
def save(self, filename="temp.pkl"): """ Save TM in the filename specified above """ output = open(filename, 'wb') cPickle.dump(self.tm, output, protocol=cPickle.HIGHEST_PROTOCOL)
0.005025
def is_acquired(self): """Check if the lock is acquired""" values = self.client.get(self.key) return six.b(self._uuid) in values
0.013158
def is_analysis_attachment_allowed(self, analysis): """Checks if the analysis """ if analysis.getAttachmentOption() not in ["p", "r"]: return False if api.get_workflow_status_of(analysis) in ["retracted"]: return False return True
0.006803
def run(self, steps=10): """Executes up to `steps` instructions.""" try: super(GeneticMachine, self).run(steps) self._error = False except StopIteration: self._error = False except Exception: self._error = True
0.006897
def register_controller(self, module, required=True, min_number=1): """Loads a controller module and returns its loaded devices. This is to be used in a mobly test class. Args: module: A module that follows the controller module interface. required: A bool. If True, fai...
0.001082
def __send_buffer(self): """ Sends the contents of self.__out_buffer to serial device :return: Number of bytes written """ bytes_written = self.serial.write(self.__out_buffer.raw) if self.DEBUG_MODE: print("Wrote: '{}'".format(binascii.hexlify(self.__out_buffe...
0.008183
def session_path(cls, project, session): """Return a fully-qualified session string.""" return google.api_core.path_template.expand( 'projects/{project}/agent/sessions/{session}', project=project, session=session, )
0.007273
def get_backend_router_id_from_hostname(self, hostname): """Finds the backend router Id that matches the hostname given No way to use an objectFilter to find a backendRouter, so we have to search the hard way. """ results = self.client.call('SoftLayer_Network_Pod', 'getAllObjects') ...
0.009281
def obj_for_name(obj_name): """ Instantiate class or function :param obj_name: class or function name :return: instance of class or function """ parts = obj_name.split('.') module = ".".join(parts[:-1]) m = __import__( module ) for comp in parts[1:]: m = getattr(m, comp) ...
0.009146
def md( self, url, width="original"): """*generate a multimarkdown image link viewable anywhere (no sign-in needed for private photos)* **Key Arguments:** - ``url`` -- the share URL for the flickr image (or just the unique photoid) - ``width`...
0.003766
def pick_keys(self, keys, use="", alg=""): """ The assumption is that upper layer has made certain you only get keys you can use. :param alg: The crypto algorithm :param use: What the key should be used for :param keys: A list of JWK instances :return: A list of ...
0.00179
def non_neighbors(graph, node, t=None): """Returns the non-neighbors of the node in the graph at time t. Parameters ---------- graph : DyNetx graph Graph to find neighbors. node : node The node whose neighbors will be returned. t : snapshot id (defa...
0.00243
def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ assert isinstance(value, datetime.date) assert not isinstance(value, datetime.datetime) try: value = value - datetime.date(year=1970, month=1, day=1) except Overfl...
0.006696
def group_alleles_by_start_end_Xbp(arr, bp=28): """Group alleles by matching ends Args: arr (numpy.array): 2D int matrix of alleles bp (int): length of ends to group by Returns: dict of lists: key of start + end strings to list of indices of alleles with matching ends """ s...
0.00569
def get_romfile_path(game, inttype=Integrations.DEFAULT): """ Return the path to a given game's romfile """ for extension in EMU_EXTENSIONS.keys(): possible_path = get_file_path(game, "rom" + extension, inttype) if possible_path: return possible_path raise FileNotFoundEr...
0.002747
def load_publickey(type, buffer): """ Load a public key from a buffer. :param type: The file type (one of :data:`FILETYPE_PEM`, :data:`FILETYPE_ASN1`). :param buffer: The buffer the key is stored in. :type buffer: A Python string object, either unicode or bytestring. :return: The PKey o...
0.001035
def max_runs_reached(self): """ :return: whether all file paths have been processed max_runs times """ if self._max_runs == -1: # Unlimited runs. return False for file_path in self._file_paths: if self._run_count[file_path] < self._max_runs: ...
0.004474
def lock(instance_id, profile=None, **kwargs): ''' Lock an instance instance_id ID of the instance to be locked CLI Example: .. code-block:: bash salt '*' nova.lock 1138 ''' conn = _auth(profile, **kwargs) return conn.lock(instance_id)
0.003472
def split_markers_from_line(line): # type: (AnyStr) -> Tuple[AnyStr, Optional[AnyStr]] """Split markers from a dependency""" if not any(line.startswith(uri_prefix) for uri_prefix in SCHEME_LIST): marker_sep = ";" else: marker_sep = "; " markers = None if marker_sep in line: ...
0.002252
def _determine_doubled_obj(self): """Return the target object. Returns the object that should be treated as the target object. For partial doubles, this will be the same as ``self.obj``, but for pure doubles, it's pulled from the special ``_doubles_target`` attribute. :return: ...
0.007782
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 targets_yaml is None: return job_configs config_yaml = 'config.yaml' ...
0.002231
def list_element_combinations_variadic( elements_specification ): """ This function accepts a specification of lists of elements for each place in lists in the form of a list, the elements of which are lists of possible elements and returns a list of lists corresponding to the combinations of ...
0.004376
def schemaValidateOneElement(self, elem): """Validate a branch of a tree, starting with the given @elem. """ if elem is None: elem__o = None else: elem__o = elem._o ret = libxml2mod.xmlSchemaValidateOneElement(self._o, elem__o) return ret
0.014388
def wins(self, year): """Returns the # of regular season wins a team in a year. :year: The year for the season in question. :returns: The number of regular season wins. """ schedule = self.schedule(year) if schedule.empty: return np.nan return schedul...
0.005587
def register(name, validator): """Register a validator instance under the given ``name``.""" if not isinstance(validator, Validator): raise TypeError("Validator instance expected, %s given" % validator.__class__) _NAMED_VALIDATORS[name] = validator
0.007463
def farthest(self, dt1, dt2, *dts): from functools import reduce """ Get the farthest date from the instance. :type dt1: datetime.datetime :type dt2: datetime.datetime :type dts: list[datetime.datetime,] :rtype: DateTime """ dt1 = pendulum.insta...
0.003937
def save_model(self, steps): """ Saves the model :param steps: The number of steps the model was trained for :return: """ with self.graph.as_default(): last_checkpoint = self.model_path + '/model-' + str(steps) + '.cptk' self.saver.save(self.sess, ...
0.006438
def gradient(self): """ Derivative of the covariance matrix over the parameters of L. Returns ------- Lu : ndarray Derivative of K over the lower triangular part of L. """ L = self.L self._grad_Lu[:] = 0 for i in range(len(self._tril1...
0.002448
def download(self, filename, representation, overwrite=False): """Download the resolved structure as a file. :param string filename: File path to save to :param string representation: Desired output representation :param bool overwrite: (Optional) Whether to allow overwriting of an exis...
0.008889
def get_response(self, request, *args, **kwargs): '''Returns the redirect response for this exception.''' # normal process response = HttpResponseRedirect(self.redirect_to) response[REDIRECT_HEADER_KEY] = self.redirect_to return response
0.00722
def register_builtin_message_types(): """Registers the built-in message types.""" from .plain import PlainTextMessage from .email import EmailTextMessage, EmailHtmlMessage register_message_types(PlainTextMessage, EmailTextMessage, EmailHtmlMessage)
0.007576
def _event_for(self, elts): """Creates an Event that is set when the bundle with elts is sent.""" event = Event() event.canceller = self._canceller_for(elts, event) return event
0.009569
def _readNamelist(currentlyIncluding, cache, namFilename, unique_glyphs): """ Detect infinite recursion and prevent it. This is an implementation detail of readNamelist. Raises NamelistRecursionError if namFilename is in the process of being included """ # normalize filename = os.path.abspath(os.path.norm...
0.017036
def send_keyevents(self, keyevent: int) -> None: '''Simulates typing keyevents.''' self._execute('-s', self.device_sn, 'shell', 'input', 'keyevent', str(keyevent))
0.00995
def get_user(self, user_id=None, username=None, email=None): """ Returns the user specified by either ID, username or email. Since more than user can have the same email address, searching by that term will return a list of 1 or more User objects. Searching by username or ID wil...
0.002172
def update_default(cls) -> 'TrustStoresRepository': """Update the default trust stores used by SSLyze. The latest stores will be downloaded from https://github.com/nabla-c0d3/trust_stores_observatory. """ temp_path = mkdtemp() try: # Download the latest trust stores ...
0.002915
def which_roles_can(self, name): """Which role can SendMail? """ targetPermissionRecords = AuthPermission.objects(creator=self.client, name=name).first() return [{'role': group.role} for group in targetPermissionRecords.groups]
0.015936
def prj_view_seq(self, *args, **kwargs): """View the, in the prj_seq_tablev selected, sequence. :returns: None :rtype: None :raises: None """ if not self.cur_prj: return i = self.prj_seq_tablev.currentIndex() item = i.internalPointer() ...
0.005013
def fit(self, X, y, num_training_samples=None): """Use correlation data to train a model. First compute the correlation of the input data, and then normalize within subject if more than one sample in one subject, and then fit to a model defined by self.clf. Parameters ...
0.000618
def _build_line(colwidths, colaligns, linefmt): "Return a string which represents a horizontal line." if not linefmt: return None if hasattr(linefmt, "__call__"): return linefmt(colwidths, colaligns) else: begin, fill, sep, end = linefmt cells = [fill*w for w in colwidth...
0.002625
def groups_roles(self, room_id=None, room_name=None, **kwargs): """Lists all user’s roles in the private group.""" if room_id: return self.__call_api_get('groups.roles', roomId=room_id, kwargs=kwargs) elif room_name: return self.__call_api_get('groups.roles', roomName=roo...
0.009217
def verify( self, headers, serialized_request_env, deserialized_request_env): # type: (Dict[str, Any], str, RequestEnvelope) -> None """Verify if the input request signature and the body matches. The verify method retrieves the Signature Certificate Chain URL, validates the ...
0.001874
def repo(name: str, owner: str) -> snug.Query[dict]: """a repository lookup by owner and name""" return json.loads((yield f'/repos/{owner}/{name}').content)
0.006098
def fix_groups(groups): """Takes care of strange group numbers.""" _groups = [] for g in groups: try: if not float(g) > 0: _groups.append(1000) else: _groups.append(int(g)) except TypeError as e: logging.info("Error in readi...
0.00216
def set_video_stream_param(self, streamtype, resolution, bitrate, framerate, gop, isvbr, callback=None): ''' Set the video stream param of stream N streamtype(0~3): Stream N. resolution(0~4): 0 720P, 1 VGA(640*480), 2 VGA(640*...
0.007456
def coerce(self, values): """Convert an iterable of literals to an iterable of options. Args: values (iterable or string): An iterable of raw values to convert into options. If the value is a string is is assumed to be a comma separated list and will be split b...
0.001823
def invoke_hook_bolt_fail(self, heron_tuple, fail_latency_ns): """invoke task hooks for every time bolt fails a tuple :type heron_tuple: HeronTuple :param heron_tuple: tuple that is failed :type fail_latency_ns: float :param fail_latency_ns: fail latency in nano seconds """ if len(self.task...
0.006192
def _update(self, conf_dict, base_name=None): """ Updates the current configuration with the values in `conf_dict`. :param dict conf_dict: Dictionary of key value settings. :param str base_name: Base namespace for setting keys. """ for name in conf_dict: # S...
0.001735
def enterEvent( self, event ): """ Toggles the display for the tracker item. """ item = self.trackerItem() if ( item ): item.setVisible(True)
0.030151
def draw_canvas(): """Render the tkinter canvas based on the state of ``world``""" for x in range(len(world)): for y in range(len(world[x])): if world[x][y].value: color = world[x][y].color_alive.get_as_hex() else: color = world[x][y].color_dead.ge...
0.002558
def emit(self, record): """ Override emit() method in handler parent for sending log to RESTful API """ # avoid infinite recursion if record.name.startswith('requests'): return data, header = self._prepPayload(record) try: self.session.po...
0.003914
def rpc_get_consensus_hashes( self, block_id_list, **con_info ): """ Return the consensus hashes at multiple block numbers Return a dict mapping each block ID to its consensus hash. Returns {'status': True, 'consensus_hashes': dict} on success Returns {'error': ...} on success ...
0.006309
def endswith(self, suffix, start=0, end=None): """Return True if ends with the specified suffix, False otherwise. With optional start, test beginning at that position. With optional end, stop comparing at that position. suffix can also be a tuple of strings to try. :param str suffix: S...
0.005282
def logon(self, password='admin'): """ Parameters ---------- password : str default 'admin' Returns ------- dict """ r = self._basic_post(url='logon', data=password) return r.json()
0.007299
def rest(self, token, endpoint=None, timeout=None): """Obtain a metadata REST API client.""" from . import rest return rest.SignalFxRestClient( token=token, endpoint=endpoint or self._api_endpoint, timeout=timeout or self._timeout)
0.006873
def align_blocks(source_sentences, target_sentences, params = LanguageIndependent): """Creates the sentence alignment of two blocks of texts (usually paragraphs). @param source_sentences: The list of source sentence lengths. @param target_sentences: The list of target sentence lengths. @param params: t...
0.006555
def open_upload_stream_with_id( self, file_id, filename, chunk_size_bytes=None, metadata=None): """Opens a Stream that the application can write the contents of the file to. The user must specify the file id and filename, and can choose to add any additional information in t...
0.001014
def effectiveTagSet(self): """Return a :class:`~pyasn1.type.tag.TagSet` object of the currently initialized component or self (if |ASN.1| is tagged).""" if self.tagSet: return self.tagSet else: component = self.getComponent() return component.effectiveTagSet
0.009434
def load(self, 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. Set to...
0.005863