Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
357,400
def vera_request(self, **kwargs): request_payload = { : , : self.scene_id, } request_payload.update(kwargs) return self.vera_controller.data_request(request_payload)
Perfom a vera_request for this scene.
357,401
def load(self, filename): self.tree = xmltreefromfile(filename) self.parsexml(self.tree.getroot()) if self.mode != Mode.XPATH: self.tree = None
Load a FoLiA XML file. Argument: filename (str): The file to load
357,402
def phase_from_polarizations(h_plus, h_cross, remove_start_phase=True): p = numpy.unwrap(numpy.arctan2(h_cross.data, h_plus.data)).astype( real_same_precision_as(h_plus)) if remove_start_phase: p += -p[0] return TimeSeries(p, delta_t=h_plus.delta_t, epoch=h_plus.start_time, copy...
Return gravitational wave phase Return the gravitation-wave phase from the h_plus and h_cross polarizations of the waveform. The returned phase is always positive and increasing with an initial phase of 0. Parameters ---------- h_plus : TimeSeries An PyCBC TmeSeries vector that contain...
357,403
def refresh(self): logger.debug() self.resize() self._update(self.editor.contentsRect(), 0, force_update_margins=True)
Refreshes the editor panels (resize and update margins).
357,404
def _slice_pad_length(num_items, length, overlap=0): if length <= overlap: raise ValueError() step = length - overlap span = num_items - length residual = span % step if residual: return step - residual else: return 0
Calculate the padding length needed for sliced samples in order not to discard data. Parameters ---------- num_items : int Number of items in dataset before collating. length : int The length of each of the samples. overlap : int, default 0 The extra number of items in curre...
357,405
def get_associated_groups(self, element): return [g for g in self.groups if element in g.members]
Returns a list of groups that an element (reaction, metabolite, gene) is associated with. Parameters ---------- element: `cobra.Reaction`, `cobra.Metabolite`, or `cobra.Gene` Returns ------- list of `cobra.Group` All groups that the provided object i...
357,406
def set_org_processor(request): if getattr(request, "org", None): org = request.org pattern_bg = org.backgrounds.filter(is_active=True, background_type="P") pattern_bg = pattern_bg.order_by("-pk").first() banner_bg = org.backgrounds.filter(is_active=True, background_type="B") ...
Simple context processor that automatically sets 'org' on the context if it is present in the request.
357,407
def choices_label(choices: tuple, value) -> str: for key, label in choices: if key == value: return label return
Iterates (value,label) list and returns label matching the choice :param choices: [(choice1, label1), (choice2, label2), ...] :param value: Value to find :return: label or None
357,408
def resolve_address_location(proc, location): curframe = proc.curframe if location == : filename = Mstack.frame2file(proc.core, curframe, canonic=False) offset = curframe.f_lasti is_address = True return Location(filename, offset, False, None) assert isinstance(locati...
Expand fields in Location namedtuple. If: '.': get fields from stack function/module: get fields from evaluation/introspection location file and line number: use that
357,409
def _classic_get_full_block(grouped_dicoms): data_blocks = [] for index in range(0, len(grouped_dicoms)): logger.info( % (index + 1, len(grouped_dicoms))) data_blocks.append(_classic_timepoint_to_block(grouped_dicoms[index])) size_x = numpy.shape(data_blocks[0])[0] size_y...
Generate a full datablock containing all timepoints
357,410
def get_permission_object(self): if not isinstance(self, BaseCreateView): if hasattr(self, ) and callable(self.get_object): return self.get_object() return None
Override this method to provide the object to check for permission against. By default uses ``self.get_object()`` as provided by ``SingleObjectMixin``. Returns None if there's no ``get_object`` method.
357,411
def preprocess(train_dataset, output_dir, eval_dataset=None, checkpoint=None, cloud=None): with warnings.catch_warnings(): warnings.simplefilter("ignore") job = preprocess_async(train_dataset, output_dir, eval_dataset, checkpoint, cloud) job.wait() print(job.state)
Blocking version of preprocess_async(). The only difference is that it blocks the caller until the job finishes, and it does not have a return value.
357,412
def push_entity(self, entity): if entity.id: print(.format(entity.name)) self.update(entity) else: print(.format(entity.name)) entity = self.register(entity) return entity
Registers or updates an entity and returns the entity_json with an ID
357,413
def find_usage(self): logger.debug("Checking usage for service %s", self.service_name) self.connect() for lim in self.limits.values(): lim._reset_usage() resp = self.conn.get_directory_limits() directory_limits = resp[] self.limits[]._add_current_usag...
Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`.
357,414
def apply_splice(a,splice): "mutate a *and* return it. a as list, splice as diff.Delta." a[splice.a:splice.b]=splice.text return a
mutate a *and* return it. a as list, splice as diff.Delta.
357,415
def get_used_fields(payload): return [ tag for tag, descriptor in payload.CHILD_MAP.items() if descriptor.__get__(payload, type(payload)) is not None ]
Get a list containing the names of the fields that are used in the xso.Query. :param payload: Query object o be :type payload: :class:`~aioxmpp.ibr.Query` :return: :attr:`list`
357,416
def wsgi(self, environ, start_response): try: environ[] = self request.bind(environ) response.bind() out = self._handle(environ) out = self._cast(out, request, response) if response.status in (100, 101, 204, 304) or re...
The bottle WSGI-interface.
357,417
def recwalk(inputpath, sorting=True): else: for dirpath, dirs, files in walk(inputpath): if sorting: files.sort() dirs.sort() for filename in files: yield (dirpath, filename)
Recursively walk through a folder. This provides a mean to flatten out the files restitution (necessary to show a progress bar). This is a generator.
357,418
def subkey(self, path): t = path.split("/") if len(t) == 2: n, for_change = t else: n, = t for_change = 0 b = (str(n) + + str(for_change) + ).encode("utf8") + self.master_public_key() offset = from_bytes_32(double_sha256(b)) i...
path: of the form "K" where K is an integer index, or "K/N" where N is usually a 0 (deposit address) or 1 (change address)
357,419
def create_birthday(min_age=18, max_age=80): age = random.randint(min_age, max_age) start = datetime.date.today() - datetime.timedelta(days=random.randint(0, 365)) return start - datetime.timedelta(days=age * 365)
Create a random birthday fomr someone between the ages of min_age and max_age
357,420
def request_acquisition(self, acquisition_request): content = self._serialize.body(acquisition_request, ) response = self._send(http_method=, location_id=, version=, content=content) return self._d...
RequestAcquisition. [Preview API] :param :class:`<ExtensionAcquisitionRequest> <azure.devops.v5_1.gallery.models.ExtensionAcquisitionRequest>` acquisition_request: :rtype: :class:`<ExtensionAcquisitionRequest> <azure.devops.v5_1.gallery.models.ExtensionAcquisitionRequest>`
357,421
def _init_env(self): from salt.config import minion_config from salt.grains import core as g_core g_core.__opts__ = minion_config(self.DEFAULT_MINION_CONFIG_PATH) self.grains_core = g_core
Initialize some Salt environment.
357,422
def mpsse_set_clock(self, clock_hz, adaptive=False, three_phase=False): self._write() if adaptive: self._write() else: self._write() if three_phase: self._write() else: ...
Set the clock speed of the MPSSE engine. Can be any value from 450hz to 30mhz and will pick that speed or the closest speed below it.
357,423
def from_arrow_type(at): import pyarrow.types as types if types.is_boolean(at): spark_type = BooleanType() elif types.is_int8(at): spark_type = ByteType() elif types.is_int16(at): spark_type = ShortType() elif types.is_int32(at): spark_type = IntegerType() el...
Convert pyarrow type to Spark data type.
357,424
def _var_and_skew(self, catchments, as_rural=False): if not hasattr(catchments, ): l_cv, l_skew = self._l_cv_and_skew(self.catchment) self.results_log[] = [] else: n = len(catchments) l_cvs = np.empty(n) l_skews = np.emp...
Calculate L-CV and L-SKEW from a single catchment or a pooled group of catchments. Methodology source: Science Report SC050050, para. 6.4.1-6.4.2
357,425
def quantile(x, q): x = pd.Series(x) return pd.Series.quantile(x, q)
Calculates the q quantile of x. This is the value of x greater than q% of the ordered values from x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :param q: the quantile to calculate :type q: float :return: the value of this feature :return type: float
357,426
def list_storage_containers(kwargs=None, storage_conn=None, call=None): if call != : raise SaltCloudSystemExit( ) if not storage_conn: storage_conn = get_storage_conn(conn_kwargs=kwargs) data = storage_conn.list_containers() ret = {} for item in data.conta...
.. versionadded:: 2015.8.0 List containers associated with the storage account CLI Example: .. code-block:: bash salt-cloud -f list_storage_containers my-azure
357,427
def get_prtflds_all(self): flds = [] dont_add = set([, , , ]) self._flds_append(flds, self.get_prtflds_default(), dont_add) self._flds_append(flds, vars(self).keys(), dont_add) self._flds_append(flds, vars(se...
When converting to a namedtuple, get all possible fields in their original order.
357,428
def positionAt( self, location, fixedX = None, fixedY = None ): rect = self.sceneRect() if rect.height() < self.minimumHeight(): rect.setHeight(self.minimumHeight()) if rect.width() < self.minimumWidth(): rect.setWidth(self.minimumWi...
Calculates the position at the inputed location. :param location <XConnectionLocation> :param fixedX <float> || None :param fixedY <float> || None :return <QPointF>
357,429
def is_logged_in(username=None): if username: if not isinstance(username, (list, tuple)): username = [username] return in session and get_username() in username return in session
Checks if user is logged in if `username` is passed check if specified user is logged in username can be a list
357,430
def nltk_download(name, ignore_errors=True): r name = re.sub(r"[-\s=+_{}^\[nltk_data\]\s+ErrorUnable to download the requested NLTK dataset: {}\n'.join(msgs))) nltk_download.done[name] = True return nltk_download.done[name]
r"""Like nltk.download, but be quiet about it, and get a room (separate python process) Does some simple whitespace normalization on `name`, but doesn't yet do fuzzy matching Caches the normalized names of packages already attempted, so they aren't re-tried >>> nltk_download('nonexistent dataset name', ig...
357,431
def replace_namespaced_cron_job_status(self, name, namespace, body, **kwargs): kwargs[] = True if kwargs.get(): return self.replace_namespaced_cron_job_status_with_http_info(name, namespace, body, **kwargs) else: (data) = self.replace_namespaced_cron_job_stat...
replace_namespaced_cron_job_status # noqa: E501 replace status of the specified CronJob # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_namespaced_cron_job_status(name, name...
357,432
def _sort_dd_skips(configs, dd_indices_all): config_current_skips = np.abs(configs[:, 1] - configs[:, 0]) if np.all(np.isnan(config_current_skips)): return {0: []} available_skips_raw = np.unique(config_current_skips) available_skips = available_skips_raw[ ~np.isnan(available_...
Given a set of dipole-dipole configurations, sort them according to their current skip. Parameters ---------- configs: Nx4 numpy.ndarray Dipole-Dipole configurations Returns ------- dd_configs_sorted: dict dictionary with the skip as keys, and arrays/lists with indices to ...
357,433
def parse_field(fld, selectable, aggregated=True, default_aggregation=): aggregation_lookup = { : func.sum, : func.min, : func.max, : func.avg, : func.count, : lambda fld: func.count(distinct(fld)), : lambda fld: func.date_trunc(, fld), ...
Parse a field object from yaml into a sqlalchemy expression
357,434
def initial_distribution_samples(self): r res = np.empty((self.nsamples, self.nstates), dtype=config.dtype) for i in range(self.nsamples): res[i, :] = self._sampled_hmms[i].stationary_distribution return res
r""" Samples of the initial distribution
357,435
def _no_trailing_whitespace(relative_path, contents, linter_options): r del relative_path del linter_options trailing_whitespace = re.compile(r"(?<![ \t\r\n])[ \t]+$") for index, line in enumerate(contents): for space in trailing_whitespace.finditer(line): assert space.end() ==...
r"""Check that every file ends with a single \n.
357,436
def merge_vertices(mesh, digits=None, textured=True, uv_digits=4): if not isinstance(digits, int): digits = util.decimal_to_digits(tol.merge) if (textured and mesh.visual.defined and mesh.visual.kind == and ...
Removes duplicate vertices based on integer hashes of each row. Parameters ------------- mesh : Trimesh object Mesh to merge vertices on digits : int How many digits to consider for vertices If not specified uses tol.merge textured : bool If True, for textured meshes onl...
357,437
def diff(ctx, files, metrics, all, detail): config = ctx.obj["CONFIG"] if not exists(config): handle_no_cache(ctx) if not metrics: metrics = get_default_metrics(config) logger.info(f"Using default metrics {metrics}") else: metrics = metrics.split(",") logge...
Show the differences in metrics for each file.
357,438
def add_simmanager_api(self, mock): iface = mock.AddProperties(iface, { : _parameters.get(, False), : _parameters.get(, new_iccid(self)), : _parameters.get(, False), : _parameters.get(, dbus.Array([], signature=)), : _parameters.get(, ), : _parameters.get(,...
Add org.ofono.SimManager API to a mock
357,439
def memoized_property(func=None, key_factory=per_instance, **kwargs): getter = memoized_method(func=func, key_factory=key_factory, **kwargs) return property(fget=getter, fdel=lambda self: getter.forget(self))
A convenience wrapper for memoizing properties. Applied like so: >>> class Foo(object): ... @memoized_property ... def name(self): ... pass Is equivalent to: >>> class Foo(object): ... @property ... @memoized_method ... def name(self): ... pass Which is equivalent to: >...
357,440
def neuron_postproc(traj, result_list):
Postprocessing, sorts computed firing rates into a table :param traj: Container for results and parameters :param result_list: List of tuples, where first entry is the run index and second is the actual result of the corresponding run. :return:
357,441
def timeCall(*funcAndArgs, **kwargs): r func, args = funcAndArgs[0], funcAndArgs[1:] start = time.time() func(*args, **kwargs) return time.time() - start
r"""Return the time (in ms) it takes to call a function (the first argument) with the remaining arguments and `kwargs`. Examples: To find out how long ``func('foo', spam=1)`` takes to execute, do: ``timeCall(func, foo, spam=1)``
357,442
def append_tz_time_only_parts(self, tag, h, m, s=None, ms=None, us=None, offset=0, header=False): ih = int(h) if ih < 0 or ih > 23: raise ValueError("Hour value `h` (%u) out of range " "0 to 23" % ih) im = int(...
Append a field with a TZTimeOnly value from components. :param tag: Integer or string FIX tag number. :param h: Hours, in range 0 to 23. :param m: Minutes, in range 0 to 59. :param s: Optional seconds, in range 0 to 59 (60 for leap second). :param ms: Optional milliseconds, in r...
357,443
def fetch(task_id, wait=0, cached=Conf.CACHED): if cached: return fetch_cached(task_id, wait) start = time() while True: t = Task.get_task(task_id) if t: return t if (time() - start) * 1000 >= wait >= 0: break sleep(0.01)
Return the processed task. :param task_id: the task name or uuid :type task_id: str or uuid :param wait: the number of milliseconds to wait for a result :type wait: int :param bool cached: run this against the cache backend :return: the full task object :rtype: Task
357,444
def is_youtube_subtitle_file_supported_language(language): language_obj = _get_language_with_alpha2_fallback(language) if language_obj is None: config.LOGGER.warning("Found unsupported language code {}".format(language)) return False else: return True
Check if the language code `language` (string) is a valid language code in the internal language id format `{primary_code}` or `{primary_code}-{subcode}` ot alternatively if it s YouTube language code that can be mapped to one of the languages in the internal represention.
357,445
def forwards(self, orm): "Write your forwards methods here." orm.Project.objects.update(label=F()) orm.Cohort.objects.update(label=F()) orm.Sample.objects.update(name=F())
Write your forwards methods here.
357,446
def geno(self, y, from_bounds=None, copy_if_changed=True, copy_always=False, repair=None, archive=None): if from_bounds is None: from_bounds = lambda x, copy=False: x if archive is not None: try: x = archive[y][] e...
maps the phenotypic input argument into the genotypic space, that is, computes essentially the inverse of ``pheno``. By default a copy is made only to prevent to modify ``y``. The inverse of the user-defined transformation (if any) is only needed if external solutions are injected, it ...
357,447
def request_args(self): kwargs = {} kwargs.update(self.request.match_info.items()) kwargs.update(self.request.query.items()) return kwargs
Returns the arguments passed with the request in a dictionary. Returns both URL resolved arguments and query string arguments.
357,448
def show_system_monitor_output_switch_status_report_time(self, **kwargs): config = ET.Element("config") show_system_monitor = ET.Element("show_system_monitor") config = show_system_monitor output = ET.SubElement(show_system_monitor, "output") switch_status = ET.SubElemen...
Auto Generated Code
357,449
def set_thread_params( self, enable=None, count=None, count_offload=None, stack_size=None, no_wait=None): self._set(, enable, cast=bool) self._set(, no_wait, cast=bool) self._set(, count) self._set(, count_offload) if count: self._section.print_o...
Sets threads related params. :param bool enable: Enable threads in the embedded languages. This will allow to spawn threads in your app. .. warning:: Threads will simply *not work* if this option is not enabled. There will likely be no error, just no execution of your t...
357,450
def main(): logging.basicConfig(format=LOGGING_FORMAT) log = logging.getLogger(__name__) parser = argparse.ArgumentParser(description=main.__doc__) add_debug(parser) add_app(parser) add_env(parser) add_properties(parser) add_region(parser) args = parser.parse_args() loggin...
Create Lambda events.
357,451
def offset(self, index=0): eta = self._geometry[self.camera][index]["ra"] xi = self._geometry[self.camera][index]["dec"] ra = self.origin.ra - (eta/math.cos(self.dec.radian))*units.degree dec = self.origin.dec - xi * units.degree + 45 * units.arcsec self._coordinate = Sk...
Offset the camera pointing to be centred on a particular CCD.
357,452
def _proxy(self): if self._context is None: self._context = ParticipantContext( self._version, account_sid=self._solution[], conference_sid=self._solution[], call_sid=self._solution[], ) return self._context
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ParticipantContext for this ParticipantInstance :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext
357,453
def optimize_lambda(self, validation): maxm = 0 minr = len(validation) for n in range(validation.shape[1]): m = np.nanargmin(validation[:, n]) if m > maxm: maxm = m r = np.where(...
Returns the index of :py:attr:`self.lambda_arr` that minimizes the validation scatter in the segment with minimum at the lowest value of :py:obj:`lambda`, with fractional tolerance :py:attr:`self.leps`. :param numpy.ndarray validation: The scatter in the validation set \ ...
357,454
def lookup(self, keys, read_consistency=None, transaction=None): conn = self.get_conn() body = {: keys} if read_consistency: body[] = read_consistency if transaction: body[] = transaction resp = (conn .projects() ....
Lookup some entities by key. .. seealso:: https://cloud.google.com/datastore/docs/reference/rest/v1/projects/lookup :param keys: the keys to lookup. :type keys: list :param read_consistency: the read consistency to use. default, strong or eventual. ...
357,455
def adjust_obscov_resfile(self, resfile=None): self.pst.adjust_weights_resfile(resfile) self.__obscov.from_observation_data(self.pst)
reset the elements of obscov by scaling the implied weights based on the phi components in res_file so that the total phi is equal to the number of non-zero weights. Parameters ---------- resfile : str residual file to use. If None, residual file with case name is ...
357,456
def glyph(dataset, orient=True, scale=True, factor=1.0, geom=None): if geom is None: arrow = vtk.vtkArrowSource() arrow.Update() geom = arrow.GetOutput() alg = vtk.vtkGlyph3D() alg.SetSourceData(geom) if isinstance(scale, str): dat...
Copies a geometric representation (called a glyph) to every point in the input dataset. The glyph may be oriented along the input vectors, and it may be scaled according to scalar data or vector magnitude. Parameters ---------- orient : bool Use the active v...
357,457
def input(self): lst = [s.aesthetics for s in self] return list(itertools.chain(*lst))
Return a list of all the aesthetics covered by the scales.
357,458
def run(self): fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), ), ) fpy = open(os.path.join(self.out_path, ), , encoding=) fpy.write() fpy.write() fpy.write() py_str = py_str_idx = 0 py_str_format = for no, line in enumerate(f...
主函数
357,459
def close(self, reply_code=200, reply_text=): if not compatibility.is_integer(reply_code): raise AMQPInvalidArgument() elif not compatibility.is_string(reply_text): raise AMQPInvalidArgument() try: if self._connection.is_closed or self.is_closed: ...
Close Channel. :param int reply_code: Close reply code (e.g. 200) :param str reply_text: Close reply text :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection ...
357,460
def res(self): params = [dict(zip(self.keys, p)) for p in self.params] return [ {"target": target, "params": param} for target, param in zip(self.target, params) ]
Get all target values found and corresponding parametes.
357,461
def all_entities(self, is_active=True): return self.get_all_entities(return_models=True, is_active=is_active)
Return all the entities in the group. Because groups can contain both individual entities, as well as whole groups of entities, this method acts as a convenient way to get a queryset of all the entities in the group.
357,462
def __replace_coord_variables(text, x_and_y, req_len, idx): return ResourceConfig.__replace_base_variables(text, req_len, idx) \ .replace("{xy}", str(x_and_y)) \ .replace("{pi}", str(math.pi))
Replace x and y with their coordinates and replace pi with value of pi. :param text: text: base text to modify :param x_and_y: location x and y :param req_len: amount of required resources :param idx: index of resource we are working on :return: str
357,463
def validate(self, format, args): fmtMap = { : , : , : } fmts = format.split() if len(fmts) != len(args): raise InvalidArgument() for i, fmt in enumerate(fmts): valid = False for f in fmt.split(): if f == and args[i] + in CommandHandler.__dict__: ...
Validate input parameters with given format. This function also checks for wildcards for recursive mode.
357,464
def run(data, samples, noreverse, maxindels, force, ipyclient): subsamples = [] for sample in samples: try: log_level = logging.getLevelName(LOGGER.getEffectiveLevel()) if not log_level == "DEBUG": if os.path.exists(data....
run the major functions for clustering within samples
357,465
def center_str(txt, font_name, font_size, offset=0): return -(text_width(txt, font_name, font_size) / 2.0) + offset
Center a string on the x axis of a reportslab canvas
357,466
def job_factory(self): jobs = dict() for section, options in self.config.items(): if section == : continue plugin_name = options[] job_kls = self.plugins[plugin_name] if hasattr(job_kls, ...
Create concrete jobs. The concrete jobs is following dictionary. jobs = { 'PLUGINNAME-build_items': { 'method': FUNCTION_OBJECT, 'interval': INTERVAL_TIME , } ... } If ConcreteJob instance has "build_discovery_items", "b...
357,467
def register_comm_target(kernel=None): if kernel is None: kernel = get_ipython().kernel kernel.comm_manager.register_target(, Widget.handle_comm_opened)
Register the jupyter.widget comm target
357,468
def _steal_content(self, other_page): other_doc = other_page.doc other_doc_pages = other_doc.pages[:] other_doc_nb_pages = other_doc.nb_pages other_page_nb = other_page.page_nb to_move = [ (other_page.__get_box_path(), self.__get_box_path()), (ot...
Call ImgDoc.steal_page() instead
357,469
def read_tf_records(batch_size, tf_records, num_repeats=1, shuffle_records=True, shuffle_examples=True, shuffle_buffer_size=None, interleave=True, filter_amount=1.0): if shuffle_examples and not shuffle_buffer_size: raise ValueError("Must set ...
Args: batch_size: batch size to return tf_records: a list of tf_record filenames num_repeats: how many times the data should be read (default: One) shuffle_records: whether to shuffle the order of files read shuffle_examples: whether to shuffle the tf.Examples shuffle_buf...
357,470
def amazon_s3(self, scene, bands): sat = self.scene_interpreter(scene) if not in bands: bands.append() if not in bands: bands.append() urls = [] for band in bands: url = self.amazon_s3_url(sat, band) ...
Amazon S3 downloader
357,471
def poll(poll, msg, server): poll = remove_smart_quotes(poll.replace(u"\u2014", u"--")) try: args = ARGPARSE.parse_args(shlex.split(poll)).poll except ValueError: return ERROR_INVALID_FORMAT if not 2 < len(args) < len(POLL_EMOJIS) + 1: return ERROR_WRONG_NUMBER_OF_ARGUMENT...
Given a question and answers, present a poll
357,472
def rpcexec(self, payload): try: response = requests.post( "http://{}:{}/rpc".format(self.host, self.port), data=json.dumps(payload, ensure_ascii=False).encode("utf8"), headers=self.headers, auth=(self.username, self.password),...
Manual execute a command on API (internally used) param str payload: The payload containing the request return: Servers answer to the query rtype: json raises RPCConnection: if no connction can be made raises UnauthorizedError: if the user is not authorized ...
357,473
def add_event_subscriber(self, name, ws): if name in self.available_events: self.available_events[name][].add(ws)
Add a new websocket subscriber to an event. name -- name of the event ws -- the websocket
357,474
def score(self, testing_features, testing_labels): yhat = self.predict(testing_features) return self.scoring_function(testing_labels,yhat)
estimates accuracy on testing set
357,475
def heuristic_crossover(random, candidates, args): crossover_rate = args.setdefault(, 1.0) bounder = args[].bounder if len(candidates) % 2 == 1: candidates = candidates[:-1] lookup = dict(zip([pickle.dumps(p.candidate, 1) for p in population], population)) mo...
Return the offspring of heuristic crossover on the candidates. It performs heuristic crossover (HX), which is similar to the update rule used in particle swarm optimization. This function also makes use of the bounder function as specified in the EC's ``evolve`` method. .. note:: Th...
357,476
def release(self, sim_size): requested = self._conc_alloc_size(sim_size) used = self.heap_location - self.heap_base released = requested if requested <= used else used self.heap_location -= released l.debug("Releasing %d bytes from the heap (%d bytes were requested to be...
The memory release primitive for this heap implementation. Decreases the position of the break to deallocate space. Guards against releasing beyond the initial heap base. :param sim_size: a size specifying how much to decrease the break pointer by (may be symbolic or not)
357,477
def find_group_consistencies(groups1, groups2): r group1_list = {tuple(sorted(_group)) for _group in groups1} group2_list = {tuple(sorted(_group)) for _group in groups2} common_groups = list(group1_list.intersection(group2_list)) return common_groups
r""" Returns a measure of group consistency Example: >>> # ENABLE_DOCTEST >>> from utool.util_alg import * # NOQA >>> groups1 = [[1, 2, 3], [4], [5, 6]] >>> groups2 = [[1, 2], [4], [5, 6]] >>> common_groups = find_group_consistencies(groups1, groups2) >>> result...
357,478
def clear_source(self): if (self.get_source_metadata().is_read_only() or self.get_source_metadata().is_required()): raise errors.NoAccess() self._my_map[] = self._source_default
Removes the source. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
357,479
def setAndDrawInspectorById(self, identifier): self.setInspectorById(identifier) regItem = self.inspectorRegItem if regItem and not regItem.successfullyImported: msg = "Unable to import {} inspector.\n{}".format(regItem.identifier, regItem.exception) Qt...
Sets the inspector and draw the contents. Does NOT trigger any actions, so the check marks in the menus are not updated. To achieve this, the user must update the actions by hand (or call getInspectorActionById(identifier).trigger() instead).
357,480
def _transform(self, data, transform, step_size): if callable(transform): data = transform(data, step_size) return data
Transform the data. If the transform is not supported by this series, returns the data unaltered.
357,481
def _read_var_data(self): var_bundles = OrderedDict() var_attrs = OrderedDict() n_vars = 0 while self.fp.tell() < self.fsize: var_attr = OrderedDict() line = self.fp.readline() modelname, res0, res1, halfpolar, center180 = li...
Iterate over the block of this bpch file and return handlers in the form of `BPCHDataBundle`s for access to the data contained therein.
357,482
def toarray(self): if self.mode == : return self.values.unchunk().toarray() if self.mode == : return self.values.unchunk()
Convert blocks to local ndarray
357,483
def extend(self, records): if self.settings.read_only: Log.error("Index opened in read only mode, no changes allowed") lines = [] try: for r in records: if in r or not in r: Log.error() id, version, json_byt...
records - MUST HAVE FORM OF [{"value":value}, ... {"value":value}] OR [{"json":json}, ... {"json":json}] OPTIONAL "id" PROPERTY IS ALSO ACCEPTED
357,484
def connect(url=, token=None): gh_session = None if url == : gh_session = create_session(token) else: gh_session = create_enterprise_session(url, token) if gh_session is None: msg = raise RuntimeError(msg, url) logger.info(, url) return gh_session
Create a GitHub session for making requests
357,485
def is_safe_to_wait( lock_expiration: BlockExpiration, reveal_timeout: BlockTimeout, block_number: BlockNumber, ) -> SuccessOrError: assert block_number > 0 assert reveal_timeout > 0 assert lock_expiration > reveal_timeout lock_timeout = lock_expiration - block_nu...
True if waiting is safe, i.e. there are more than enough blocks to safely unlock on chain.
357,486
def loadtxt_asdict(fn, **kwargs): kwargs.update(unpack=True) d = loadtxt(fn, **kwargs) if len(np.shape(d)) == 2: keys = kwargs.get(, None) or range(len(d)) D = dict([(k, v) for k, v in zip(keys, d)]) elif len(np.shape(d)) == 1: keys = kwargs.get(, None) or [0] D = d...
Return what is returned from loadtxt as a dict. The 'unpack' keyword is enforced to True. The keys in the dict is the column numbers loaded. It is the integers 0...N-1 for N loaded columns, or the numbers in usecols.
357,487
def _patch_path(path): r if path.startswith(): return path abs_path = os.path.abspath(path) if not abs_path[1] == :
r""" Paths have a max length of api.MAX_PATH characters (260). If a target path is longer than that, it needs to be made absolute and prepended with \\?\ in order to work with API calls. See http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx for details.
357,488
def load(self, config): password_dict = {} if config is None: logger.warning("No configuration file available. Cannot load password list.") elif not config.has_section(self._section): logger.warning("No [%s] section in the configuration file. Cannot load passwor...
Load the password from the configuration file.
357,489
def handle(self, *args, **options): quickstart = Quickstart() try: quickstart.create_app(os.path.join(settings.BASE_DIR, ), options.get()) self.stdout.write( self.style.SUCCESS("Successfully created app ({name}), donapps.{name}name') )) ...
Create new app
357,490
def _update_config_location(self,directory,files=None): if not self._connectToFlickr(): print("%s - CouldnNo location information foundSetting location information : %st find lat/lon for %s"%(location)) return False logger.debug(%(results[0])) _lat,_lon...
Loads location and applies to all files in given files list (or if none, all files in flickr DB) google reverse GEO to figure out location lat/long file can contain things like: Australia Sydney, Australia Holcomb Campground, California. If image already has Lat...
357,491
def get(cls, channel, start, end, pad=None, scaled=None, dtype=None, verbose=False, allow_tape=None, **kwargs): return cls.DictClass.get( [channel], start, end, pad=pad, scaled=scaled, dtype=dtype, verbose=verbose, allow_tape=allow_tape, **kwargs)[str(channel)]
Get data for this channel from frames or NDS This method dynamically accesses either frames on disk, or a remote NDS2 server to find and return data for the given interval Parameters ---------- channel : `str`, `~gwpy.detector.Channel` the name of the channel to rea...
357,492
def add(self, *widgets): for w in widgets: if is_widget(w): if w not in self.widgets: self.widgets.add(w) w.add_internal(self) elif is_container(w): if w not in self.containers: self.cont...
Place @widgets under the blitting hand of the Container(). Each arg must be a Widget(), a fellow Container(), or an iterable. Else, things get ugly...
357,493
def is_iframe(self, el): return ((el.name if self.is_xml_tree(el) else util.lower(el.name)) == ) and self.is_html_tag(el)
Check if element is an `iframe`.
357,494
def filter(self, callback=None): if callback: return self.__class__(list(filter(callback, self.items))) return self.__class__(list(filter(None, self.items)))
Run a filter over each of the items. :param callback: The filter callback :type callback: callable or None :rtype: Collection
357,495
def get_ports_count(context, filters=None): LOG.info("get_ports_count for tenant %s filters %s" % (context.tenant_id, filters)) return db_api.port_count_all(context, join_security_groups=True, **filters)
Return the number of ports. The result depends on the identity of the user making the request (as indicated by the context) as well as any filters. : param context: neutron api request context : param filters: a dictionary with keys that are valid keys for a port as listed in the RESOURCE_ATTRI...
357,496
def _discover_meta_cols(self, **kwargs): cols = set([]) for arg, value in kwargs.items(): if isstr(value) and value in self.meta.columns: cols.add(value) return list(cols)
Return the subset of `kwargs` values (not keys!) matching a `meta` column name
357,497
def validate(self, value): if isinstance(value, (str, unicode)) and not re.match(self.__pattern, value): raise orb.errors.ColumnValidationError(self, ) else: return super(EmailColumn, self).validate(value)
Validates the value provided is a valid email address, at least, on paper. :param value: <str> :return: <bool>
357,498
def ingest_from_blob(self, blob_descriptor, ingestion_properties): queues = self._resource_manager.get_ingestion_queues() queue_details = random.choice(queues) storage_client = CloudStorageAccount(queue_details.storage_account_name, sas_token=queue_details.sas) queue_service = ...
Enqueuing an ingest command from azure blobs. :param azure.kusto.ingest.BlobDescriptor blob_descriptor: An object that contains a description of the blob to be ingested. :param azure.kusto.ingest.IngestionProperties ingestion_properties: Ingestion properties.
357,499
def p_OperationRest(p): p[0] = model.Operation(return_type=p[1], name=p[2], arguments=p[4])
OperationRest : ReturnType OptionalIdentifier "(" ArgumentList ")" ";"