text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def delete_wish_list_by_id(cls, wish_list_id, **kwargs):
"""Delete WishList
Delete an instance of WishList by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_wish_list_by_id(wis... | 0.00444 |
def init_ui(self):
"""Setup control widget UI."""
self.control_layout = QHBoxLayout()
self.setLayout(self.control_layout)
self.reset_button = QPushButton()
self.reset_button.setFixedSize(40, 40)
self.reset_button.setIcon(QtGui.QIcon(WIN_PATH))
self.game_timer = QL... | 0.002621 |
def adjustRange(self, recursive=True):
"""
Adjust the start and end ranges for this item based on the limits from
its children. This method will only apply to group items.
:param recursive | <bool>
"""
if ( self.adjustmentsBlocked('range') ):
... | 0.020886 |
def summarize_tensors(tensor_dict, tag=None):
"""Summarize the tensors.
Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/.
"""
if tag is None:
tag = "tensors/"
for t_name in list(tensor_dict):
t = tensor_dict[t_name]
tf.summary.histogram(tag... | 0.012012 |
def get_missing_value_key(d):
"""
Get the Missing Value entry from a table of data. If none is found, try the columns.
If still none found, prompt user.
:param dict d: Table of data
:return str _mv: Missing Value
"""
_mv = "nan"
# Attempt to find a table-level missing value key
try... | 0.005373 |
def get_alt_lengths(self):
"""Returns the longest length of the variant. For deletions, return is negative,
SNPs return 0, and insertions are +. None return corresponds to no variant in interval
for specified individual
"""
#this is a hack to store the # of individuals without h... | 0.009494 |
def list_documents(project_id, knowledge_base_id):
"""Lists the Documents belonging to a Knowledge base.
Args:
project_id: The GCP project linked with the agent.
knowledge_base_id: Id of the Knowledge base."""
import dialogflow_v2beta1 as dialogflow
client = dialogflow.DocumentsClient()... | 0.000996 |
def register(self, typedef):
"""
Add the typedef to this engine if it is compatible.
After registering a :class:`~TypeDefinition`, it will not be bound
until :meth:`~TypeEngine.bind` is next called.
Nothing will happen when register is called with a typedef that is
pend... | 0.001779 |
def _apply(self, method_name, *args, **kwargs):
"""Call ``method_name`` with args and kwargs on each member.
Returns a sequence of return values.
"""
return [
getattr(member, method_name)(*args, **kwargs)
for member in self.forms
] | 0.006711 |
def _cc(self):
"""
implementation of the efficient bilayer cross counting by insert-sort
(see Barth & Mutzel paper "Simple and Efficient Bilayer Cross Counting")
"""
g=self.layout.grx
P=[]
for v in self:
P.extend(sorted([g[x].pos for x in self._neighbo... | 0.018622 |
def widont_html(value):
"""
Add an HTML non-breaking space between the final two words at the end of
(and in sentences just outside of) block level tags to avoid "widowed"
words.
Examples:
>>> print(widont_html('<h2>Here is a simple example </h2> <p>Single</p>'))
<h2>Here is a simple&nbs... | 0.004667 |
def strings_equal(s1, s2):
"""
Timing-attack resistant string comparison.
Normal comparison using == will short-circuit on the first mismatching
character. This avoids that by scanning the whole string, though we
still reveal to a timing attack whether the strings are the same
length.
"""
... | 0.003396 |
def updateFontPicker(self):
"""
Updates the font picker widget to the current font settings.
"""
font = self.currentFont()
self._fontPickerWidget.setPointSize(font.pointSize())
self._fontPickerWidget.setCurrentFamily(font.family()) | 0.007018 |
def detect_encoding(self, path):
"""
For the implementation of encoding definitions in Python, look at:
- http://www.python.org/dev/peps/pep-0263/
.. note:: code taken and adapted from
```jedi.common.source_to_unicode.detect_encoding```
"""
with open(path, 'r... | 0.002026 |
def authorization_code(self, request, data, client):
"""
Handle ``grant_type=authorization_code`` requests as defined in
:rfc:`4.1.3`.
"""
grant = self.get_authorization_code_grant(request, request.POST,
client)
if constants.SINGLE_ACCESS_TOKEN:
... | 0.010264 |
def clause_indices(self):
"""The list of clause indices in ``words`` layer.
The indices are unique only in the boundary of a single sentence.
"""
if not self.is_tagged(CLAUSE_ANNOTATION):
self.tag_clause_annotations()
return [word.get(CLAUSE_IDX, None) for word in sel... | 0.006079 |
def setup_logging(self):
"""Setup python logging handler."""
date_format = '%Y-%m-%dT%H:%M:%S'
log_format = '%(asctime)s %(levelname)s: %(message)s'
if self.opts.verbose:
lvl = logging.DEBUG
else:
lvl = logging.INFO
# Requests is a bit chatty
... | 0.001987 |
def data(self, data):
"""Called for text between tags"""
if self.state == STATE_SOURCE_ID:
self.context.audit_record.source_id = int(data) # Audit ids can be 64 bits
elif self.state == STATE_DATETIME:
dt = datetime.datetime.strptime(data, "%Y-%m-%dT%H:%M:%S")
... | 0.007105 |
def long_encode(input, errors='strict'):
"""Transliterate to 8 bit using as many letters as needed.
For example, \u00e4 LATIN SMALL LETTER A WITH DIAERESIS ``ä`` will
be replaced with ``ae``.
"""
if not isinstance(input, text_type):
input = text_type(input, sys.getdefaultencoding(), errors... | 0.002268 |
def dotted(self):
" Returns dotted-decimal reperesentation "
obj = libcrypto.OBJ_nid2obj(self.nid)
buf = create_string_buffer(256)
libcrypto.OBJ_obj2txt(buf, 256, obj, 1)
if pyver == 2:
return buf.value
else:
return buf.value.decode('ascii') | 0.00639 |
def mark_broker_action_done(action, rid=None, unit=None):
"""Mark action as having been completed.
@param action: name of action to be performed
@returns None
"""
rdata = relation_get(rid, unit) or {}
broker_rsp = rdata.get(get_broker_rsp_key())
if not broker_rsp:
return
rsp = ... | 0.001832 |
def ask(question, default_answer=False, default_answer_str="no"):
"""
Ask for user input.
This asks a yes/no question with a preset default.
You can bypass the user-input and fetch the default answer, if
you set
Args:
question: The question to ask on stdout.
default_answer: The... | 0.000768 |
def quick_search(self, name, platform=None, sort_by=None, desc=True):
"""
Quick search method that allows you to search for a game using only the
title and the platform
:param name: string
:param platform: int
:param sort_by: string
:param desc: bool
:ret... | 0.002096 |
def save(self, obj):
"""Save current instance - as per the gludb spec."""
cur = self._conn().cursor()
tabname = obj.__class__.get_table_name()
index_names = obj.__class__.index_names() or []
col_names = ['id', 'value'] + index_names
value_holders = ['%s'] * len(col_nam... | 0.003061 |
def serialize(self, include_class=True, save_dynamic=False, **kwargs):
"""Serializes a **HasProperties** instance to dictionary
This uses the Property serializers to serialize all Property values
to a JSON-compatible dictionary. Properties that are undefined are
not included. If the **H... | 0.001112 |
def parse(fp):
"""
Parse the contents of the `~io.IOBase.readline`-supporting file-like object
``fp`` as a simple line-oriented ``.properties`` file and return a
generator of ``(key, value, original_lines)`` triples for every entry in
``fp`` (including duplicate keys) in order of occurrence. The th... | 0.001647 |
def showGroupMenu( self ):
"""
Displays the group menu to the user for modification.
"""
group_active = self.isGroupingActive()
group_by = self.groupBy()
menu = XMenu(self)
menu.setTitle('Grouping Options')
menu.setShowTitle(True)
... | 0.013138 |
def write_file(file_path, txt, **kws):
"""将文本内容写入文件。
:param str file_path: 文件路径。
:param str txt: 待写入的文件内容。
"""
if not os.path.exists(file_path):
upDir = os.path.dirname(file_path)
if not os.path.isdir(upDir):
os.makedirs(upDir)
kw = {"mode":"w", "encoding":"utf-8"}... | 0.00885 |
def _read_gtf(gtf):
"""
Load GTF file with precursor positions on genome
"""
if not gtf:
return gtf
db = defaultdict(list)
with open(gtf) as in_handle:
for line in in_handle:
if line.startswith("#"):
continue
cols = line.strip().split("\t")... | 0.00319 |
def close_handle(self):
"""
Closes the handle to the module.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them. So unless you've been tinkering with it,
sett... | 0.003175 |
def configure_all_loggers_for_colour(remove_existing: bool = True) -> None:
"""
Applies a preconfigured datetime/colour scheme to ALL logger.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE ... | 0.001789 |
def select_color(cpcolor, evalcolor, idx=0):
""" Selects item color for plotting.
:param cpcolor: color for control points grid item
:type cpcolor: str, list, tuple
:param evalcolor: color for evaluated points grid item
:type evalcolor: str, list, tuple
:param idx: index of the current geometry... | 0.001031 |
def _set_blob_properties(self, ud):
# type: (Uploader, blobxfer.models.upload.Descriptor) -> None
"""Set blob properties (md5, cache control)
:param Uploader self: this
:param blobxfer.models.upload.Descriptor ud: upload descriptor
"""
if ud.requires_non_encrypted_md5_put... | 0.004219 |
def multi_ifo_coherent_job_setup(workflow, out_files, curr_exe_job,
science_segs, datafind_outs, output_dir,
parents=None, slide_dict=None, tags=None):
"""
Method for setting up coherent inspiral jobs.
"""
if tags is None:
tags = ... | 0.003549 |
def pdf_split(
input: str, output: str, stepsize: int = 1, sequence: [int] = None
):
"""
Split the input file in multiple output files
:param input: name of the input file
:param output: name of the output files
:param stepsize: how many pages per file, only if sequence is None
:param sequen... | 0.000534 |
def getAggShocks(self):
'''
Returns aggregate state variables and shocks for this period. The capital-to-labor ratio
is irrelevant and thus treated as constant, and the wage and interest rates are also
constant. However, aggregate shocks are assigned from a prespecified history.
... | 0.011295 |
def of_cls(self):
"""
DONT USE. Will be deleted soon. Use ``self.of``!
"""
if isinstance(self.of, six.string_types):
warnings.warn('When using Range programatically, dont pass "of" param as string!')
return Register.get_task_cls(self.of)
return self.of | 0.009494 |
def generic_loss(top_out, targets, model_hparams, vocab_size, weights_fn):
"""Compute loss numerator and denominator for one shard of output."""
del vocab_size # unused arg
logits = top_out
logits = common_attention.maybe_upcast(logits, hparams=model_hparams)
cutoff = getattr(model_hparams, "video_modality_l... | 0.014056 |
def configure_proxy(self, curl_object):
"""configure pycurl proxy settings"""
curl_object.setopt(curl_object.PROXY, self._proxy_hostname)
curl_object.setopt(curl_object.PROXYPORT, self._proxy_port)
curl_object.setopt(curl_object.PROXYTYPE, curl_object.PROXYTYPE_SOCKS5)
if self._p... | 0.00655 |
def set_coupl_old(self):
""" Using the adjacency matrix, sample a coupling matrix.
"""
if self.model == 'krumsiek11' or self.model == 'var':
# we already built the coupling matrix in set_coupl20()
return
self.Coupl = np.zeros((self.dim,self.dim))
for i in ... | 0.008172 |
def get_weather(test=False):
"""
Returns weather reports from the dataset.
"""
if _Constants._TEST or test:
rows = _Constants._DATABASE.execute("SELECT data FROM weather LIMIT {hardware}".format(
hardware=_Constants._HARDWARE))
data = [r[0] for r in rows]
data = ... | 0.00838 |
def wait(self, timeout=None):
# type: (Optional[int]) -> None
"""Wait on the long running operation for a specified length
of time. You can check if this call as ended with timeout with the
"done()" method.
:param int timeout: Period of time to wait for the long running
... | 0.005714 |
def getlist(self, key, delimiter=',', **kwargs):
"""
Gets the setting value as a :class:`list`; it splits the string using ``delimiter``.
:param str delimiter: split the value using this delimiter
:rtype: list
"""
value = self.get(key, **kwargs)
if value is None... | 0.008026 |
def _from_hex_digest(digest):
"""Convert hex digest to sequence of bytes."""
return "".join(
[chr(int(digest[x : x + 2], 16)) for x in range(0, len(digest), 2)]
) | 0.010989 |
def run_job(self,
job, # type: Union[JobBase, WorkflowJob, None]
runtime_context # type: RuntimeContext
): # type: (...) -> None
""" Execute a single Job in a seperate thread. """
if job is not None:
with self.pending_jobs_lock:
... | 0.004702 |
def data_dirpath(task=None, **kwargs):
"""Get the path of the corresponding data directory.
Parameters
----------
task : str, optional
The task for which datasets in the desired directory are used for. If
not given, a path for the corresponding task-agnostic directory is
returne... | 0.000812 |
def model_page(self, request, app_label, model_name, rest_of_url=None):
"""
Handles the model-specific functionality of the databrowse site,
delegating<to the appropriate ModelDatabrowse class.
"""
try:
model = get_model(app_label, model_name)
except LookupErr... | 0.002538 |
def image_height(image):
"""
Returns the height of the image found at the path supplied by `image`
relative to your project's images directory.
"""
image_size_cache = _get_cache('image_size_cache')
if not Image:
raise SassMissingDependency('PIL', 'image manipulation')
filepath = Stri... | 0.000929 |
def build_java_docs(app):
"""build java docs and then move the outdir"""
java_path = app.builder.srcdir + '/../scala-package'
java_doc_sources = 'find . -type f -name "*.scala" | egrep \"\.\/core|\.\/infer\" | egrep \"\/javaapi\" | egrep -v \"Suite\"'
java_doc_classpath = ':'.join([
'`find nativ... | 0.008841 |
def _parse_api_time(timestr):
"""
Typical expiration times returned from the auth server are in this
format:
2012-05-02T14:27:40.000-05:00
They can also be returned as a UTC value in this format:
2012-05-02T14:27:40.000Z
This method returns a proper dateti... | 0.002641 |
def remove_file(self, relativePath, name=None, removeFromSystem=False):
"""
Remove file from repository.
:Parameters:
#. relativePath (string): The relative to the repository path of the directory where the file should be dumped.
If relativePath does not exist, it wil... | 0.007306 |
def model_definition_factory(base_model_definition, **kwargs):
"""
Provides an iterator over passed-in
configuration values, allowing for easy
exploration of models.
Parameters:
___________
base_model_definition:
The base `ModelDefinition` to augment
kwargs:
Can be any... | 0.002328 |
def _listAttrGroupMembers(self, attrGroup):
"""
Returns a list of all members in the attribute group.
"""
from inspect import getmembers, ismethod
methods = getmembers(self, ismethod)
group_prefix = attrGroup + '_'
group_len = len(group_prefix)
group_membe... | 0.004107 |
def get_keys(src, dst, keys):
"""
Copies the value of keys from source object to dest object
:param src:
:param dst:
:param keys:
:return:
"""
for key in keys:
#dst[no_camel(key)] = src[key] if key in src else None
dst[key] = src[key] if key in src else None | 0.006515 |
def get_onionoo_details(self, agent):
"""
Requests the 'details' document from onionoo.torproject.org via
the given `twisted.web.iweb.IAgent` -- you can get a suitable
instance to pass here by calling either :meth:`txtorcon.Tor.web_agent` or
:meth:`txtorcon.Circuit.web_agent`.
... | 0.004072 |
def copyFile(input, output, replace=None):
"""Copy a file whole from input to output."""
_found = findFile(output)
if not _found or (_found and replace):
shutil.copy2(input, output) | 0.00495 |
def _write_box_information(xml_file, structure, ref_distance):
"""Write box information.
Parameters
----------
xml_file : file object
The file object of the hoomdxml file being written
structure : parmed.Structure
Parmed structure object
ref_energy : float, default=1.0
R... | 0.001887 |
def fetch_column(self, sql, *args, **kwargs):
"""Executes an SQL SELECT query and returns the first column of the first row or `None`.
:param sql: statement to execute
:param args: parameters iterable
:param kwargs: parameters iterable
:return: the first row of the first column ... | 0.006757 |
def _parse_json(self, page, exactly_one=True):
'''Returns location, (latitude, longitude) from json feed.'''
places = page.get('results', [])
if not len(places):
self._check_status(page.get('status'))
return None
def parse_place(place):
'''Get the lo... | 0.00267 |
def set_chain_info(self, chain_id, chain_name, num_groups):
"""Set the chain information.
:param chain_id: the asym chain id from mmCIF
:param chain_name: the auth chain id from mmCIF
:param num_groups: the number of groups this chain has
"""
self.chain_id_list.append(cha... | 0.004728 |
def nonspeech_fragments(self):
"""
Iterates through the nonspeech fragments in the list
(which are sorted).
:rtype: generator of (int, :class:`~aeneas.syncmap.SyncMapFragment`)
"""
for i, fragment in enumerate(self.__fragments):
if fragment.fragment_type == S... | 0.005249 |
def do_gate_matrix(self, matrix: np.ndarray,
qubits: Sequence[int]) -> 'AbstractQuantumSimulator':
"""
Apply an arbitrary unitary; not necessarily a named gate.
:param matrix: The unitary matrix to apply. No checks are done
:param qubits: A list of qubits to apply... | 0.00678 |
def create_group(self, name):
"""
Create group
:param name: Group name
"""
parameters = {
'name': name
}
url = self.TEAM_GROUPS_URL
connection = Connection(self.token)
connection.set_url(self.production, url)
connection.add_pa... | 0.005291 |
def filter_single_need(need, filter_string=""):
"""
Checks if a single need/need_part passes a filter_string
:param need: need or need_part
:param filter_string: string, which is used as input for eval()
:return: True, if need as passed the filter_string, else False
"""
filter_context = nee... | 0.003333 |
def block_matrix(A, B, C, D):
r"""Generate the operator matrix with quadrants
.. math::
\begin{pmatrix} A B \\ C D \end{pmatrix}
Args:
A (Matrix): Matrix of shape ``(n, m)``
B (Matrix): Matrix of shape ``(n, k)``
C (Matrix): Matrix of shape ``(l, m)``
D (Matrix): Ma... | 0.002062 |
def base_warfare(name, bases, attributes):
"""
Adds any number of attributes to an existing class.
:param name: Name.
:type name: unicode
:param bases: Bases.
:type bases: list
:param attributes: Attributes.
:type attributes: dict
:return: Base.
:rtype: object
"""
asser... | 0.003373 |
def setMonospace(self):
"""
Fix the fonts of the first 32 styles to a mono space one.
|Args|
* **None**
|Returns|
**None**
|Raises|
* **None**
"""
font = bytes('courier new', 'utf-8')
for ii in range(32):
self.Send... | 0.005525 |
def sg_train_func(func):
r""" Decorates a function `func` as sg_train_func.
Args:
func: A function to decorate
"""
@wraps(func)
def wrapper(**kwargs):
r""" Manages arguments of `tf.sg_opt`.
Args:
**kwargs:
lr: A Python Scalar (optional). Learning rate.... | 0.002884 |
def _deploy(self):
"""Deploy environment and wait for all hooks to finish executing."""
timeout = int(os.environ.get('AMULET_SETUP_TIMEOUT', 900))
try:
self.d.setup(timeout=timeout)
self.d.sentry.wait(timeout=timeout)
except amulet.helpers.TimeoutError:
... | 0.004049 |
def call_frog(text):
"""
Call frog on the text and return (sent, offset, word, lemma, pos, morphofeat) tuples
"""
host, port = os.environ.get('FROG_HOST', 'localhost:9887').split(":")
frogclient = FrogClient(host, port, returnall=True)
sent = 1
offset = 0
for word, lemma, morph, mor... | 0.006633 |
def _createConnection(self, connections):
"""
Create GSSHAPY Connection Objects Method
"""
for c in connections:
# Create GSSHAPY Connection object
connection = Connection(slinkNumber=c['slinkNumber'],
upSjuncNumber=c['upSjunc'... | 0.003976 |
def add_lv_load_area(self, lv_load_area):
# TODO: check docstring
"""Adds a LV load_area to _lv_load_areas if not already existing
Args
----
lv_load_area: :shapely:`Shapely Polygon object<polygons>`
Descr
"""
self._lv_load_areas.append(lv_load... | 0.008989 |
def redirect_stdout(self, enabled=True, log_level=logging.INFO):
"""
Redirect sys.stdout to file-like object.
"""
if enabled:
if self.__stdout_wrapper:
self.__stdout_wrapper.update_log_level(log_level=log_level)
else:
self.__stdout_... | 0.005085 |
def train(self, conversation):
"""
Train the chat bot based on the provided list of
statements that represents a single conversation.
"""
previous_statement_text = None
previous_statement_search_text = ''
statements_to_create = []
for conversation_count,... | 0.002368 |
def words(self, fileids=None) -> Generator[str, str, None]:
"""
Provide the words of the corpus; skipping any paragraphs flagged by keywords to the main
class constructor
:param fileids:
:return: words, including punctuation, one by one
"""
for sentence in self.se... | 0.006652 |
def _compute_permanent_id(private_key):
"""
Internal helper. Return an authenticated service's permanent ID
given an RSA private key object.
The permanent ID is the base32 encoding of the SHA1 hash of the
first 10 bytes (80 bits) of the public key.
"""
pub = private_key.public_key()
p =... | 0.001484 |
def area(p):
"""Area of a polygone
:param p: list of the points taken in any orientation,
p[0] can differ from p[-1]
:returns: area
:complexity: linear
"""
A = 0
for i in range(len(p)):
A += p[i - 1][0] * p[i][1] - p[i][0] * p[i - 1][1]
return A / 2. | 0.003279 |
def _make_headers(config, kwargs):
""" Replace the kwargs with one where the headers include our user-agent """
headers = kwargs.get('headers')
headers = headers.copy() if headers is not None else {}
headers['User-Agent'] = config.args.user_agent
kwargs = kwargs.copy()
kwargs['headers'] = head... | 0.005865 |
def analyze(self, config_string=None):
"""
Analyze the given container and
return the corresponding job object.
On error, it will return ``None``.
:param string config_string: the configuration string generated by wizard
:rtype: :class:`~aeneas.job.Job` or ``None``
... | 0.004241 |
def list_files(self, extensions=None):
"""
List the ports contents by file type or all.
:param extensions: string extensions, single string or list of extensions.
:return: A list of full path names of each file.
"""
if self.type.lower() != 'directory':
raise V... | 0.003148 |
def _six_fail_hook(modname):
"""Fix six.moves imports due to the dynamic nature of this
class.
Construct a pseudo-module which contains all the necessary imports
for six
:param modname: Name of failed module
:type modname: str
:return: An astroid module
:rtype: nodes.Module
"""
... | 0.000821 |
def delete_topology(self, topologyName):
""" delete topology """
path = self.get_topology_path(topologyName)
LOG.info("Removing topology: {0} from path: {1}".format(
topologyName, path))
try:
self.client.delete(path)
return True
except NoNodeError:
raise_(StateException("No... | 0.012571 |
def main_lstm_generate_text():
"""Generate text by Synced sequence input and output."""
# rnn model and update (describtion: see tutorial_ptb_lstm.py)
init_scale = 0.1
learning_rate = 1.0
max_grad_norm = 5
sequence_length = 20
hidden_size = 200
max_epoch = 4
max_max_epoch = 100
... | 0.001916 |
def GetArtifactKnowledgeBase(client_obj, allow_uninitialized=False):
"""This generates an artifact knowledge base from a GRR client.
Args:
client_obj: A GRRClient object which is opened for reading.
allow_uninitialized: If True we accept an uninitialized knowledge_base.
Returns:
A KnowledgeBase sema... | 0.007117 |
def _TemplateNamesToFiles(self, template_str):
"""Parses a string of templates into a list of file handles."""
template_list = template_str.split(":")
template_files = []
try:
for tmplt in template_list:
template_files.append(open(os.path.join(self.template_di... | 0.00625 |
def get_setter(self, oid):
"""
Retrieve the nearest parent setter function for an OID
"""
if hasattr(self.setter, oid):
return self.setter[oid]
parents = [ poid for poid in list(self.setter.keys()) if oid.startswith(poid) ]
if parents:
return self.setter[max(parents)]
return self.default_setter | 0.044444 |
def has_trivial_constructor(class_):
"""if class has public trivial constructor, this function will return
reference to it, None otherwise"""
class_ = class_traits.get_declaration(class_)
trivial = find_trivial_constructor(class_)
if trivial and trivial.access_type == 'public':
return trivia... | 0.003115 |
def get(self):
"""
Reloads the measurements from the backing store.
:return: 200 if success.
"""
try:
self._measurementController.reloadCompletedMeasurements()
return None, 200
except:
logger.exception("Failed to reload measurements")
... | 0.008287 |
def _host():
"""Get the Host from the most recent HTTP request."""
host_and_port = request.urlparts[1]
try:
host, _ = host_and_port.split(':')
except ValueError:
# No port yet. Host defaults to '127.0.0.1' in bottle.request.
return DEFAULT_BIND
return host or DEFAULT_BIND | 0.003165 |
def record_list_projects(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /record-xxxx/listProjects API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects
"""
return DXHTTPRequest('/%s/listProjec... | 0.010336 |
def handle(self):
"""
Executes the command
"""
database = self.option("database")
repository = DatabaseMigrationRepository(self.resolver, "migrations")
repository.set_source(database)
repository.create_repository()
self.info("Migration table created succ... | 0.006061 |
def extract(self, searches, tree=None, as_dict=True):
"""
>>> foo = pdf.extract([['pages', 'LTPage']])
>>> foo
{'pages': [<LTPage>, <LTPage>]}
>>> pdf.extract([['bar', ':in_bbox("100,100,400,400")']], foo['pages'][0])
{'bar': [<LTTextLineHorizont... | 0.001898 |
def git_clone(target_dir, repo_location, branch_or_tag=None, verbose=True):
"""Clone repo at repo_location to target_dir and checkout branch_or_tag.
If branch_or_tag is not specified, the HEAD of the primary
branch of the cloned repo is checked out.
"""
target_dir = pipes.quote(target_dir)
comm... | 0.001546 |
def VEXTRACTF128(cpu, dest, src, offset):
"""Extract Packed Floating-Point Values
Extracts 128-bits of packed floating-point values from the source
operand (second operand) at an 128-bit offset from imm8[0] into the
destination operand (first operand). The destination may be either an
... | 0.006036 |
def value(self, value, *args, **kwargs):
"""
Takes a string value and returns the Date based on the format
"""
from datetime import datetime
value = self.obj.value(value, *args, **kwargs)
try:
rv = datetime.strptime(value, self.format)
except ValueErro... | 0.005333 |
def secure(func_or_obj, check_permissions_for_obj=None):
"""
This method secures a method or class depending on invocation.
To decorate a method use one argument:
@secure(<check_permissions_method>)
To secure a class, invoke with two arguments:
secure(<obj instance>, <check_permissions... | 0.001339 |
def get_all_context_names(context_num):
"""Based on the nucleotide base context number, return
a list of strings representing each context.
Parameters
----------
context_num : int
number representing the amount of nucleotide base context to use.
Returns
-------
a list of st... | 0.001032 |
def raise_on_failure(mainfunc):
"""raise if and only if mainfunc fails"""
try:
errors = mainfunc()
if errors:
exit(errors)
except CalledProcessError as error:
exit(error.returncode)
except SystemExit as error:
if error.code:
raise
except Keyboa... | 0.004975 |
def package_config(path, template='__config__.ini.TEMPLATE', config_name='__config__.ini', **params):
"""configure the module at the given path with a config template and file.
path = the filesystem path to the given module
template = the config template filename within that path
... | 0.004296 |
def lca(root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root is None or root is p or root is q:
return root
left = lca(root.left, p, q)
right = lca(root.right, p, q)
if left is not None and right is not None:
retur... | 0.00277 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.