Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
366,900
def container_start(name, remote_addr=None, cert=None, key=None, verify_cert=True): container = container_get( name, remote_addr, cert, key, verify_cert, _raw=True ) container.start(wait=True) return _pylxd_model_to_dict(container)
Start a container name : Name of the container to start remote_addr : An URL to a remote Server, you also have to give cert and key if you provide remote_addr and its a TCP Address! Examples: https://myserver.lan:8443 /var/lib/mysocket.sock cert : ...
366,901
def get_command(self, version=2): try: options = _C[] options_str = " -o ".join(options) if options_str: options_str = "-o " + options_str + " " except KeyError: options_str = "" if self.username: ...
Return the SSH protocol specific command to connect.
366,902
def get_many(self, content_ids, feature_names=None): try: resp = self.conn.mget(index=self.index, doc_type=self.type, _source=self._source(feature_names), body={: map(eid, content_ids)}) except TransportError: ...
Returns an iterable of feature collections. This efficiently retrieves multiple FCs corresponding to the list of ids given. Tuples of identifier and feature collection are yielded. If the feature collection for a given id does not exist, then ``None`` is returned as the second element o...
366,903
def reStructuredText_to_html(input, output, css_file): LOGGER.info("{0} | Converting reStructuredText file to html!".format( reStructuredText_to_html.__name__, input)) os.system("{0} --stylesheet-path= > ".format(RST2HTML, os.path....
Outputs a reStructuredText file to html. :param input: Input reStructuredText file to convert. :type input: unicode :param output: Output html file. :type output: unicode :param css_file: Css file. :type css_file: unicode :return: Definition success. :rtype: bool
366,904
def _forward(X, s=1.1, gamma=1., k=5): X = list(X) def alpha(i): return (n/T)*(s**i) def tau(i, j): if j > i: return (j-i)*gamma*log(n) return 0. def f(j, x): return alpha(j) * exp(-1. * alpha(j) * x) def C(j, t): if j == 0 and t == 0: ...
Forward dynamic algorithm for burstness automaton HMM, from `Kleinberg (2002) <http://www.cs.cornell.edu/home/kleinber/bhs.pdf>`_. Parameters ---------- X : list A series of time-gaps between events. s : float (default: 1.1) Scaling parameter ( > 1.)that controls graininess of ...
366,905
def seq_dup_levels_plot (self): data = dict() max_dupval = 0 for s_name in self.fastqc_data: try: thisdata = {} for d in self.fastqc_data[s_name][]: thisdata[d[]] = d[] max_dupval = max(max_dupval, d[])...
Create the HTML for the Sequence Duplication Levels plot
366,906
def make_file_path(project_dir, project_name, root, name): return path.join(make_dir_path(project_dir, root, project_name), name)
Generates the target path for a file
366,907
def make_mutant_tuples(example_protos, original_feature, index_to_mutate, viz_params): mutant_features = make_mutant_features(original_feature, index_to_mutate, viz_params) mutant_examples = [] for example_proto in example_protos: for mutant_f...
Return a list of `MutantFeatureValue`s and a list of mutant Examples. Args: example_protos: The examples to mutate. original_feature: A `OriginalFeatureList` that encapsulates the feature to mutate. index_to_mutate: The index of the int64_list or float_list to mutate. viz_params: A `VizParams` ...
366,908
def setup(self, services): super(SchedulerService, self).setup(services) self._fs_event_service.register_all_files_handler(self._enqueue_fs_event) if self._invalidation_globs: self._invalidating_snapshot = self._get_snapshot() self._invalidating_files = self._invalidating_sn...
Service setup.
366,909
def imagetransformer_base_8l_8h_big_cond_dr03_dan(): hparams = imagetransformer_sep_channels_8l() hparams.block_width = 256 hparams.block_length = 256 hparams.hidden_size = 512 hparams.num_heads = 8 hparams.filter_size = 2048 hparams.batch_size = 4 hparams.max_length = 3075 hparams.layer_preprocess...
big 1d model for conditional image generation.2.99 on cifar10.
366,910
def make_processitem_arguments(arguments, condition=, negate=False, preserve_case=False): document = search = content_type = content = arguments ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=...
Create a node for ProcessItem/arguments :return: A IndicatorItem represented as an Element node
366,911
def normalize_url(url): uri = urlparse(url) query = uri.query or "" pairs = parse_qsl(query) decoded_pairs = [(unquote(key), value) for key, value in pairs] encoded_pairs = [(quote(key), value) for key, value in decoded_pairs] normalized_query = urlencode(encoded_pairs) return ParseR...
Returns the given URL with all query keys properly escaped. Args: url (str): The URL to normalize. Returns: str: The normalized URL.
366,912
def get_interfaces(self): interfaces = self.xml.find().iter() iobjs = [] for interface in interfaces: _type = interface.attrib[] mac = interface.find().attrib[] source = interface.find().attrib[_type] model = interface.find().attrib[] ...
Return a list of sham.network.interfaces.NetworkInterface describing all the interfaces this VM has
366,913
def get_checksum(self, encoder=base64.b64encode, hasher=hashlib.sha256): assert self._closed, "Archive not closed" with open(self._temp_archive_file.name, ) as fh: return encoder(checksum(fh, hasher())).decode()
Return the b64 encoded sha256 checksum of the archive.
366,914
def render(self, template_name, __data=None, **kw): return self.template.render(template_name, **self._vars(__data, **kw))
Given a template name and template data. Renders a template and returns as string
366,915
def _group_by_sample_and_batch(samples): out = collections.defaultdict(list) for data in samples: out[(dd.get_sample_name(data), dd.get_align_bam(data), tuple(_get_batches(data)))].append(data) return [xs[0] for xs in out.values()]
Group samples split by QC method back one per sample-batch.
366,916
def add_file(self, **args): s information to the set of files to be published in this dataset. :param file_name: Mandatory. The file name (string). This information will simply be included in the PID record, but not used for anything. :param file_handle: Mandato...
Adds a file's information to the set of files to be published in this dataset. :param file_name: Mandatory. The file name (string). This information will simply be included in the PID record, but not used for anything. :param file_handle: Mandatory. The handle (PID) of ...
366,917
def createAllShaders(self): "Purpose: Creates all the shaders used by HelloVR SDL" self.m_unSceneProgramID = self.compileGLShader( "Scene", dedent(), dedent() ) self.m_nSceneMatrixLocation = glGetUniformLocation( s...
Purpose: Creates all the shaders used by HelloVR SDL
366,918
def collect(self): collected = super(Command, self).collect() if self.faster: self.worker_spawn_method() self.post_processor() return collected
Create some concurrent workers that process the tasks simultaneously.
366,919
def generate_hash(filepath): fr = FileReader(filepath) data = fr.read_bin() return _calculate_sha256(data)
Public function that reads a local file and generates a SHA256 hash digest for it
366,920
def get_portchannel_info_by_intf_output_lacp_receive_machine_state(self, **kwargs): config = ET.Element("config") get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf") config = get_portchannel_info_by_intf output = ET.SubElement(get_portchannel_info_by_intf, ...
Auto Generated Code
366,921
def setStyles(self, styleUpdatesDict): setStyleMethod = self.setStyle for newName, newValue in styleUpdatesDict.items(): setStyleMethod(newName, newValue) return self.style
setStyles - Sets one or more style params. This all happens in one shot, so it is much much faster than calling setStyle for every value. To remove a style, set its value to empty string. When all styles are removed, the "style" attribute will be nullified. ...
366,922
def calculate(self, batch_info): value = self._value_function(batch_info) self.buffer += value
Calculate value of a metric
366,923
def get_event(self, *etypes, timeout=None): self._validate_etypes(*etypes) start = time.time() e = self._eventq.get(timeout=timeout) if isinstance(e, Exception): raise e self._stats[] += 1 if etypes and e.type not in etypes: if timeout: ...
Return a single event object or block until an event is received and return it. - etypes(str): If defined, Slack event type(s) not matching the filter will be ignored. See https://api.slack.com/events for a listing of valid event types. - timeout(int): Max time, in second...
366,924
def qteKillMiniApplet(self): if self._qteMiniApplet is None: return if not self.qteIsMiniApplet(self._qteMiniApplet): msg = ( ) self.qteLogger.warning(msg) if self._qteMiniApplet not in self._qteAppletList: ...
Remove the mini applet. If a different applet is to be restored/focused then call ``qteMakeAppletActive`` for that applet *after* calling this method. |Args| * **None** |Returns| * **None** |Raises| * **None**
366,925
def cdf_single(z, N, normalization, dH=1, dK=3): return 1 - fap_single(z, N, normalization=normalization, dH=dH, dK=dK)
Cumulative distribution for the Lomb-Scargle periodogram Compute the expected cumulative distribution of the periodogram for the null hypothesis - i.e. data consisting of Gaussian noise. Parameters ---------- z : array-like the periodogram value N : int the number of data point...
366,926
def update(self, resource, id_, updates): args = self._es_args(resource, refresh=True) if self._get_retry_on_conflict(): args[] = self._get_retry_on_conflict() updates.pop(, None) updates.pop(, None) self._update_parent_args(resource, args, updates) ...
Update document in index.
366,927
def waitForVMState(rh, userid, desiredState, maxQueries=90, sleepSecs=5): rh.printSysLog("Enter vmUtils.waitForVMState, userid: " + userid + " state: " + desiredState + " maxWait: " + str(maxQueries) + " sleepSecs: " + str(sleepS...
Wait for the virtual machine to go into the indicated state. Input: Request Handle userid whose state is to be monitored Desired state, 'on' or 'off', case sensitive Maximum attempts to wait for desired state before giving up Sleep duration between waits Output: Dicti...
366,928
def loads(self, string): "Decompress the passed-in compact script and return the result." script_class = self.get_script_class() script = self._load(BytesIO(string), self._protocol, self._version) return script_class(script)
Decompress the passed-in compact script and return the result.
366,929
def ProgChunks(list_, chunksize, nInput=None, **kwargs): if nInput is None: nInput = len(list_) n_chunks = get_num_chunks(nInput, chunksize) kwargs[] = n_chunks if not in kwargs: kwargs[] = 1 chunk_iter = util_iter.ichunks(list_, chunksize) progiter_ = ProgressIter(chunk_it...
Yeilds an iterator in chunks and computes progress Progress version of ut.ichunks Args: list_ (list): chunksize (?): nInput (None): (default = None) Kwargs: length, freq Returns: ProgressIter: progiter_ CommandLine: python -m utool.util_progress Pr...
366,930
def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format): inputs_for_logging = inputs if strides > 1: inputs = fixed_padding(inputs, kernel_size, data_format) outputs = tf.layers.conv2d( inputs=inputs, filters=filters, kernel_size=kernel_size, strides=strides, paddin...
Strided 2-D convolution with explicit padding.
366,931
def read_file(self, filename): try: fh = open(filename, ) table_set = any_tableset(fh) except: table_set = None return table_set
Guess the filetype and read the file into row sets
366,932
def shell(command, **kwargs): b_stdoutflush = False b_stderrflush = False b_waitForChild = True for key, val in kwargs.items(): if key == : b_stdoutflush = val if key == : b_stderrflush = val if key == : b_waitForChild = val chil...
Runs 'command' on the underlying shell and keeps the stdout and stderr stream separate. Returns [stdout, stderr, exitCode]
366,933
def set_sgr_code(self, params): if not params: return code = params.pop(0) if code == 0: self.reset_sgr() elif code == 1: if self.bold_text_enabled: self.bold = True else: self.intensity = ...
Set attributes based on SGR (Select Graphic Rendition) codes. Parameters ---------- params : sequence of ints A list of SGR codes for one or more SGR commands. Usually this sequence will have one element per command, although certain xterm-specific commands r...
366,934
def Negative(other_param, mode="invert", reroll_count_max=2): return ForceSign( other_param=other_param, positive=False, mode=mode, reroll_count_max=reroll_count_max )
Converts another parameter's results to negative values. Parameters ---------- other_param : imgaug.parameters.StochasticParameter Other parameter which's sampled values are to be modified. mode : {'invert', 'reroll'}, optional How to change the signs. Valid values are ``invert...
366,935
def _send_command(self, command): if self.status is None or self.status.media_session_id is None: self.logger.warning( "%s command requested but no session is active.", command[MESSAGE_TYPE]) return command[] = self.status.media_session_i...
Send a command to the Chromecast on media channel.
366,936
def make_importfrom_alias(queue, body, context, name): import_from, store = queue.popleft(), queue.popleft() expect(import_from, instrs.IMPORT_FROM, "after IMPORT_NAME") if not import_from.arg == name: raise DecompilationError( "IMPORT_FROM name mismatch. Expected %r, but got %s." ...
Make an ast.alias node for the names list of an ast.ImportFrom. Parameters ---------- queue : deque Instruction Queue body : list Current body. context : DecompilationContext name : str Expected name of the IMPORT_FROM node to be popped. Returns ------- alia...
366,937
def cal(self, opttype, strike, exp1, exp2): assert pd.Timestamp(exp1) < pd.Timestamp(exp2) _row1 = _relevant_rows(self.data, (strike, exp1, opttype,), "No key for {} strike {} {}".format(exp1, strike, opttype)) _row2 = _relevant_rows(self.data, (strike, exp2, opttype,), ...
Metrics for evaluating a calendar spread. Parameters ------------ opttype : str ('call' or 'put') Type of option on which to collect data. strike : numeric Strike price. exp1 : date or date str (e.g. '2015-01-01') Earlier expiration date. ...
366,938
def embedding_lookup(self, x, means): x_means_hot = self.nearest_neighbor(x, means) x_means_hot_flat = tf.reshape( x_means_hot, [-1, self.hparams.num_blocks, self.hparams.block_v_size]) x_means = tf.matmul(tf.transpose(x_means_hot_flat, perm=[1, 0, 2]), means) x_means = tf.transpose(x_means...
Compute nearest neighbors and loss for training the embeddings. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means. Returns: The nearest neighbor in one hot form, the nearest neighbor ...
366,939
def parse(url_or_path, encoding=None, handler_class=DrillHandler): handler = handler_class() parser = expat.ParserCreate(encoding) parser.buffer_text = 1 parser.StartElementHandler = handler.start_element parser.EndElementHandler = handler.end_element parser.CharacterDataHandler = handler.c...
:param url_or_path: A file-like object, a filesystem path, a URL, or a string containing XML :rtype: :class:`XmlElement`
366,940
def increment(self, counter_name, delta): current_value = self.counters.get(counter_name, 0) new_value = current_value + delta self.counters[counter_name] = new_value return new_value
Increment counter value. Args: counter_name: counter name as String. delta: increment delta as Integer. Returns: new counter value.
366,941
def route(self, path_regex, methods=[], doc=True): def register_func(func): if doc: self.env[].append({: path_regex, : .join(methods), : func.__doc__}) for method in methods: self._handlers[method].append((re.compile(path_regex), func...
Decorator to register a handler Parameters: * path_regex: Request path regex to match against for running the handler * methods: HTTP methods to use this handler for * doc: Add to internal doc structure
366,942
def _handle_option_deprecations(options): undeprecated_options = _CaseInsensitiveDictionary() for key, value in iteritems(options): optname = str(key).lower() if optname in URI_OPTIONS_DEPRECATION_MAP: renamed_key = URI_OPTIONS_DEPRECATION_MAP[optname] if renamed_key...
Issue appropriate warnings when deprecated options are present in the options dictionary. Removes deprecated option key, value pairs if the options dictionary is found to also have the renamed option.
366,943
def waitStarted(self): ns = None while not ns: try: time.sleep(3) ns = Pyro.naming.NameServerLocator( identification=self.identification).getNS() except Pyro.errors.NamingError as er: pass
wait until name server is started.
366,944
def _list_fields(self): response = self.__proxy__.list_fields() return [s for s in response[] if not s.startswith("_")]
Get the current settings of the model. The keys depend on the type of model. Returns ------- out : list A list of fields that can be queried using the ``get`` method.
366,945
def mount_iso_image(self, image, image_name, ins_file_name): query_parms_str = . \ format(quote(image_name, safe=), quote(ins_file_name, safe=)) self.manager.session.post( self.uri + + query_parms_str, body=image)
Upload an ISO image and associate it to this Partition using the HMC operation 'Mount ISO Image'. When the partition already has an ISO image associated, the newly uploaded image replaces the current one. Authorization requirements: * Object-access permission to this Partition...
366,946
def rename_scored_calls(self,change): output = self.copy() output[] = output.apply(lambda x: _dict_rename(x[],change) ,1) return output
Change the names of scored call names, input dictionary change with {<current name>:<new name>} format, new name must not already exist Args: change (dict): a dictionary of current name keys and new name values Returns: CellDataFrame: The CellDataFrame modified.
366,947
def get_graphs(self, run_key, debug=False): graph_dict = (self._run_key_to_debug_graphs if debug else self._run_key_to_original_graphs) graph_wrappers = graph_dict.get(run_key, {}) graph_defs = dict() for device_name, wrapper in graph_wrappers.items(): graph_defs[device_name...
Get the runtime GraphDef protos associated with a run key. Args: run_key: A Session.run kay. debug: Whether the debugger-decoratedgraph is to be retrieved. Returns: A `dict` mapping device name to `GraphDef` protos.
366,948
def pixel_to_utm(row, column, transform): east = transform[0] + column * transform[1] north = transform[3] + row * transform[5] return east, north
Convert pixel coordinate to UTM coordinate given a transform :param row: row pixel coordinate :type row: int or float :param column: column pixel coordinate :type column: int or float :param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)` ...
366,949
def sys_mmap_pgoff(self, address, size, prot, flags, fd, offset): return self.sys_mmap2(address, size, prot, flags, fd, offset)
Wrapper for mmap2
366,950
def get_domain(url): parse_result = urlparse(url) domain = "{schema}://{netloc}".format( schema=parse_result.scheme, netloc=parse_result.netloc) return domain
Get domain part of an url. For example: https://www.python.org/doc/ -> https://www.python.org
366,951
def syllabifyTextgrid(isleDict, tg, wordTierName, phoneTierName, skipLabelList=None, startT=None, stopT=None): sp minT = tg.minTimestamp maxT = tg.maxTimestamp wordTier = tg.tierDict[wordTierName] phoneTier = tg.tierDict[phoneTierName] if skipLabelList is None: ...
Given a textgrid, syllabifies the phones in the textgrid skipLabelList allows you to skip labels without generating warnings (e.g. '', 'sp', etc.) The textgrid must have a word tier and a phone tier. Returns a textgrid with only two tiers containing syllable information (syllabificati...
366,952
def get_comment(self, name): comment = self.__comments.get(name) if comment: return comment aliases = self.__get_aliases(name) for alias in aliases: comment = self.__comments.get(alias) if comment: return comment ret...
Banana banana
366,953
def formatted_command(self): command = command_template.format(**format_dict) return command
Build and return the formatted command for this `Link`. This is exactly the command as called from the Unix command line.
366,954
def _clone_node(self) -> : clone = type(self)() for attr in self.attributes: clone.setAttribute(attr, self.getAttribute(attr)) for c in self.classList: clone.addClass(c) clone.style.update(self.style) return clone
Need to copy class, not tag. So need to re-implement copy.
366,955
def list_dvs(kwargs=None, call=None): if call != : raise SaltCloudSystemExit( ) return {: salt.utils.vmware.list_dvs(_get_si())}
List all the distributed virtual switches for this VMware environment CLI Example: .. code-block:: bash salt-cloud -f list_dvs my-vmware-config
366,956
def all(guideids=None, filter=None, order=None): parameters = [] if guideids: parameters.append( % .join(map(str, guideids))) if filter: parameters.append( % filter) if order: parameters.append( % order) parameters = .join(parameters) offset =...
Fetch all guides. :param iterable guideids: Only return Guides corresponding to these ids. :param string filter: Only return guides of this type. Choices: installation, repair, disassembly, teardown, technique, maintenance. :param string ...
366,957
def get_provider(self, provider_name=): try: if self._providers is None: self._providers = self._initialize_providers() return self._providers[provider_name] except KeyError: raise AssertionError(f)
Fetch provider with the name specified in Configuration file
366,958
def _validate_features(features, column_type_map, valid_types, label): if not isinstance(features, list): raise TypeError("Input must be a list, if specified.") if len(features) == 0: raise ValueError("If specified, input must contain " + "at least one column nam...
Identify the subset of desired `features` that are valid for the Kmeans model. A warning is emitted for each feature that is excluded. Parameters ---------- features : list[str] Desired feature names. column_type_map : dict[str, type] Dictionary mapping each column name to the type...
366,959
def _convert_reftype_to_jaeger_reftype(ref): if ref == link_module.Type.CHILD_LINKED_SPAN: return jaeger.SpanRefType.CHILD_OF if ref == link_module.Type.PARENT_LINKED_SPAN: return jaeger.SpanRefType.FOLLOWS_FROM return None
Convert opencensus reference types to jaeger reference types.
366,960
def resolve_aonly(self,tables_dict,table_ctor): "circular depends on pgmock.Table. refactor." for alias,selectx in self.aonly.items(): table = table_ctor(alias,infer_columns(selectx,tables_dict),None) table.rows = run_select(selectx,tables_dict,table_ctor) self.aonly[alias] = table self.ao...
circular depends on pgmock.Table. refactor.
366,961
def os_application_version_set(package): application_version = get_upstream_version(package) if not application_version: application_version_set(os_release(package)) else: application_version_set(application_version)
Set version of application for Juju 2.0 and later
366,962
def plot_eq(fignum, DIblock, s): plt.figure(num=fignum) if len(DIblock) < 1: return if not isServer: plt.figtext(.02, .01, version_num) plot_net(fignum) plot_di(fignum, DIblock) plt.axis("equal") plt.text(-1.1, 1.15, s) plt.draw()
plots directions on eqarea projection Parameters __________ fignum : matplotlib figure number DIblock : nested list of dec/inc pairs s : specimen name
366,963
def version_check(self): try: version_info = self[] except KeyError: raise ValidateError() try: float(version_info[]) except KeyError: raise ValidateError() except ValueError: raise ValidateError() ...
Check if the version entry is in the proper format
366,964
def parallelize(self, c, numSlices=None): numSlices = int(numSlices) if numSlices is not None else self.defaultParallelism if isinstance(c, xrange): size = len(c) if size == 0: return self.parallelize([], numSlices) step = c[1] - c[0] if size ...
Distribute a local Python collection to form an RDD. Using xrange is recommended if the input represents a range for performance. >>> sc.parallelize([0, 2, 3, 4, 6], 5).glom().collect() [[0], [2], [3], [4], [6]] >>> sc.parallelize(xrange(0, 6, 2), 5).glom().collect() [[], [0], [...
366,965
def pick(rest): "Pick between a few options" question = rest.strip() choices = util.splitem(question) if len(choices) == 1: return "I can't pick if you give me only one choice!" else: pick = random.choice(choices) certainty = random.sample(phrases.certainty_opts, 1)[0] return "%s... %s %s" % (pick, certain...
Pick between a few options
366,966
def append(self, node): if node.parent == self.key and not self.elapsed_time: self.children.append(node) else: for child in self.children: if not child.elapsed_time: child.append(node)
To append a new child.
366,967
def _email(name, *, allow_unverified=False): def inner(fn): @functools.wraps(fn) def wrapper(request, user_or_users, **kwargs): if isinstance(user_or_users, (list, set)): recipients = user_or_users else: recipients = [user_or_users] ...
This decorator is used to turn an e function into an email sending function! The name parameter is the name of the email we're going to be sending (used to locate the templates on the file system). The allow_unverified kwarg flags whether we will send this email to an unverified email or not. We gener...
366,968
def enabled(name, skip_verify=False, **kwargs): t want to manage the running process, remember that if you want to enable a running service to use the enable: True option for the running or dead function. name The name of the init or rc script used to manage the service ...
Ensure that the service is enabled on boot, only use this state if you don't want to manage the running process, remember that if you want to enable a running service to use the enable: True option for the running or dead function. name The name of the init or rc script used to manage the servi...
366,969
def expand_param_list(self, paramlist): if type(paramlist) == types.DictType: paramlist = [paramlist] iparamlist = [] for params in paramlist: if ( in params and params[] == ): iparamlist.append(params) else:...
expands the parameters list according to one of these schemes: grid: every list item is combined with every other list item list: every n-th list item of parameter lists are combined
366,970
def auth_timeout(self): self.lock.acquire() try: self.__logger.debug("Timeout while waiting for jabber:iq:auth result") if self._auth_methods_left: self._auth_methods_left.pop(0) finally: self.lock.release()
Handle legacy authentication timeout. [client only]
366,971
def fly(cls, conf_path, docname, source, maxdepth=1): msg = ("``.. articles::`` directive is going to be deprecated. " "use ``.. autodoctree`` instead.") warnings.warn(msg, FutureWarning) directive_pattern = ".. articles:...
Generate toctree directive for rst file. :param conf_path: conf.py file absolute path :param docname: the rst file relpath from conf.py directory. :param source: rst content. :param maxdepth: int, max toc tree depth.
366,972
def get_tok(self, tok): tdata = self.tokens["{0}.get_token".format(self.opts[])](self.opts, tok) if not tdata: return {} rm_tok = False if not in tdata: rm_tok = True if tdata.get(, ) < time.time(): rm_tok = True ...
Return the name associated with the token, or False if the token is not valid
366,973
def get_response_structure(name): return { CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST: SMB2CreateDurableHandleResponse(), CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT: SMB2CreateDurableHandleReconnect(), CreateConte...
Returns the response structure for a know list of create context responses. :param name: The constant value above :return: The response structure or None if unknown
366,974
def trees_to_dataframe(self, fmap=): if not PANDAS_INSTALLED: raise Exception(( )) if getattr(self, , None) is not None and self.booster not in {, }: raise ValueError( .format(self.booster)) tre...
Parse a boosted tree model text dump into a pandas DataFrame structure. This feature is only defined when the decision tree model is chosen as base learner (`booster in {gbtree, dart}`). It is not defined for other base learner types, such as linear learners (`booster=gblinear`). Param...
366,975
def get_token(self): payload = {: , : self.client_id, : self.client_secret} r = requests.post(OAUTH_ENDPOINT, data=json.dumps(payload), headers={: }) response = r.json() if r.status_code != 200 and not ERROR_KEY in response: raise GfycatClientErr...
Gets the authorization token
366,976
def _delete_element(name, element_type, data, server=None): _api_delete(.format(element_type, quote(name, safe=)), data, server) return name
Delete an element
366,977
def mask_from_embedding(emb): return weights_nonzero(tf.reduce_sum(tf.abs(emb), axis=3, keepdims=True))
Input embeddings -> padding mask. We have hacked symbol_modality to return all-zero embeddings for padding. Returns a mask with 0.0 in the padding positions and 1.0 elsewhere. Args: emb: a Tensor with shape [batch, width, height, depth]. Returns: a 0.0/1.0 Tensor with shape [batch, width, height, 1].
366,978
def run_loop(self): "keep rendering until the user says quit" self.running = True event = SDL_Event() try: while self.running: while SDL_PollEvent(ctypes.byref(event)) != 0: f = self._sdl_event_handlers.get(event.type) if f is not None: f ( event ) self.render_scene() exc...
keep rendering until the user says quit
366,979
def in6_iseui64(x): eui64 = inet_pton(socket.AF_INET6, ) x = in6_and(inet_pton(socket.AF_INET6, x), eui64) return x == eui64
Return True if provided address has an interface identifier part created in modified EUI-64 format (meaning it matches *::*:*ff:fe*:*). Otherwise, False is returned. Address must be passed in printable format.
366,980
def get_degenerate_statements(self): logger.info("Checking for statements...\n") q_stmts = prefixes + res_stmts = self.g.query(q_stmts) logger.info("Protein -> Protein/Activity statements:") logger.info("---------------------------------------") for s...
Get all degenerate BEL statements. Stores the results of the query in self.degenerate_stmts.
366,981
def fetch(self, method, params=None): if params: params = urllib.parse.urlencode(params, doseq=True).encode("utf-8") content = self._make_request( self.BASE_URI + method, params, ) return json.loads(content.decode("utf-8"))
Fetch an url.
366,982
def fit_zyz(target_gate): assert bk.BACKEND == tf = bk.TL tfe = bk.tfe steps = 4000 dev = if bk.DEVICE == else with tf.device(dev): t = tfe.Variable(np.random.normal(size=[3]), name=) def loss_fn(): gate = qf.ZYZ(t[0], t[1], t[2]) ...
Tensorflow eager mode example. Given an arbitrary one-qubit gate, use gradient descent to find corresponding parameters of a universal ZYZ gate.
366,983
def check_gap(xpub, api_key): params = {: api_key, : xpub} resource = + util.urlencode(params) resp = util.call_api(resource, base_url=) json_resp = json.loads(resp) return json_resp[]
Call the 'v2/receive/checkgap' endpoint and returns the callback log for a given callback URI with parameters. :param str xpub: extended public key :param str api_key: Blockchain.info API V2 key :return: an int
366,984
def query_all_issues(after): page = count(1) data = [] while True: page_data = query_issues(next(page), after) if not page_data: break data.extend(page_data) return data
Hits the github API for all closed issues after the given date, returns the data.
366,985
def remove_filter_set(self, filter_name): if filter_name in self._filter_sets: del self._filter_sets[filter_name] else: raise ValueError()
Remove filter set by name :param filter_name: str
366,986
def _call_multi(self, clients, command, *args): responses, errors = {}, {} for addr, client in clients.items(): res, err = self._call_single(client, command, *args) responses[addr] = res errors[addr] = err return responses, errors
Call multi
366,987
def from_rotation_matrix(rot, nonorthogonal=True): try: from scipy import linalg except ImportError: linalg = False rot = np.array(rot, copy=False) shape = rot.shape[:-2] if linalg and nonorthogonal: from operator import mul from functools import reduce ...
Convert input 3x3 rotation matrix to unit quaternion By default, if scipy.linalg is available, this function uses Bar-Itzhack's algorithm to allow for non-orthogonal matrices. [J. Guidance, Vol. 23, No. 6, p. 1085 <http://dx.doi.org/10.2514/2.4654>] This will almost certainly be quite a bit slower than...
366,988
def tags(self): tags = set() for i in self: tags |= set(i.keys()) return tags
Creates a list of all the tags of the contained items # Returns `list [str]` > A list of all the tags
366,989
def norm(A): return np.sqrt(A.multiply(A).sum(1).A1) if issparse(A) else np.sqrt(np.einsum(, A, A))
computes the L2-norm along axis 1 (e.g. genes or embedding dimensions) equivalent to np.linalg.norm(A, axis=1)
366,990
def ordered_by_replica(self, request_key): state = self.get(request_key) if not state: return state.unordered_by_replicas_num -= 1
Should be called by each replica when request is ordered or replica is removed.
366,991
def add(self, member, score): return self.client.zadd(self.name, member, score)
Add the specified member to the sorted set, or update the score if it already exist.
366,992
def ComplementEquivalence(*args, **kwargs): return ast.Complement( ast.Equivalence(*args, **kwargs), **kwargs)
Change x != y to not(x == y).
366,993
def validate_xml(file): max_file_size = current_app.config.get( , 1 * 1024 * 1024) if file.size > max_file_size: return False with file.open() as fp: try: content = fp.read().decode() xml.dom.minidom.parseString(content) return True e...
Validate an XML file.
366,994
def _set_status_data(self, userdata): self._on_mask = userdata[] self._off_mask = userdata[] self._x10_house_code = userdata[] self._x10_unit = userdata[] self._ramp_rate = userdata[] self._on_level = userdata[] self._led_brightness = userdata[] s...
Set status properties from userdata response. Response values: d3: On Mask d4: Off Mask d5: X10 House Code d6: X10 Unit d7: Ramp Rate d8: On-Level d9: LED Brightness d10: Non-Toggle Mask d11: LED ...
366,995
def generate_terms(self, ref, root, file_type=None): last_section = root t = None if isinstance(ref, Source): row_gen = ref ref_path = row_gen.__class__.__name__ else: row_gen = get_generator(ref) ref_path = ref.path tr...
An generator that yields term objects, handling includes and argument children. :param file_type: :param doc: :param root: :param ref:
366,996
def get_assessment_part_item_design_session(self, proxy): if not self.supports_assessment_part_lookup(): raise errors.Unimplemented() return sessions.AssessmentPartItemDesignSession(proxy=proxy, runtime=self._runtime)
Gets the ``OsidSession`` associated with the assessment part item design service. return: (osid.assessment.authoring.AssessmentPartItemDesignSession) - an ``AssessmentPartItemDesignSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_...
366,997
def get_attribute_values_string(self): attributes = [] for attribute_name, attribute_value in sorted(self.__dict__.items()): if attribute_name[0] == or attribute_value is None: continue if isinstance(attribute_value, dict): attribute_value = sorted(attribute_value.items...
Retrieves a comparable string of the attribute values. Returns: str: comparable string of the attribute values.
366,998
def gt_type(self): if not self.called: return None elif all(a == 0 for a in self.gt_alleles): return HOM_REF elif len(set(self.gt_alleles)) == 1: return HOM_ALT else: return HET
The type of genotype, returns one of ``HOM_REF``, ``HOM_ALT``, and ``HET``.
366,999
def begin_tag(self, name: str) -> Node: self.tag_cache[name] = Tag(self._stream, self._stream.index) return True
Save the current index under the given name.