Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
357,200
def GET_AUTH(self, courseid): course, __ = self.get_course_and_check_rights(courseid) user_input = web.input() if "submission" in user_input: submission = self.database.submissions.find_one({"_id": ObjectId(user_input.submission), ...
GET request
357,201
def removeTextAll(self, text): removedBlocks = [] blocks = self.blocks for i in range(len(blocks)): block = blocks[i] if issubclass(block.__class__, AdvancedTag): continue if text in block: ...
removeTextAll - Removes ALL occuraces of given text in a text node (i.e. not part of a tag) @param text <str> - text to remove @return list <str> - All text node containing #text BEFORE the text was removed. Empty list if no text removed NOTE: To remove a node, @se...
357,202
def add_membership_listener(self, member_added=None, member_removed=None, fire_for_existing=False): self.membership_listeners.append((member_added, member_removed, fire_for_existing)) return self
Helper method for adding membership listeners :param member_added: (Function), Function to be called when a member is added, in the form of f(member) (optional). :param member_removed: (Function), Function to be called when a member is removed, in the form of f(member) (optional). ...
357,203
def split(series): s = df_.split_array_like(series.apply(list).to_frame(), )[] s.name = series.name return s
Split values. The index is dropped, but this may change in the future. Parameters ---------- series : ~pandas.Series[~pytil.numpy.ArrayLike] Series with array-like values. Returns ------- ~pandas.Series Series with values split across rows. Examples -------- >...
357,204
def xml_import(self, filepath=None, xml_content = None, markings=None, identifier_ns_uri = None, uid = None, **kargs): if not markings: markings = [] if no...
Call this function for generic import of an XML file with the following arguments: - filename: Path to XML file - markings (optional): List of information objects with which the imported object should be marked - identifier_ns_uri: Namespace of the identifiers, if identifiers are to b...
357,205
def get_storage(request): storage_model = oauth2_settings.storage_model user_property = oauth2_settings.storage_model_user_property credentials_property = oauth2_settings.storage_model_credentials_property if storage_model: module_name, class_name = storage_model.rsplit(, 1) module...
Gets a Credentials storage object provided by the Django OAuth2 Helper object. Args: request: Reference to the current request object. Returns: An :class:`oauth2.client.Storage` object.
357,206
def for_latitude_longitude(cls, latitude, longitude, zoom): point = Point.from_latitude_longitude(latitude=latitude, longitude=longitude) pixel_x, pixel_y = point.pixels(zoom=zoom) return cls.for_pixels(pixel_x=pixel_x, pixel_y=pixel_y, zoom=zoom)
Creates a tile from lat/lon in WGS84
357,207
def plot(self, ax_list=None, fontsize=12, **kwargs): history = self.history num_plots, ncols, nrows = len(history), 1, 1 if num_plots > 1: ncols = 2 nrows = num_plots // ncols + num_plots % ncols ax_list, fig, plot = get_axarray_fig_plt(ax_list...
Plot relaxation history i.e. the results of the last iteration of each SCF cycle. Args: ax_list: List of axes. If None a new figure is produced. fontsize: legend fontsize. kwargs: keyword arguments are passed to ax.plot Returns: matplotlib figure
357,208
def genslices(n): def range_with_none(): yield None yield from range(-n, n+1) for t in product(range_with_none(), range_with_none(), range_with_none()): s = slice(*t) if s.step != 0: yield s
Generate all possible slices for a single dimension.
357,209
def strlen(state, s): cpu = state.cpu if issymbolic(s): raise ConcretizeArgument(state.cpu, 1) zero_idx = _find_zero(cpu, state.constraints, s) ret = zero_idx for offset in range(zero_idx - 1, -1, -1): byt = cpu.read_int(s + offset, 8) if issymbolic(byt): ...
strlen symbolic model. Algorithm: Walks from end of string not including NULL building ITE tree when current byte is symbolic. :param State state: current program state :param int s: Address of string :return: Symbolic strlen result :rtype: Expression or int
357,210
def coreBurkAlpha(self, R, Rs, rho0, r_core, ax_x, ax_y): x = R * Rs ** -1 p = Rs * r_core ** -1 gx = self._G(x, p) a = 2 * rho0 * Rs ** 2 * gx / x return a * ax_x / R, a * ax_y / R
deflection angle :param R: :param Rs: :param rho0: :param r_core: :param ax_x: :param ax_y: :return:
357,211
def check_for_named_partition(self, schema, table, partition_name): with self.metastore as client: return client.check_for_named_partition(schema, table, partition_name)
Checks whether a partition with a given name exists :param schema: Name of hive schema (database) @table belongs to :type schema: str :param table: Name of hive table @partition belongs to :type schema: str :partition: Name of the partitions to check for (eg `a=b/c=d`) :...
357,212
def set_outlets(self, pores=[], overwrite=False): r if self.settings[] is False: logger.warning( + ) Ps = self._parse_indices(pores) if np.sum(self[][Ps]) > 0: raise Exception() if overwrite: self[] = False se...
r""" Set the locations through which defender exits the network. This is only necessary if 'trapping' was set to True when ``setup`` was called. Parameters ---------- pores : array_like Locations where the defender can exit the network. Any defender ...
357,213
def get_track_by_id(session, track_id, track_point_limit=None, track_point_offset=None): tracking_data = {} if track_point_limit: tracking_data[] = track_point_limit if track_point_offset: tracking_data[] = track_point_offset response = make_get_request(session, .format(trac...
Gets a specific track
357,214
def get_user(): if HAS_PWD: ret = pwd.getpwuid(os.geteuid()).pw_name elif HAS_WIN_FUNCTIONS and salt.utils.win_functions.HAS_WIN32: ret = salt.utils.win_functions.get_current_user() else: raise CommandExecutionError( ) return salt.utils.stringutils.to_unicode(ret...
Get the current user
357,215
def move(self, target_parent, name=None, include_children=True, include_instances=True): if not name: name = self.name if self.category == Category.MODEL and target_parent.category == Category.MODEL: moved_model = relocate_model(part=self, target_parent=target_parent, na...
Move the `Part` to target parent, both of them the same category. .. versionadded:: 2.3 :param target_parent: `Part` object under which the desired `Part` is moved :type target_parent: :class:`Part` :param name: how the moved top-level `Part` should be called :type name: basest...
357,216
def last_update_time(self) -> float: stdout = self.stdout_interceptor stderr = self.stderr_interceptor return max([ self._last_update_time, stdout.last_write_time if stdout else 0, stderr.last_write_time if stderr else 0, ])
The last time at which the report was modified.
357,217
def key_verify(rsakey, signature, message, digest): padding = _asymmetric.padding.PKCS1v15() if isinstance(rsakey, _asymmetric.rsa.RSAPrivateKey): rsakey = rsakey.public_key() try: rsakey.verify(signature, message, padding, digest) except Exception as e: return False el...
Verify the given signature with the RSA key.
357,218
def writeObject(self, obj, output, setReferencePosition=False): def proc_variable_length(format, length): result = b if length > 0b1110: result += pack(, (format << 4) | 0b1111) result = self.writeObject(length, result) else: ...
Serializes the given object to the output. Returns output. If setReferencePosition is True, will set the position the object was written.
357,219
def clear_sent_messages(self, offset=None): if offset is None: offset = getattr(settings, , defaults.MAILQUEUE_CLEAR_OFFSET) if type(offset) is int: offset = datetime.timedelta(hours=offset) delete_before = timezone.now() - offset self.filter(sent=True,...
Deletes sent MailerMessage records
357,220
def add(self, data, header, row=None, subheader=None): if self.rows is not None and row is None: raise ValueError() if self.rows is None and row is not None: raise ValueError() if isinstance(data, pd.Series): if subheader is not None: ...
Filter `data` by arguments of this SummaryStats instance, then apply `pd.describe()` and format the statistics Parameters ---------- data : pd.DataFrame or pd.Series data for which summary statistics should be computed header : str column name for descrip...
357,221
def get_cached_menus(): items = cache.get(CACHE_KEY) if items is None: menu = generate_menu() cache.set(CACHE_KEY, menu.items) else: menu = Menu(items) return menu
Return the menus from the cache or generate them if needed.
357,222
def add_package(self, name): name, cls_name = parse_package_string(name) if name in self.package_map: return package = EffectPackage(name) package.load() self.packages.append(package) self.package_map[package.name] = package self....
Registers a single package :param name: (str) The effect package to add
357,223
def write_data(fo, datum, schema): record_type = extract_record_type(schema) logical_type = extract_logical_type(schema) fn = WRITERS.get(record_type) if fn: if logical_type: prepare = LOGICAL_WRITERS.get(logical_type) if prepare: datum = prepare(da...
Write a datum of data to output stream. Paramaters ---------- fo: file-like Output file datum: object Data to write schema: dict Schemda to use
357,224
def get_conn(self): if not self._client: self._client = Client(credentials=self._get_credentials()) return self._client
Retrieves connection to Cloud Translate :return: Google Cloud Translate client object. :rtype: Client
357,225
def download_file(self, bucket, key, filename, extra_args=None, expected_size=None): self._start_if_needed() if extra_args is None: extra_args = {} self._validate_all_known_args(extra_args) transfer_id = self._transfer_monitor.notify_new_transfe...
Downloads the object's contents to a file :type bucket: str :param bucket: The name of the bucket to download from :type key: str :param key: The name of the key to download from :type filename: str :param filename: The name of a file to download to. :type ext...
357,226
def purge_existing_ovb(nova_api, neutron): LOG.info() for server in nova_api.servers.list(): if server.name in (, ): server.delete() if server.name.startswith(): server.delete() for router in neutron.list_routers().get(): if router[] not in (, ): ...
Purge any trace of an existing OVB deployment.
357,227
def init(self, sys_clock, swo_clock, console): self._swo_clock = swo_clock if not self._session.probe.has_swo(): LOG.warning("Probe %s does not support SWO", self._session.probe.unique_id) return self._session.target.trace_start() ...
! @brief Configures trace graph and starts thread. This method performs all steps required to start up SWV. It first calls the target's trace_start() method, which allows for target-specific trace initialization. Then it configures the TPIU and ITM modules. A simple trace data processin...
357,228
def tag(self, sentence, tokenize=True): if sentence.strip() == "": return [] elif sentence.strip() in PUNCTUATION: if self.include_punc: _sym = sentence.strip() if _sym in tuple(): _tag = "." ...
Tag a string `sentence`. :param str or list sentence: A string or a list of sentence strings. :param tokenize: (optional) If ``False`` string has to be tokenized before (space separated string).
357,229
def _indent_change(change, out, options, indent): show_unchanged = getattr(options, "show_unchanged", False) show_ignored = getattr(options, "show_ignored", False) show = False desc = change.get_description() if change.is_change(): if change.is_ignored(options): if show_i...
recursive function to print indented change descriptions
357,230
def parse(rmk: str) -> RemarksData: rmkdata = {} for item in rmk.split(): if len(item) in [5, 9] and item[0] == and item[1:].isdigit(): rmkdata[] = core.make_number(_tdec(item[1:5], None)) rmkdata[] = core.make_number(_tdec(item[5:], None)) return RemarksData(**rmkd...
Finds temperature and dewpoint decimal values from the remarks
357,231
def state_size(self) -> Sequence[Shape]: return self._sizes(self._compiler.rddl.state_size)
Returns the MDP state size.
357,232
def build_suite(args): loader = Loader() if len(args.files) == 0 or args.files[0] == "-": suite = loader.load_suite_from_stdin() else: suite = loader.load(args.files) return suite
Build a test suite by loading TAP files or a TAP stream.
357,233
def cleanup_handlers(event=None): if event: if event in HANDLER_REGISTRY: del HANDLER_REGISTRY[event] if event in EXTERNAL_HANDLER_REGISTRY: del EXTERNAL_HANDLER_REGISTRY[event] else: HANDLER_REGISTRY.clear() EXTERNAL_HANDLER_REGISTRY.clear()
Remove handlers of a given `event`. If no event is informed, wipe out all events registered. Be careful!! This function is intended to help when writing tests and for debugging purposes. If you call it, all handlers associated to an event (or to all of them) will be disassociated. Which means that ...
357,234
def generate_table_shared_access_signature(self, table_name, permission=None, expiry=None, start=None, id=None, ip=None, protocol=None, start_pk=None, start_rk=None, ...
Generates a shared access signature for the table. Use the returned signature with the sas_token parameter of TableService. :param str table_name: The name of the table to create a SAS token for. :param TablePermissions permission: The permissions associated with the sha...
357,235
def TensorBoardWSGIApp(logdir, plugins, multiplexer, reload_interval, path_prefix=, reload_task=): path_to_run = parse_event_files_spec(logdir) if reload_interval >= 0: start_reloading_multiplexer(multiplexer, path_to_run, reload_interval, relo...
Constructs the TensorBoard application. Args: logdir: the logdir spec that describes where data will be loaded. may be a directory, or comma,separated list of directories, or colons can be used to provide named directories plugins: A list of base_plugin.TBPlugin subclass instances. multiplexe...
357,236
def _restart_stream(self): self._input_state = "restart" self._output_state = "restart" self.features = None self.transport.restart() if self.initiator: self._send_stream_start(self.stream_id)
Restart the stream as needed after SASL and StartTLS negotiation.
357,237
def clear_intersection(self, other_dict): for key, value in other_dict.items(): if key in self.globals and self.globals[key] is value: del self.globals[key] if key in self.locals and self.locals[key] is value: del self.locals[key] return...
Clears out locals and globals from this scope where the key-value pair matches with other_dict. This allows cleanup of temporary variables that may have washed up into this Scope. Arguments --------- other_dict: a :class:`dict` to be used to determine scope clearance. ...
357,238
def get_dip(self): areas = self._get_areas() dips = numpy.array([surf.get_dip() for surf in self.surfaces]) return numpy.sum(areas * dips) / numpy.sum(areas)
Compute dip of each surface element and return area-weighted average value (in range ``(0, 90]``). Given that dip values are constrained in the range (0, 90], the simple formula for weighted mean is used.
357,239
def register_backend(name, backend, allow_overwrite=False): if hasattr(Circuit, "run_with_" + name): if allow_overwrite: warnings.warn(f"Circuit has attribute `run_with_{name}`.") else: raise ValueError(f"Circuit has attribute `run_with_{name}`.")...
Register new backend. Args: name (str): The name of backend. gateclass (type): The type object of backend allow_overwrite (bool, optional): If True, allow to overwrite the existing backend. Otherwise, raise the ValueError. Raises: ValueEr...
357,240
def json(self, conversion: _Text = ) -> Mapping: if not self._json: if conversion is : from xmljson import badgerfish as serializer elif conversion is : from xmljson import abdera as serializer elif conversion is : f...
A JSON Representation of the XML. Default is badgerfish. :param conversion: Which conversion method to use. (`learn more <https://github.com/sanand0/xmljson#conventions>`_)
357,241
def declare_actor(self, actor): self.emit_before("declare_actor", actor) self.declare_queue(actor.queue_name) self.actors[actor.actor_name] = actor self.emit_after("declare_actor", actor)
Declare a new actor on this broker. Declaring an Actor twice replaces the first actor with the second by name. Parameters: actor(Actor): The actor being declared.
357,242
def get_local_densities(data, kernel_mult = 2.0, metric = ): data = np.atleast_2d(data) assert isinstance(kernel_mult, numbers.Real) and kernel_mult > 0 kernel_width = kernel_mult * median_min_distance(data, metric) N_samples = data.shape[0] if 8.0 * get_chunk_size(N_sample...
For each sample point of the data-set 'data', estimate a local density in feature space by counting the number of neighboring data-points within a particular region centered around that sample point. Parameters ---------- data : array of shape (n_samples, n_features) The data-se...
357,243
def endpoint_get(auth=None, **kwargs): * cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return cloud.get_endpoint(**kwargs)
Get a single endpoint CLI Example: .. code-block:: bash salt '*' keystoneng.endpoint_get id=02cffaa173b2460f98e40eda3748dae5
357,244
def pxconfig(self, line): args = magic_arguments.parse_argstring(self.pxconfig, line) if args.targets: self.view.targets = self._eval_target_str(args.targets) if args.block is not None: self.view.block = args.block if args.set_verbose is not None: ...
configure default targets/blocking for %px magics
357,245
def is_ordered_mapping(obj): if not (is_mapping(obj) and hasattr(obj, )): return False try: obj.__reversed__() except TypeError: return False else: return True
Checks whether given object is an ordered mapping, e.g. a :class:`OrderedDict`. :return: ``True`` if argument is an ordered mapping, ``False`` otherwise
357,246
def Ts2(self, srcName, reoptimize=False, approx=True, tol=None, MaxIterations=10, verbosity=0): saved_state = LikelihoodState(self) if verbosity > 0: print("*** Start Ts_dl ***") source_attributes = self.getExtraSourceAttributes() self.logLike.syncParams...
Computes the TS value for a source indicated by "srcName." If "reoptimize=True" is selected this function will reoptimize the model up to "MaxIterations" given the tolerance "tol" (default is the tolerance selected for the overall fit). If "appox=True" is selected (the default) it will...
357,247
def _get_result_paths(self, data): result = {} result[] = ResultPath( Path=self.Parameters[].Value, IsWritten=self.Parameters[].isOn()) result[] = ResultPath( Path=self.Parameters[].Value, IsWritten=self.Parameters[].isOn()) re...
Set the result paths
357,248
def search_items(self, mode, request): validate_search_mode(mode) method = getattr(self.dynamodb_client, mode) try: response = method(**request) except botocore.exceptions.ClientError as error: raise BloopException("Unexpected error during {}.".format(mod...
Invoke query/scan by name. Response always includes "Count" and "ScannedCount" :param str mode: "query" or "scan" :param request: Unpacked into :func:`boto3.DynamoDB.Client.query` or :func:`boto3.DynamoDB.Client.scan`
357,249
def plot_job_history(jobs, interval=): def get_date(job): return datetime.datetime.strptime(job.creation_date(), ) current_time = datetime.datetime.now() if interval == : bins = [(current_time - datetime.timedelta(days=k*365/12)) ...
Plots the job history of the user from the given list of jobs. Args: jobs (list): A list of jobs with type IBMQjob. interval (str): Interval over which to examine. Returns: fig: A Matplotlib figure instance.
357,250
def create_database(self, instance, name, character_set=None, collate=None): return instance.create_database(name, character_set=character_set, collate=collate)
Creates a database with the specified name on the given instance.
357,251
def createCommit(self, varBind, **context): name, val = varBind (debug.logger & debug.FLAG_INS and debug.logger( % (self, name, val))) cbFun = context[] instances = context[].setdefault(self.name, {self.ST_CREATE: {}, self.ST_DESTROY: {}}) idx = context[] ...
Create Managed Object Instance. Implements the second of the multi-step workflow similar to the SNMP SET command processing (:RFC:`1905#section-4.2.5`). The goal of the second phase is to actually create requested Managed Object Instance. When multiple Managed Objects Instances are cre...
357,252
def compute_layer(cls, data, params, layout): check_required_aesthetics( cls.REQUIRED_AES, list(data.columns) + list(params.keys()), cls.__name__) data = remove_missing( data, na_rm=params.get(, False), vars=list(cls.REQUI...
Calculate statistics for this layers This is the top-most computation method for the stat. It does not do any computations, but it knows how to verify the data, partition it call the next computation method and merge results. stats should not override this method. Para...
357,253
def freeze(self, tmp_dir): for sfile in self.secrets(): src_file = hard_path(sfile, self.opt.secrets) if not os.path.exists(src_file): raise aomi_excep.IceFile("%s secret not found at %s" % (self, src_file)) d...
Copies a secret into a particular location
357,254
def _handle_module(args): module = _get_module_filename(args.module) if not module: _error("Could not load module or package: %r", args.module) elif isinstance(module, Unparseable): _error("Could not determine module source: %r", args.module) _parse_and_output(module, args)
Handles the -m argument.
357,255
def termset_ancestors(self, terms): ancs = set() for term in terms: ancs = ancs.union(self.ontology.ancestors(term)) return ancs.union(set(terms))
reflexive ancestors Arguments --------- terms - a set or list of class IDs Returns: set of class IDs
357,256
def get_all_synIdx(self): tic = time() synIdx = {} randomstate = np.random.get_state() for cellindex in self.RANK_CELLINDICES: np.random.seed(self.POPULATIONSEED + cellindex) synIdx[cellin...
Auxilliary function to set up class attributes containing synapse locations given as LFPy.Cell compartment indices This function takes no inputs. Parameters ---------- None Returns ------- synIdx : dict `output[cellindex][populationindex][...
357,257
def _to_bfloat16_unbiased(x, noise): x_sign = tf.sign(x) x = x * x_sign + 1e-30 cand1 = tf.to_bfloat16(x) cand1_f = tf.to_float(cand1) cand2 = tf.to_bfloat16( tf.where(tf.greater(x, cand1_f), cand1_f * 1.005, cand1_f * 0.995)) ret = _randomized_roundoff_to_bfloat16(x, noise, cand1, cand...
Convert a float32 to a bfloat16 using randomized roundoff. Args: x: A float32 Tensor. noise: a float32 Tensor with values in [0, 1), broadcastable to tf.shape(x) Returns: A float32 Tensor.
357,258
def full_symbol(self): if self._full_symbol is None: self._full_symbol = self._symbol_extract(cache.RE_FULL_CURSOR, brackets=True) return self._full_symbol
Returns the symbol under the cursor AND additional contextual symbols in the case of %-separated lists of type members.
357,259
def set_config_file(name): s name. This function is intended to be used from states. CLI Example: .. code-block:: bash salt syslog_ng.set_config_file name=/etc/syslog-ng ' global __SYSLOG_NG_CONFIG_FILE old = __SYSLOG_NG_CONFIG_FILE __SYSLOG_NG_CONFIG_FILE = name changes...
Sets the configuration's name. This function is intended to be used from states. CLI Example: .. code-block:: bash salt '*' syslog_ng.set_config_file name=/etc/syslog-ng
357,260
def group_layout(path, files, **kwargs): if len(files) > 0: two_column_layout(path, list(grouper(files, 2)), **kwargs)
Make a well layout in chunks of two from a list of files path: str Location to make the well html file files: list of pycbc.workflow.core.Files This list of images to show in order within the well layout html file. Every two are placed on the same row.
357,261
async def echo_all(app, message): for address in app.kv.get_prefix().values(): host, port = address.decode().split() port = int(port) await tcp_echo_client(message, loop, host, port)
Send and recieve a message from all running echo servers
357,262
def generate_document_vector(self, doc, mode=): if mode == : selected_function = HashedIndex.get_tfidf elif mode == : selected_function = functools.partial(HashedIndex.get_tfidf, normalized=True) elif mode == : selected_function = HashedIndex.get_term...
Returns a representation of the specified document as a feature vector weighted according the mode specified (by default tf-dif). A custom weighting function can also be passed which receives the hashedindex instance, the selected term and document as parameters. The result will be ret...
357,263
def dataset_path(cls, project, dataset): return google.api_core.path_template.expand( "projects/{project}/datasets/{dataset}", project=project, dataset=dataset )
Return a fully-qualified dataset string.
357,264
def height(cls, path): if os.path.exists( path ): sb = os.stat( path ) h = (sb.st_size / BLOCK_HEADER_SIZE) - 1 return h else: return None
Get the locally-stored block height
357,265
def enable_hardware_breakpoint(self, dwThreadId, address): t = self.system.get_thread(dwThreadId) bp = self.get_hardware_breakpoint(dwThreadId, address) if bp.is_running(): self.__del_running_bp_from_all_threads(bp) bp.enable(None, t)
Enables the hardware breakpoint at the given address. @see: L{define_hardware_breakpoint}, L{has_hardware_breakpoint}, L{get_hardware_breakpoint}, L{enable_one_shot_hardware_breakpoint}, L{disable_hardware_breakpoint} L{erase_hardware_brea...
357,266
def _get_new_batch(self, ds_type:DatasetType)->Collection[Tensor]: "Retrieves new batch of DatasetType, and detaches it." return self.learn.data.one_batch(ds_type=ds_type, detach=True, denorm=False, cpu=False)
Retrieves new batch of DatasetType, and detaches it.
357,267
def GetRequestXML(self, method, *args): self.suds_client.set_options(nosend=True) service_request = (getattr(self, method))(*args).envelope self.suds_client.set_options(nosend=False) return lxml.etree.fromstring(service_request)
Get the raw SOAP XML for a request. Args: method: The method name. *args: A list of arguments to be passed to the method. Returns: An element containing the raw XML that would be sent as the request.
357,268
def push(self, move): self.move_number += 1 captured_piece = self.piece_type_at(move.to_square) if move else NONE self.captured_piece_stack.append(captured_piece) self.move_stack.append(move) if not move: self.turn ^= 1 ...
Updates the position with the given move and puts it onto a stack. Null moves just increment the move counters, switch turns and forfeit en passant capturing. No validation is performed. For performance moves are assumed to be at least pseudo legal. Otherwise there is no guarantee that t...
357,269
def dttm_sql_literal(self, dttm, is_epoch_in_utc): tf = self.python_date_format if self.database_expression: return self.database_expression.format(dttm.strftime()) elif tf: if is_epoch_in_utc: seconds_since_epoch = dttm.timestamp() el...
Convert datetime object to a SQL expression string If database_expression is empty, the internal dttm will be parsed as the string with the pattern that the user inputted (python_date_format) If database_expression is not empty, the internal dttm will be parsed as the sql senten...
357,270
def is_hidden(path): hidden = False f = os.path.basename(path) if f[:1] in (, b): hidden = True elif _PLATFORM == : FILE_ATTRIBUTE_HIDDEN = 0x2 if PY35: results = os.lstat(path) hidden = bool(results.st_file_attributes & FILE_ATTRIB...
Check if file is hidden.
357,271
def _to_tree(self, rule_node): orig_rule = self.orig_rules[rule_node.rule.alias] children = [] for child in rule_node.children: if isinstance(child, RuleNode): children.append(self._to_tree(child)) else: assert isinstance(child.nam...
Converts a RuleNode parse tree to a lark Tree.
357,272
def make_executable(path, fatal=True): if is_executable(path): return 0 if is_dryrun(): LOG.debug("Would make %s executable", short(path)) return 1 if not os.path.exists(path): return abort("%s does not exist, cant chmod %s: %s", short(path), e, fatal=(fatal, -1))
:param str|None path: chmod file with 'path' as executable :param bool|None fatal: Abort execution on failure if True :return int: 1 if effectively done, 0 if no-op, -1 on failure
357,273
def write(self, fptr): num_uuids = len(self.ulst) length = 4 + 4 + 2 + num_uuids * 16 write_buffer = struct.pack(, length, b, num_uuids) fptr.write(write_buffer) for j in range(num_uuids): fptr.write(self.ulst[j].bytes)
Write a UUID list box to file.
357,274
def has(self, module_name, class_name, attribute_name): self.read(module_name) return self.parser.has_option(class_name, attribute_name)
Parameters ---------- module_name: String The analysis_path of the module class_name: String The analysis_path of the class attribute_name: String The analysis_path of the attribute Returns ------- has_prior: bool T...
357,275
def findhight(data, ignoret=None, threshold=20): time = np.sort(data[]) ww = np.ones(len(time), dtype=bool) if ignoret: for (t0, t1) in ignoret: ww = ww & np.where( (time < t0) | (time > t1), True, False ) bins = np.round(time[ww]).astype() counts = np.bincount(bins) ...
Find bad time ranges from distribution of candidates. ignoret is list of tuples [(t0, t1), (t2, t3)] defining ranges to ignore. threshold is made above std of candidate distribution in time. Returns the time (in seconds) and counts for bins above threshold.
357,276
def round_optimum(self, x): x = np.array(x) if not ((x.ndim == 1) or (x.ndim == 2 and x.shape[0] == 1)): raise ValueError("Unexpected dimentionality of x. Got {}, expected (1, N) or (N,)".format(x.ndim)) if x.ndim == 2: x = x[0] x_rounded = [] v...
Rounds some value x to a feasible value in the design space. x is expected to be a vector or an array with a single row
357,277
def _translate_timeperiod(self, timeperiod): if self.time_grouping == 1: return timeperiod year, month, day, hour = time_helper.tokenize_timeperiod(timeperiod) if self.time_qualifier == QUALIFIER_HOURLY: ...
method translates given timeperiod to the grouped timeperiod
357,278
def _print(self, msg=None, always=False): if always or not self.commons[].quiet: if msg: print_(msg) else: print_()
A wrapper around print that only prints if we are not running in quiet mode
357,279
def _GetKeys(self, top_level, keys, depth=1): match = {} if not isinstance(top_level, dict): return match keys = set(keys) if depth == 1: for key in keys: match[key] = top_level.get(key, None) else: for _, parsed_key, parsed_value in RecurseKey(top_level...
Helper function to return keys nested in a plist dict. By default this function will return the values for the named keys requested by a plugin in match dictionary object. The default setting is to look a single layer down from the root (same as the check for plugin applicability). This level is suitab...
357,280
def _encodeTimestamp(timestamp): if timestamp.tzinfo == None: raise ValueError() tzDelta = timestamp.utcoffset() if tzDelta.days >= 0: tzValStr = .format(int(tzDelta.seconds / 60 / 15)) else: tzVal = int((tzDelta.days * -3600 * 24 - tzDelta.seconds) / 60 / 15) ...
Encodes a 7-octet timestamp from the specified date Note: the specified timestamp must have a UTC offset set; you can use gsmmodem.util.SimpleOffsetTzInfo for simple cases :param timestamp: The timestamp to encode :type timestamp: datetime.datetime :return: The encoded timestamp :rtyp...
357,281
def get_time(): time_request = + 47 * now = struct.unpack("!12I", ntp_service.request(time_request, timeout=5.0).data.read())[10] return time.ctime(now - EPOCH_START)
Get time from a locally running NTP server
357,282
def release_lock(self, verbose=VERBOSE, raiseError=RAISE_ERROR): if not os.path.isfile(self.__lockPath): released = True code = 0 else: try: with open(self.__lockPath, ) as fd: lock = fd.readlines() except E...
Release the lock when set and close file descriptor if opened. :Parameters: #. verbose (bool): Whether to be verbose about errors when encountered #. raiseError (bool): Whether to raise error exception when encountered :Returns: #. result (boolean): Whether the lock...
357,283
def get_coding_potential_cutoff(ref_gtf, ref_fasta, data): train_gtf, test_gtf = gtf.split_gtf(ref_gtf, sample_size=2000) coding_gtf = gtf.partition_gtf(train_gtf, coding=True) noncoding_gtf = gtf.partition_gtf(train_gtf) noncoding_fasta = gtf.gtf_to_fasta(noncoding_gtf, ref_fasta) cds_fasta = ...
estimate the coding potential cutoff that best classifies coding/noncoding transcripts by splitting the reference annotation into a test and training set and determining the cutoff where the sensitivity and specificity meet
357,284
def getmodule(object): if ismodule(object): return object if isclass(object): return sys.modules.get(object.__module__) try: file = getabsfile(object) except TypeError: return None if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] ...
Return the module an object was defined in, or None if not found.
357,285
def search_and_extract_orfs_matching_protein_database(self, unpack, search_method, maximum_range, thread...
As per aa_db_search() except slightly lower level. Search an input read set (unpack) and then extract the proteins that hit together with their containing nucleotide sequences. Parameters ---------- output_search_file: str path to hmmsearch output table or diamond ba...
357,286
def decompile(input_, file_, output, format_, jar, limit, decompiler): from androguard import session if file_ and input_: print("Can not give --input and positional argument! " "Please use only one of them!", file=sys.stderr) sys.exit(1) if not input_ and not file_: ...
Decompile an APK and create Control Flow Graphs. Example: \b $ androguard resources.arsc
357,287
def functions(self): if self._functions is None: self._functions = FunctionList(self._version, service_sid=self._solution[], ) return self._functions
Access the functions :returns: twilio.rest.serverless.v1.service.function.FunctionList :rtype: twilio.rest.serverless.v1.service.function.FunctionList
357,288
def _scan_soot_block(self, cfg_job, current_func_addr): addr, function_addr, cfg_node, soot_block = self._generate_cfgnode(cfg_job, current_func_addr) cfg_job.apply_function_edges(self, clear=True) if cfg_node is None: return [ ] ...
Generate a list of successors (generating them each as entries) to IRSB. Updates previous CFG nodes with edges. :param CFGJob cfg_job: The CFGJob instance. :param int current_func_addr: Address of the current function :return: a list of successors :rtype: list
357,289
def _GetUsernameFromProfilePath(self, path): while path and path[-1] == : path = path[:-1] if path: _, _, path = path.rpartition() return path
Retrieves the username from a Windows profile path. Trailing path path segment are ignored. Args: path (str): a Windows path with '\\' as path segment separator. Returns: str: basename which is the last path segment.
357,290
def IV(abf,T1,T2,plotToo=True,color=): rangeData=abf.average_data([[T1,T2]]) AV,SD=rangeData[:,0,0],rangeData[:,0,1] Xs=abf.clampValues(T1) if plotToo: new(abf) pylab.margins(.1,.1) annotate(abf) return AV,SD
Given two time points (seconds) return IV data. Optionally plots a fancy graph (with errorbars) Returns [[AV],[SD]] for the given range.
357,291
def _do_main(self, commands): self._reset() self._init_schema_helper() self._run_prerequisites(commands) idl_ = idl.Idl(self.remote, self.schema_helper) seqno = idl_.change_seqno while True: self._idl_wait(idl_, seqno) seqno = idl_.chang...
:type commands: list of VSCtlCommand
357,292
def mesh(self, mesh_size=1, extra_height=0.1, edge=True, attach=True): a, b = self.get_domain() a -= 2*mesh_size b += 2*mesh_size x_mesh = np.arange(a[0], b[0], mesh_size) y_mesh = np.arange(a[1], b[1], mesh_size) x, y = np.meshgrid(x_mesh, y_mesh...
Generates a set of points distributed in a mesh that covers the whole Place and computes their height. Generates a xy mesh with a given mesh_size in the Place.surface's domain and computes the Surface's height for the nodes. This mesh is alligned with the main directions `x` an...
357,293
def add_entry_listener(self, include_value=False, key=None, added_func=None, removed_func=None, clear_all_func=None): if key: key_data = self._to_data(key) request = multi_map_add_entry_listener_to_key_codec.encode_request(name=self.name, key=key_data, ...
Adds an entry listener for this multimap. The listener will be notified for all multimap add/remove/clear-all events. :param include_value: (bool), whether received event should include the value or not (optional). :param key: (object), key for filtering the events (optional). :param ad...
357,294
def get_values(self, config_manager, ignore_mismatches, obj_hook=DotDict): if self.delayed_parser_instantiation: try: app = config_manager._get_option() source = "%s%s" % (app.value.app_name, file_name_extension) self.config_obj = configobj.Co...
Return a nested dictionary representing the values in the ini file. In the case of this ValueSource implementation, both parameters are dummies.
357,295
def arnoldi_res(A, V, H, ip_B=None): N = V.shape[0] invariant = H.shape[0] == H.shape[1] A = get_linearoperator((N, N), A) if invariant: res = A*V - numpy.dot(V, H) else: res = A*V[:, :-1] - numpy.dot(V, H) return norm(res, ip_B=ip_B)
Measure Arnoldi residual. :param A: a linear operator that can be used with scipy's aslinearoperator with ``shape==(N,N)``. :param V: Arnoldi basis matrix with ``shape==(N,n)``. :param H: Hessenberg matrix: either :math:`\\underline{H}_{n-1}` with ``shape==(n,n-1)`` or :math:`H_n` with ``shape=...
357,296
def DEFINE_multichoice(self, name, default, choices, help, constant=False): self.AddOption( type_info.MultiChoice( name=name, default=default, choices=choices, description=help), constant=constant)
Choose multiple options from a list.
357,297
def get_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS): if self.hProcess in (None, win32.INVALID_HANDLE_VALUE): self.open_handle(dwDesiredAccess) else: dwAccess = self.hProcess.dwAccess if (dwAccess | dwDesiredAccess) != dwAccess: se...
Returns a handle to the process with I{at least} the access rights requested. @note: If a handle was previously opened and has the required access rights, it's reused. If not, a new handle is opened with the combination of the old and new access rights. @typ...
357,298
def loop_until_closed(self): if isinstance(self._state, NOT_YET_CONNECTED): self._tell_session_about_disconnect() self._state = DISCONNECTED() else: def closed(): return isinstance(self._state, DISCONNECTED) ...
Execute a blocking loop that runs and executes event callbacks until the connection is closed (e.g. by hitting Ctrl-C). While this method can be used to run Bokeh application code "outside" the Bokeh server, this practice is HIGHLY DISCOURAGED for any real use case.
357,299
def extract_dynamic_part(uri): for part in uri.split(): part = part.strip() if part.startswith() and part.endswith(): return clean_dynamic_uri(part)
Extract dynamic url part from :uri: string. :param uri: URI string that may contain dynamic part.