Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
353,400
def popitem(self): try: item = dict.popitem(self) return (item[0], item[1][0]) except KeyError, e: raise BadRequestKeyError(str(e))
Pop an item from the dict.
353,401
async def _gen_result_handler(self, response: Dict[str, Any]): code = response.get("CODE") res = response.get("MESSAGE") ID = res.get("ID") if code in (201, 301): ait = self._wrap_gen(ID) self.tasks.get(ID).set_result(ait) self._gens_queue[ID]...
流式结果响应处理. + 收到状态码标识201或301的响应后,将tasks中ID对应的Future对象的结果设置为一个用于包装的异步生成器. 并为这个ID创建一个异步队列保存在`_gens_queue[ID]`中用于存取结果 + 收到状态码标识为202的响应后向对应ID的存取队列中存入一条结果. + 收到终止状态码206后向对应ID的异步生成器结果获取队列中存入一个`StopAsyncIteration`对象用于终止异步迭代器 Parameters: (response): - 响应的python字典形式数据 ...
353,402
def getuser(): is_windows = platform.system() == "Windows" no_username_in_env = os.environ.get("USERNAME") is None return cross_platform_getuser(is_windows, no_username_in_env)
Return the username.
353,403
def flush(self): items = [] for data in self._to_put: items.append(encode_put(self.connection.dynamizer, data)) for data in self._to_delete: items.append(encode_delete(self.connection.dynamizer, data)) self._write(items) self._to_put = [] ...
Flush pending items to Dynamo
353,404
def DSP_capture_add_samples_stereo(self,new_data_left,new_data_right): self.capture_sample_count = self.capture_sample_count + len(new_data_left) + len(new_data_right) if self.Tcapture > 0: self.data_capture_left = np.hstack((self.data_capture_left,new_data_left)) s...
Append new samples to the data_capture_left array and the data_capture_right array and increment the sample counter. If length reaches Tcapture, then the newest samples will be kept. If Tcapture = 0 then new values are not appended to the data_capture array.
353,405
def _get_sync(self, url): response = self.session.get(url) if response.status_code == requests.codes.ok: return response.json() else: raise HTTPError
Internal method used for GET requests Args: url (str): URL to fetch Returns: Individual URL request's response Raises: HTTPError: If HTTP request failed.
353,406
def bninception(num_classes=1000, pretrained=): r model = BNInception(num_classes=num_classes) if pretrained is not None: settings = pretrained_settings[][pretrained] assert num_classes == settings[], \ "num_classes should be {}, but is {}".format(settings[], num_classes) ...
r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper.
353,407
def serialize_object(self, attr, **kwargs): if attr is None: return None if isinstance(attr, ET.Element): return attr obj_type = type(attr) if obj_type in self.basic_types: return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs...
Serialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be cast to str. :param dict attr: Object to be serialized. :rtype: dict or str
353,408
def _maximization(self, X): for i in range(self.k): resp = np.expand_dims(self.responsibility[:, i], axis=1) mean = (resp * X).sum(axis=0) / resp.sum() covariance = (X - mean).T.dot((X - mean) * resp) / resp.sum() self.parameters[i]["mean"], sel...
Update the parameters and priors
353,409
def launch(self, args, ctx, grid_dims, block_dims, shared_mem=0): assert ctx.device_type == , "Cuda kernel can only be launched on GPU" assert len(grid_dims) == 3, "grid_dims must be a tuple of 3 integers" assert len(block_dims) == 3, "grid_dims must be a tuple of 3 integers" as...
Launch cuda kernel. Parameters ---------- args : tuple of NDArray or numbers List of arguments for kernel. NDArrays are expected for pointer types (e.g. `float*`, `double*`) while numbers are expected for non-pointer types (e.g. `int`, `float`). ctx :...
353,410
def ColorfullyWriteLine(log: str, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: Logger.ColorfullyWrite(log + , consoleColor, writeToFile, printToStdout, logFile)
log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyWriteLine('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames.
353,411
def _log_in_sent_log(self, block): self._sent_log_file.write("\n") sent_file_info = block.latest_file_info self._sent_log_file.write("|".join((sent_file_info.basename, sent_file_info.sha1))) if hasattr(block, ): self._sent_log_file.write("|") sel...
Logs: block file | bfile (not encrypted) sha1 [| bfile encryption key | encrypted bfile sha1] <tab>content file | cfile sha1 | part of parts [| whole file sha1]
353,412
def chr_rom(self): try: return self.raw_data[self.chr_rom_start:self.chr_rom_stop] except IndexError: raise ValueError()
Return the CHR ROM of the ROM file.
353,413
def parse_single_computer(entry): computer = Computer(dns_hostname=get_field(entry, ), description=get_field( entry, ), os=get_field(entry, ), group_id=get_field(entry, )) try: ip = str(ipaddress.ip_address(get_field(entry, ))) except ValueError: ip = if ip: comput...
Parse the entry into a computer object.
353,414
def plot_run_nlive(method_names, run_dict, **kwargs): logx_given_logl = kwargs.pop(, None) logl_given_logx = kwargs.pop(, None) logx_min = kwargs.pop(, None) ymax = kwargs.pop(, None) npoints = kwargs.pop(, 100) figsize = kwargs.pop(, (6.4, 2)) post_mass_norm = kwargs.pop(, None) cu...
Plot the allocations of live points as a function of logX for the input sets of nested sampling runs of the type used in the dynamic nested sampling paper (Higson et al. 2019). Plots also include analytically calculated distributions of relative posterior mass and relative posterior mass remaining. ...
353,415
def init_pkg(pkg, repo_dest): vars = {: pkg} with dir_path(repo_dest): patch( % vars) git([, , pkg]) git([, , , % pkg])
Initializes a custom named package module. This works by replacing all instances of 'project' with a custom module name.
353,416
def minimum_image( self, r1, r2 ): delta_r = r2 - r1 delta_r = np.array( [ x - math.copysign( 1.0, x ) if abs(x) > 0.5 else x for x in delta_r ] ) return( delta_r )
Find the minimum image vector from point r1 to point r2. Args: r1 (np.array): fractional coordinates of point r1. r2 (np.array): fractional coordinates of point r2. Returns: (np.array): the fractional coordinate vector from r1 to the nearest image of r2.
353,417
def read_acls(self): group = self[self.sampler_group][] return {param: group[param].value for param in group.keys()}
Reads the acls of all the parameters. Returns ------- dict A dictionary of the ACLs, keyed by the parameter name.
353,418
def col(self): class ColumnList(object): pass data = ColumnList() for name in self.get_column_names(): expression = getattr(self, name, None) if not isinstance(expression, Expression): expression = Expression(self, name) se...
Gives direct access to the columns only (useful for tab completion). Convenient when working with ipython in combination with small DataFrames, since this gives tab-completion. Columns can be accesed by there names, which are attributes. The attribues are currently expressions, so you can do c...
353,419
def wasSolvedBy(self, user): thisExercise = _Solution.what == self byThisUser = _Solution.who == user condition = q.AND(thisExercise, byThisUser) return self.store.query(_Solution, condition, limit=1).count() == 1
Checks if this exercise has previously been solved by the user.
353,420
def wallet_balance_total(self, wallet): wallet = self._process_value(wallet, ) payload = {"wallet": wallet} resp = self.call(, payload) for k, v in resp.items(): resp[k] = int(v) return resp
Returns the sum of all accounts balances in **wallet** :param wallet: Wallet to return sum of balances for :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_balance_total( ... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D81789F3F"...
353,421
def apt_install(packages, options=None, fatal=False): if options is None: options = [] cmd = [, ] cmd.extend(options) cmd.append() if isinstance(packages, six.string_types): cmd.append(packages) else: cmd.extend(packages) log("Installing {} with options: {}".for...
Install one or more packages.
353,422
def gries_misra(n): primes = [] factor = [0] * n for x in range(2, n): if not factor[x]: factor[x] = x primes.append(x) for p in primes: if p > factor[x] or p * x >= n: break factor[p * x] = p return pri...
Prime numbers by the sieve of Gries-Misra Computes both the list of all prime numbers less than n, and a table mapping every integer 2 ≤ x < n to its smallest prime factor :param n: positive integer :returns: list of prime numbers, and list of prime factors :complexity: O(n)
353,423
def remove_prefix(self, auth, spec, recursive = False): self._logger.debug("remove_prefix called; spec: %s" % unicode(spec)) if in spec: p = self.list_prefix(auth, spec)[0] del spec[] spec[] = p[] spec[] = p[] elif...
Remove prefix matching `spec`. * `auth` [BaseAuth] AAA options. * `spec` [prefix_spec] Specifies prefixe to remove. * `recursive` [bool] When set to True, also remove child prefixes. This is the documentation of the intern...
353,424
def _clone_post_init(self, obj=None, **kwargs): if obj is None or obj is self: for attr, value in Plottable.EXTRA_ATTRS.items(): setattr(self, attr, value) else: for attr, value in Plottable.EXTRA_ATTRS....
obj must be another Plottable instance. obj is used by Clone to properly transfer all attributes onto this object.
353,425
def print(self, indent=2): status = { ResultCode.NOT_IMPLEMENTED: .format( Fore.YELLOW, Style.RESET_ALL), ResultCode.IGNORED: .format( Fore.YELLOW, Style.RESET_ALL), ResultCode.FAILED: .format( Fore.RED, Style.RESET_ALL...
Print self with optional indent.
353,426
def __plain_bfs(adj, source): seen = set() nextlevel = {source} while nextlevel: thislevel = nextlevel nextlevel = set() for v in thislevel: if v not in seen: yield v seen.add(v) ...
modified NX fast BFS node generator
353,427
def getJsonFromApi(view, request): jsonText = view(request) jsonText = json.loads(jsonText.content.decode()) return jsonText
Return json from querying Web Api Args: view: django view function. request: http request object got from django. Returns: json format dictionary
353,428
def get_tasks(self): self.owner.sync() return [t for t in self.owner.tasks.values() if t.project_id == self.id]
Return all tasks in this project. :return: A list of all tasks in this project.class :rtype: list of :class:`pytodoist.todoist.Task` >>> from pytodoist import todoist >>> user = todoist.login('john.doe@gmail.com', 'password') >>> project = user.get_project('PyTodoist') ...
353,429
def request_withdrawal(self, amount: Number, address: str, subtract_fee: bool=False, **params) -> Withdrawal: self.log.debug(f) amount = self._parse_money(amount) if self.dry_run: withdrawal = Withdrawal.create_default(TxType.WITHDRAWAL, self.currency, amount, address) ...
Request a withdrawal.
353,430
def with_path(self, path): new_command = copy.deepcopy(self) new_command._paths.append(str(path)) return new_command
Return new Command object that will be run with a new addition to the PATH environment variable that will be fed to the command.
353,431
def load(fnames, tag=None, sat_id=None, obs_long=0., obs_lat=0., obs_alt=0., TLE1=None, TLE2=None): import sgp4 from sgp4.earth_gravity import wgs72 from sgp4.io import twoline2rv import ephem import pysatMagVect ...
Returns data and metadata in the format required by pysat. Finds position of satellite in both ECI and ECEF co-ordinates. Routine is directly called by pysat and not the user. Parameters ---------- fnames : list-like collection File name that contains date in its name. ...
353,432
def wait_for_visible(self, locator): for i in range(timeout_seconds): try: if self.driver.is_visible(locator): break except: pass time.sleep(1) else: raise ElementVisiblityTimeout("%s visibility ...
Synchronization to deal with elements that are present, but are disabled until some action triggers their visibility. :raises: ElementVisiblityTimeout
353,433
def update_port_side(self): from rafcon.utils.geometry import point_left_of_line p = (self._initial_pos.x, self._initial_pos.y) nw_x, nw_y, se_x, se_y = self.get_adjusted_border_positions() if point_left_of_line(p, (nw_x, nw_y), (se_x, se_y)): if point_left_of_lin...
Updates the initial position of the port The port side is ignored but calculated from the port position. Then the port position is limited to the four side lines of the state.
353,434
def asDictionary(self): template = { "xmin" : self._xmin, "ymin" : self._ymin, "xmax" : self._xmax, "ymax" : self._ymax, "spatialReference" : self.spatialReference } if self._zmax is not None and \ self._zmin is not ...
returns the envelope as a dictionary
353,435
def _aggr_mode(inList): valueCounts = dict() nonNone = 0 for elem in inList: if elem == SENTINEL_VALUE_FOR_MISSING_DATA: continue nonNone += 1 if elem in valueCounts: valueCounts[elem] += 1 else: valueCounts[elem] = 1 if nonNone == 0: return None sortedCount...
Returns most common value seen in the non-None elements of the list
353,436
def get_request_headers(self): request_headers = self.get_proxy_request_headers(self.request) if (self.add_remote_user and hasattr(self.request, ) and self.request.user.is_active): request_headers[] = self.request.user.get_username() self.log.info("REMOT...
Return request headers that will be sent to upstream. The header REMOTE_USER is set to the current user if AuthenticationMiddleware is enabled and the view's add_remote_user property is True. .. versionadded:: 0.9.8
353,437
def _set_ldp_ecmp(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={: []}, int_size=32), restriction_dict={: [u]}), default=RestrictedClassType(base_type=long, restricti...
Setter method for ldp_ecmp, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/ldp/ldp_holder/ldp_ecmp (uint32) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_ecmp is considered as a private method. Backends looking to populate this variable should ...
353,438
def tryValue(self, name, val, scope=): theDict, oldVal = findScopedPar(self, scope, name) if oldVal == val: return (True, None) theDict[name] = val if ans != True: flatStr = "All values are invalid!" if ans != False...
For the given item name (and scope), we are being asked to try the given value to see if it would pass validation. We are not to set it, but just try it. We return a tuple: If it fails, we return: (False, the last known valid value). On success, we return: (True, None)...
353,439
def _spawn_receiver_loop(self): job = gevent.spawn(self._receiver_loop) self.jobs.append(job) return job
Spawns the reader loop. This is called internall by socketio_manage().
353,440
def check_file_existence(path): pathvalidate.validate_file_path(path) if not os.path.lexists(path): raise FileNotFoundError(path) if os.path.isfile(path): logger.debug("file found: " + path) return FileType.FILE if os.path.isdir(path): logger.debug("directory fou...
:return: FileType :rtype: int :raises InvalidFilePathError: :raises FileNotFoundError: :raises RuntimeError:
353,441
def LessThan(self, value): self._awql = self._CreateSingleValueCondition(value, ) return self._query_builder
Sets the type of the WHERE clause as "less than". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
353,442
def next(self): if self._cur_item is not None: res = self._cur_item self._cur_item = None return res return next(self._ex_context)
:return: The next result item. :rtype: dict :raises StopIteration: If there is no more result.
353,443
def bootstrap_auc(df, col, pred_col, n_bootstrap=1000): scores = np.zeros(n_bootstrap) old_len = len(df) df.dropna(subset=[col], inplace=True) new_len = len(df) if new_len < old_len: logger.info("Dropping NaN values in %s to go from %d to %d rows" % (col, old_len, new_len)) preds = ...
Calculate the boostrapped AUC for a given col trying to predict a pred_col. Parameters ---------- df : pandas.DataFrame col : str column to retrieve the values from pred_col : str the column we're trying to predict n_boostrap : int the number of bootstrap samples Re...
353,444
def wait(method, timeout, fail_on_timeout=None, **kwargs): return Waiter(lambda value: bool(value)).start(method, timeout, fail_on_timeout, **kwargs)
Wait ``timeout`` seconds until ``method(**kwargs)`` returns a ``value`` that *bool(value)==True*. Returns last ``value``. If time expired and ``fail_on_timeout`` specified, then raise TimeoutException. :param method: :param timeout: :param fail_on_timeout: :param kwargs: :return:
353,445
def get_main_pattern(self, directory): return os.path.join(directory, format( , extension=self.filename_extension.lstrip(), program_name=self.program_name, prefix=self.get_prefix(directory), ))
Get the :func:`~glob.glob()` pattern to find the main configuration file. :param directory: The pathname of a base directory (a string). :returns: A filename pattern (a string). This method generates a pattern that matches a filename based on :attr:`program_name` with the suffix :attr:...
353,446
def forwards(self, orm): "Write your forwards methods here." for status in orm[].objects.all(): for statustrans_old in orm[].objects.filter(status=status): orm[].objects.create( name=statustrans_old.name, language_...
Write your forwards methods here.
353,447
def List(self, device_path): connection = self.protocol_handler.Open(self._handle, destination=b) listing = self.filesync_handler.List(connection, device_path) connection.Close() return listing
Return a directory listing of the given path. Args: device_path: Directory to list.
353,448
def build_engine_session(connection: str, echo: bool = False, autoflush: Optional[bool] = None, autocommit: Optional[bool] = None, expire_on_commit: Optional[bool] = None, scopefunc=None) -> Tupl...
Build an engine and a session. :param connection: An RFC-1738 database connection string :param echo: Turn on echoing SQL :param autoflush: Defaults to True if not specified in kwargs or configuration. :param autocommit: Defaults to False if not specified in kwargs or configuration. :param expire_o...
353,449
def compress_encoder_1d(x, hparams, name=None): x = tf.expand_dims(x, axis=2) return compress_encoder(x, hparams, strides=(2, 1), kernel_size=(hparams.kernel_size, 1), name=name)
Encoder that compresses 1-D inputs by 2**num_compress_steps. Args: x: Tensor of shape [batch, length, channels]. hparams: HParams. name: string, variable scope. Returns: Tensor of shape [batch, latent_length, hparams.hidden_size], where latent_length is hparams.num_latents * length / 2...
353,450
def return_markers(self): markers = [] triggers = self._triggers DTYPE_MAX = iinfo(triggers.dtype[]).max triggers = triggers[triggers[] != DTYPE_MAX] for trig in triggers: markers.append( {: str(trig[]), : trig[] / self._s_f...
Return all the markers (also called triggers or events). Returns ------- list of dict where each dict contains 'name' as str, 'start' and 'end' as float in seconds from the start of the recordings, and 'chan' as list of str with the channels involved (if not ...
353,451
def authenticate_eauth(self, load): if not in load: log.warning() return False if load[] not in self.opts[]: log.warning(, load[]) log.warning() return False if not self.time_auth(load): log.war...
Authenticate a user by the external auth module specified in load. Return True on success or False on failure.
353,452
def get_api(self, name=None): if name is None: try: return self.conf.get("api").copy() except: raise Exception(f"Couldn't find the API configuration")
Returns the API configuration
353,453
def validate_ignore_reuse(stages, ignore_reuse_stages): if not isinstance(ignore_reuse_stages, list): raise WorkflowBuilderException() ignore_reuse_set = set(ignore_reuse_stages) if in ignore_reuse_set and ignore_reuse_set == 1: return stage_ids = set([stage.get() for stage in s...
Checks if each stage ID specified in ignore_reuse_stages exists in the workflow definition. If ignore_reuse_stages contains only '*', the field is valid.
353,454
def reindex_to(self, x, attribute="Name"): names = [i[attribute] for i in x] new = self.copy() new.data = new.data.reindex(names) return new
Returns a copy that only has rows corresponding to feature names in x. Parameters ---------- x : str or pybedtools.BedTool BED, GFF, GTF, or VCF where the "Name" field (that is, the value returned by feature['Name']) or any arbitrary attribute attribute : str ...
353,455
def isdisjoint(self, other): def isdisjoint_trans_pure(pipe): return not pipe.sinter(self.key, other.key) def isdisjoint_trans_mixed(pipe): self_values = set(self.__iter__(pipe)) if use_redis: other_values = set(other.__iter__(pipe)) ...
Return ``True`` if the set has no elements in common with *other*. Sets are disjoint if and only if their intersection is the empty set. :param other: Any kind of iterable. :rtype: boolean
353,456
def equals(self, other): if self.is_(other): return True if not isinstance(other, Index): return False if is_object_dtype(self) and not is_object_dtype(other): return other.equals(self) try: return array_equivalent(...
Determine if two Index objects contain the same elements.
353,457
def split_user_input(line, pattern=None): encoding = get_stream_enc(sys.stdin, ) line = py3compat.cast_unicode(line, encoding) if pattern is None: pattern = line_split match = pattern.match(line) if not match: try: ifun, the_rest = line.split(None,1) ...
Split user input into initial whitespace, escape character, function part and the rest.
353,458
def close_panel(self): self.hide() self.lineEditReplace.clear() self.lineEditSearch.clear()
Closes the panel
353,459
def _parse_match(self, match): if not match: if self.default: return self.default else: raise NothingMatchedError( f"Extract `{self._re_select}` error, " f"please check selector or set parameter named `defau...
If there is a group dict, return the dict; even if there's only one value in the dict, return a dictionary; If there is a group in match, return the group; if there is only one value in the group, return the value; if there has no group, return the whole matched string; i...
353,460
def gen_blocks(output, ascii_props=False, append=False, prefix=""): with codecs.open(output, if append else , ) as f: if not append: f.write(HEADER) f.write( % prefix) no_block = [] last = -1 max_range = MAXASCII if ascii_props else MAXUNICODE form...
Generate Unicode blocks.
353,461
def _set_exp_dscp_state(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=exp_dscp_state.exp_dscp_state, is_container=, presence=False, yang_name="exp-dscp-state", rest_name="exp-dscp-state", parent=self, path_helper=self._path_helper, extmethods=self._...
Setter method for exp_dscp_state, mapped from YANG variable /exp_dscp_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_exp_dscp_state is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_exp_...
353,462
def start(self, e): logger.debug("Spawning metric & trace reporting threads") self.sensor.meter.run() instana.singletons.tracer.recorder.run()
Starts the agent and required threads
353,463
def get_msg_display_string(self, msgid): message_definitions = self.get_message_definitions(msgid) if len(message_definitions) == 1: return repr(message_definitions[0].symbol) return repr([md.symbol for md in message_definitions])
Generates a user-consumable representation of a message. Can be just the message ID or the ID and the symbol.
353,464
def repr_list(_list, indent): if _list is None: return if isinstance(_list, MutableSequence): bm = em = elif isinstance(_list, Iterable): bm = em = else: raise TypeError("Object must be an iterable, but is a %s" % ...
Return a debug representation of a list or tuple.
353,465
def psnr_stack(data1, data2, metric=np.mean, method=): r if data1.ndim != 3 or data2.ndim != 3: raise ValueError() return metric([psnr(i, j, method=method) for i, j in zip(data1, data2)])
r"""Peak Signa-to-Noise for stack of images This method calculates the PSNRs for two stacks of 2D arrays. By default the metod returns the mean value of the PSNRs, but any other metric can be used. Parameters ---------- data1 : np.ndarray Stack of images, 3D array data2 : np.ndarra...
353,466
def init(parser = None): global p,subparsers if parser is None: p = argparse.ArgumentParser() else: p = parser arg = p.add_argument subparsers = p.add_subparsers()
module needs to be initialized by 'init'. Can be called with parser to use a pre-built parser, otherwise a simple default parser is created
353,467
def notimplemented (func): def newfunc (*args, **kwargs): co = func.func_code attrs = (co.co_name, co.co_filename, co.co_firstlineno) raise NotImplementedError("function %s at %s:%d is not implemented" % attrs) return update_func_meta(newfunc, func)
Raises a NotImplementedError if the function is called.
353,468
def call(self, context, x, losses=None): has_length_dim = context.length_dim in x.shape.dims if not has_length_dim: x_shape = x.shape shape_with_length = mtf.Shape( x_shape.dims[:-1] + [mtf.Dimension("length", 1)] + x_shape.dims[-1:]) x = mtf.reshape(x, shape_with_leng...
Call the layer.
353,469
def _complete(self): text = msg_id = self.kernel_manager.shell_channel.complete( text, self._get_input_buffer_cursor_line(), self._get_input_buffer_cursor_column(), se...
Reimplemented to support IPython's improved completion machinery.
353,470
def del_permission(self, role, name): if not self.has_permission(role, name): return True targetGroup = AuthGroup.objects(role=role, creator=self.client).first() target = AuthPermission.objects(groups=targetGroup, name=name, creator=self.client).first() if not target...
revoke authorization of a group
353,471
def get_missing_languages(self, field_name, db_table): db_table_fields = self.get_table_fields(db_table) for lang_code in AVAILABLE_LANGUAGES: if build_localized_fieldname(field_name, lang_code) not in db_table_fields: yield lang_code
Gets only missings fields.
353,472
def pop_fw_local(self, tenant_id, net_id, direc, node_ip): net = self.get_network(net_id) serv_obj = self.get_service_obj(tenant_id) serv_obj.update_fw_local_cache(net_id, direc, node_ip) if net is not None: net_dict = self.fill_dcnm_net_info(tenant_id, direc, net.vl...
Populate the local cache. Read the Network DB and populate the local cache. Read the subnet from the Subnet DB, given the net_id and populate the cache.
353,473
def instruction_LSR_register(self, opcode, register): a = register.value r = self.LSR(a) register.set(r)
Logical shift right accumulator
353,474
def get_identity(context, prefix=None, identity_func=None, user=None): if prefix is not None: try: return context[ % prefix] except KeyError: pass try: return context[] except KeyError: pass if getattr(settings, , True): try: ...
Get the identity of a logged in user from a template context. The `prefix` argument is used to provide different identities to different analytics services. The `identity_func` argument is a function that returns the identity of the user; by default the identity is the username.
353,475
def get_file_location(self, pathformat=None): if self.scheme != "file": return None, None path = url_unquote(self.path) host = self.netloc or None if pathformat is None: if os.name == "nt": pathformat = "windows" else: ...
Returns a tuple with the location of the file in the form ``(server, location)``. If the netloc is empty in the URL or points to localhost, it's represented as ``None``. The `pathformat` by default is autodetection but needs to be set when working with URLs of a specific system. The s...
353,476
def add_property(self, pred, obj): pred = Uri(pred) try: self[pred].append(obj) except KeyError: try: new_prop = self.properties[pred] except AttributeError: self.properties = {} ...
adds a property and its value to the class instance args: pred: the predicate/property to add obj: the value/object to add obj_method: *** No longer used.
353,477
def fetch(self, vault_client): result = self.read(vault_client) if result: if isinstance(result, dict) and in result: self.existing = result[] else: self.existing = result else: self.existing = None
Populate internal representation of remote Vault resource contents
353,478
def argument_search(self): arguments, _ = self.argparser.parse_known_args() return self.search(**vars(arguments))
Uses the command line arguments to fill the search function and call it.
353,479
def initialize(self, endog, freq_weights): if (endog.ndim > 1 and endog.shape[1] > 1): y = endog[:, 0] self.n = endog.sum(1) return y*1./self.n, self.n else: return endog, np.ones(endog.shape[0])
Initialize the response variable. Parameters ---------- endog : array Endogenous response variable Returns -------- If `endog` is binary, returns `endog` If `endog` is a 2d array, then the input is assumed to be in the format (successes, fai...
353,480
def unsubscribe_from_chat( self, subscriber: Callable[[events.ChatMessageWasReceived], None], ) -> None: self._chat_subscribers.remove(subscriber)
Not thread-safe.
353,481
def connect(self, addr): if _debug: DeviceToDeviceClientService._debug("connect %r", addr) conn = ConnectionState(addr) self.multiplexer.connections[addr] = conn conn.service = self conn.pendingNPDU = [] request = ServiceRe...
Initiate a connection request to the device.
353,482
def get_radial_circles(self): circles = ffi.new() _check_status(cairo.cairo_pattern_get_radial_circles( self._pointer, circles + 0, circles + 1, circles + 2, circles + 3, circles + 4, circles + 5)) return tuple(circles)
Return this radial gradient’s endpoint circles, each specified as a center coordinate and a radius. :returns: A ``(cx0, cy0, radius0, cx1, cy1, radius1)`` tuple of floats.
353,483
def hparams(self, defaults, unused_model_hparams): (super(BabiQa, self).hparams(defaults, unused_model_hparams)) p = defaults num_classes = self._encoders["targets"].vocab_size p.modality = {"targets": modalities.ModalityType.CLASS_LABEL} p.vocab_size = {"targets": num_classes}
Returns problem_hparams. Args: defaults: default hyperparameters unused_model_hparams: model hyperparameters
353,484
def fetch(weeks, force): weeks = get_last_weeks(weeks) print(weeks) recommender = RecordRecommender(config) recommender.fetch_weeks(weeks, overwrite=force)
Fetch newest PageViews and Downloads.
353,485
def inventory(host, port, time, report_every_n_tags, antennas, tx_power, tari, session, mode_identifier, tag_population, reconnect, tag_filter_mask, impinj_extended_configuration, impinj_search_mode, impinj_reports, impinj_fixed_freq): Args = namedtu...
Conduct inventory (searching the area around the antennas).
353,486
def mouse_release_event(self, event): if event.button() not in [1, 2]: return self.example.mouse_release_event(event.x(), event.y(), event.button())
Forward mouse release events to the example
353,487
def cli(obj, name, email, password, status, text): if not any([name, email, password, status, text]): click.echo() sys.exit(1) client = obj[] try: r = client.update_me(name=name, email=email, password=password, status=status, attributes=None, text=text) except Exception as ...
Update current user details, including password reset.
353,488
def from_service_account_file(cls, filename, **kwargs): info, signer = _service_account_info.from_filename( filename, require=[, ]) return cls._from_signer_and_info(signer, info, **kwargs)
Creates a Credentials instance from a service account json file. Args: filename (str): The path to the service account json file. kwargs: Additional arguments to pass to the constructor. Returns: google.auth.service_account.Credentials: The constructed ...
353,489
def _at_for(self, calculator, rule, scope, block): var, _, name = block.argument.partition() frm, _, through = name.partition() if through: inclusive = True else: inclusive = False frm, _, through = frm.partition() frm = calculator.cal...
Implements @for
353,490
def listen(self, grpc_port): if self._grpc_port: raise ValueError( "This DebuggerPlugin instance is already listening at gRPC port %d" % self._grpc_port) self._grpc_port = grpc_port sys.stderr.write( % (self._grpc_port, self._logdir)) sys.stderr.flush...
Start listening on the given gRPC port. This method of an instance of DebuggerPlugin can be invoked at most once. This method is not thread safe. Args: grpc_port: port number to listen at. Raises: ValueError: If this instance is already listening at a gRPC port.
353,491
def check_socket(host, port): with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: return sock.connect_ex((host, port)) == 0
Checks if port is open on host. This is used to check if the Xenon-GRPC server is running.
353,492
def comments(self, group, event_id): resource = urijoin(group, self.REVENTS, event_id, self.RCOMMENTS) params = { self.PPAGE: self.max_items } for page in self._fetch(resource, params): yield page
Fetch the comments of a given event.
353,493
def stft_from_frames(frames, window=, dtype=np.complex64): win_length = frames.shape[0] n_fft = win_length fft_window = filters.get_window(window, win_length, fftbins=True) fft_window = fft_window.reshape((-1, 1)) stft_matrix = np.empty((int(1 + n_fft // 2), frames.shape[1]), ...
Variation of the librosa.core.stft function, that computes the short-time-fourier-transfrom from frames instead from the signal. See http://librosa.github.io/librosa/_modules/librosa/core/spectrum.html#stft
353,494
def pull(self, images, file_name=None, save=True, **kwargs): s requested name for the file. It can optionally be None if the user wants a default. save: if True, you should save the container to the database using self.add() Returns ======= finished: a single container...
pull an image from a singularity registry Parameters ========== images: refers to the uri given by the user to pull in the format <collection>/<namespace>. You should have an API that is able to retrieve a container based on parsing this uri. file_name: the user's requested name for the file....
353,495
def from_mapping(self, *mapping, **kwargs): mappings = [] if len(mapping) == 1: if hasattr(mapping[0], ): mappings.append(mapping[0].items()) else: mappings.append(mapping[0]) elif len(mapping) > 1: raise TypeE...
Updates the config like :meth:`update` ignoring items with non-upper keys.
353,496
def _cmp_by_origin(path1, path2): def get_origin_pref(origin): if origin.value == BGP_ATTR_ORIGIN_IGP: return 3 elif origin.value == BGP_ATTR_ORIGIN_EGP: return 2 elif origin.value == BGP_ATTR_ORIGIN_INCOMPLETE: return 1 else: LOG....
Select the best path based on origin attribute. IGP is preferred over EGP; EGP is preferred over Incomplete. If both paths have same origin, we return None.
353,497
def out(self, obj, formatter=None, out_file=None): if not isinstance(obj, CommandResultItem): raise TypeError(.format(CommandResultItem.__name__, type(obj))) import platform import colorama if platform.system() == : out_file = colorama.AnsiToWin32(out...
Produces the output using the command result. The method does not return a result as the output is written straight to the output file. :param obj: The command result :type obj: knack.util.CommandResultItem :param formatter: The formatter we should use for the command result ...
353,498
def UpdateUserCredentials(client_id, client_secret, refresh_token, adwords_manager_cid, developer_token): app_user = AppUser.query(AppUser.user == users.get_current_user()).fetch()[0] app_user.client_id = client_id app_user.client_secret = client_secret app_user.refresh_token = ref...
Update the credentials associated with application user. Args: client_id: str Client Id retrieved from the developer's console. client_secret: str Client Secret retrieved from the developer's console. refresh_token: str Refresh token generated with the above client id/secret. adwords_manager_cid: str...
353,499
def get_cards(self, archived_state=github.GithubObject.NotSet): assert archived_state is github.GithubObject.NotSet or isinstance(archived_state, (str, unicode)), archived_state url_parameters = dict() if archived_state is not github.GithubObject.NotSet: url_parameters["arc...
:calls: `GET /projects/columns/:column_id/cards <https://developer.github.com/v3/projects/cards/#list-project-cards>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.ProjectCard.ProjectCard` :param archived_state: string