text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_region():
"""Gets the AWS Region ID for this system
:return: (str) AWS Region ID where this system lives
"""
log = logging.getLogger(mod_logger + '.get_region')
# First get the availability zone
availability_zone = get_availability_zone()
if availability_zone is None:
msg ... | 0.003578 |
def query(
self,
query,
job_config=None,
job_id=None,
job_id_prefix=None,
location=None,
project=None,
retry=DEFAULT_RETRY,
):
"""Run a SQL query.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.... | 0.00152 |
def _extract_from_html(msg_body):
"""
Extract not quoted message from provided html message body
using tags and plain text algorithm.
Cut out first some encoding html tags such as xml and doctype
for avoiding conflict with unicode decoding
Cut out the 'blockquote', 'gmail_quote' tags.
Cut ... | 0.000681 |
def permalink(func):
"""
Decorator that calls app_reverse()
Use this instead of standard django.db.models.permalink if you want to
integrate the model through ApplicationContent. The wrapped function
must return 4 instead of 3 arguments::
class MyModel(models.Model):
@appmodels.p... | 0.001761 |
def create_listening_socket(host, port, handler):
"""
Create socket and set listening options
:param host:
:param port:
:param handler:
:return:
"""
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(1)
... | 0.002591 |
def sendRobust(
signal=Any,
sender=Anonymous,
*arguments, **named
):
"""Send signal from sender to all connected receivers catching errors
signal -- (hashable) signal value, see connect for details
sender -- the sender of the signal
if Any, only receivers registered for Any ... | 0.002654 |
def setGameScore(self, user_id, score, game_message_identifier,
force=None,
disable_edit_message=None):
"""
See: https://core.telegram.org/bots/api#setgamescore
:param game_message_identifier: Same as ``msg_identifier`` in :meth:`telepot.Bot.editMessage... | 0.009346 |
def p_queue(p):
"""
queue : QUEUE COLON LIFO
| QUEUE COLON FIFO
"""
if p[3] == "LIFO":
p[0] = {"queue": LIFO()}
elif p[3] == "FIFO":
p[0] = {"queue": FIFO()}
else:
raise RuntimeError("Queue discipline '%s' is not supported!" % p[1]) | 0.003425 |
def create_install_template_skin(self):
"""
Create an example ckan extension for this environment and install it
"""
ckan_extension_template(self.name, self.target)
self.install_package_develop('ckanext-' + self.name + 'theme') | 0.007491 |
def _delete_state(self, activity, agent, state_id=None, registration=None, etag=None):
"""Private method to delete a specified state from the LRS
:param activity: Activity object of state to be deleted
:type activity: :class:`tincan.activity.Activity`
:param agent: Agent object of state... | 0.001923 |
def start_watcher_thread(self):
"""
Start watcher thread.
:return:
Watcher thread object.
"""
# Create watcher thread
watcher_thread = threading.Thread(target=self.run_watcher)
# If the reload mode is `spawn_wait`
if self._reload_mode == self... | 0.002695 |
def transmit(self, payload, **kwargs):
"""
Transmit content metadata items to the integrated channel.
"""
items_to_create, items_to_update, items_to_delete, transmission_map = self._partition_items(payload)
self._transmit_delete(items_to_delete)
self._transmit_create(item... | 0.007557 |
def execute(self, kv, **kwargs):
"""
Execute the operation scheduling items as needed
:param kv: An iterable of keys (or key-values, or Items)
:param kwargs: Settings for the operation
:return: A MultiResult object
"""
self._verify_iter(kv)
if not len(kv):... | 0.002022 |
def letter2num(letters, zbase=False):
"""A = 1, C = 3 and so on. Convert spreadsheet style column
enumeration to a number.
Answers:
A = 1, Z = 26, AA = 27, AZ = 52, ZZ = 702, AMJ = 1024
>>> from channelpack.pullxl import letter2num
>>> letter2num('A') == 1
True
>>> letter2num('Z') == ... | 0.001166 |
def get(cls, attachment_public_uuid, custom_headers=None):
"""
Get a specific attachment's metadata through its UUID. The Content-Type
header of the response will describe the MIME type of the attachment
file.
:type api_context: context.ApiContext
:type attachment_public... | 0.002323 |
def to_python(self, value):
"""Convert value if needed."""
if isinstance(value, GroupDescriptor):
value = value._value # pylint: disable=protected-access
result = {}
for name, field in self.fields.items():
result[name] = field.to_python(value.get(name, None))
... | 0.005602 |
def extractor(url):
"""Extract details from the response body."""
response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed)
if clone:
mirror(url, response)
matches = rhref.findall(response)
for link in matches:
# Remove e... | 0.000969 |
def create_log_entry(self, log_entry_form):
"""Creates a new ``LogEntry``.
arg: log_entry_form (osid.logging.LogEntryForm): the form for
this ``LogEntry``
return: (osid.logging.LogEntry) - the new ``LogEntry``
raise: IllegalState - ``log_entry_form`` already used in ... | 0.004292 |
def org_set_member_access(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /org-xxxx/setMemberAccess API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FsetMemberAccess
"""
return DXHTTPRequest('/%s/se... | 0.01005 |
def register_db(cls, dbname):
"""Register method to keep list of dbs."""
def decorator(subclass):
"""Register as decorator function."""
cls._dbs[dbname] = subclass
subclass.name = dbname
return subclass
return decorator | 0.006873 |
def use_categories_as_metadata(self):
'''
Returns a TermDocMatrix which is identical to self except the metadata values are now identical to the
categories present.
:return: TermDocMatrix
'''
new_metadata_factory = CSRMatrixFactory()
for i, category_idx in enume... | 0.004154 |
def pip_version_check(session):
"""Check for an update for pip.
Limit the frequency of checks to once per week. State is stored either in
the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
of the pip script path.
"""
import pip # imported here to prevent circular import... | 0.00039 |
def set_reviewing(self, hit_id, revert=None):
"""
Update a HIT with a status of Reviewable to have a status of Reviewing,
or reverts a Reviewing HIT back to the Reviewable status.
Only HITs with a status of Reviewable can be updated with a status of
Reviewing. Similarly, only ... | 0.008897 |
def list_udas(self, database=None, like=None):
"""
Lists all UDAFs associated with a given database
Parameters
----------
database : string
like : string for searching (optional)
"""
if not database:
database = self.current_database
st... | 0.003831 |
def cast(self, **kwargs):
"""Get the cast for a movie specified by id from the API.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('cast')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
... | 0.005848 |
def step(self, action):
"""
Run one frame of the NES and return the relevant observation data.
Args:
action (byte): the bitmap determining which buttons to press
Returns:
a tuple of:
- state (np.ndarray): next frame as a result of the given action
... | 0.00134 |
def fit_quadrature(orth, nodes, weights, solves, retall=False, norms=None, **kws):
"""
Using spectral projection to create a polynomial approximation over
distribution space.
Args:
orth (chaospy.poly.base.Poly):
Orthogonal polynomial expansion. Must be orthogonal for the
... | 0.000902 |
def opp_stats(self, year):
"""Returns a Series (dict-like) of the team's opponent's stats from the
team-season page.
:year: Int representing the season.
:returns: A Series of team stats.
"""
doc = self.get_year_doc(year)
table = doc('table#team_stats')
df... | 0.004796 |
def apply(self, compound, orientation='', compound_port=''):
"""Arrange copies of a Compound as specified by the Pattern.
Parameters
----------
compound
orientation
Returns
-------
"""
compounds = list()
if self.orientations.get(orientat... | 0.002454 |
def find(self, name=None, **attrs):
r"""First descendant node matching criteria.
Returns None if no descendant node found.
:return: descendant node matching criteria
:rtype: Union[None,TexExpr]
>>> from TexSoup import TexSoup
>>> soup = TexSoup(r'''
... \sectio... | 0.003344 |
def _Moran_BV_Matrix_array(variables, w, permutations=0, varnames=None):
"""
Base calculation for MORAN_BV_Matrix
"""
if varnames is None:
varnames = ['x{}'.format(i) for i in range(k)]
k = len(variables)
rk = list(range(0, k - 1))
results = {}
for i in rk:
for j in rang... | 0.00141 |
def read_array(fname, sep=','):
r"""
Convert a CSV file without header into a numpy array of floats.
>>> from openquake.baselib.general import gettemp
>>> print(read_array(gettemp('.1 .2, .3 .4, .5 .6\n')))
[[[0.1 0.2]
[0.3 0.4]
[0.5 0.6]]]
"""
with open(fname) as f:
rec... | 0.001905 |
def _findSwiplWin():
import re
"""
This function uses several heuristics to gues where SWI-Prolog is installed
in Windows. It always returns None as the path of the resource file because,
in Windows, the way to find it is more robust so the SWI-Prolog DLL is
always able to find it.
:return... | 0.001687 |
def generateLatticeFile(self, beamline, filename=None, format='elegant'):
""" generate simulation files for lattice analysis,
e.g. ".lte" for elegant, ".madx" for madx
input parameters:
:param beamline: keyword for beamline
:param filename: name of lte/mad file,
... | 0.002374 |
def is_active(self, key, *instances, **kwargs):
"""
Returns ``True`` if any of ``instances`` match an active switch.
Otherwise returns ``False``.
>>> operator.is_active('my_feature', request) #doctest: +SKIP
"""
try:
default = kwargs.pop('default', False)
... | 0.001321 |
def max_width(self):
"""Get maximum width of progress bar
:rtype: int
:returns: Maximum column width of progress bar
"""
value, unit = float(self._width_str[:-1]), self._width_str[-1]
ensure(unit in ["c", "%"], ValueError,
"Width unit must be either 'c' o... | 0.002436 |
def itemsize(obj, **opts):
'''Return the item size of an object (in bytes).
See function **basicsize** for a description of
the options.
'''
v = _typedefof(obj, **opts)
if v:
v = v.item
return v | 0.004219 |
def convert_response(check_response, project_id):
"""Computes a http status code and message `CheckResponse`
The return value a tuple (code, message, api_key_is_bad) where
code: is the http status code
message: is the message to return
api_key_is_bad: indicates that a given api_key is bad
Arg... | 0.002941 |
def _handle_api(self, handler, handler_args, handler_kwargs):
""" Handle call to subclasses and convert the output to an appropriate value """
try:
status_code, return_value = handler(*handler_args, **handler_kwargs)
except APIError as error:
return error.send()
... | 0.009547 |
def compute_score(self):
"""Calculate the overall test score using the configuration."""
# LOGGER.info("Begin scoring")
cases = self.get_configured_tests() | set(self.result.cases)
scores = DataFrame({"score": 0.0, "max": 1.0},
index=sorted(cases))
self... | 0.000819 |
def list_keywords(self):
''' Return the list of keywords '''
names = []
try:
for n in self.cur.execute("SELECT keyword FROM keyword;").fetchall():
# Strip out leading and trailing whitespaces (can be artifacts of old data)
k = n[0].strip()
... | 0.010204 |
def items(self):
"""
Return a copied list of the property names and values
of this CIM instance.
Each item in the returned list is a tuple of property name (in the
original lexical case) and property value.
The order of properties is preserved.
"""
retur... | 0.005319 |
def schedule_next_requests(self):
"""Schedules a request if available"""
# TODO: While there is capacity, schedule a batch of redis requests.
for req in self.next_requests():
self.crawler.engine.crawl(req, spider=self) | 0.007874 |
def lint(exclude, skip_untracked, commit_only):
# type: (List[str], bool, bool) -> None
""" Lint python files.
Args:
exclude (list[str]):
A list of glob string patterns to test against. If the file/path
matches any of those patters, it will be filtered out.
skip_untr... | 0.001511 |
def _get_split_tasks(args, split_fn, file_key, outfile_i=-1):
"""Split up input files and arguments, returning arguments for parallel processing.
outfile_i specifies the location of the output file in the arguments to
the processing function. Defaults to the last item in the list.
"""
split_args = ... | 0.001826 |
def _get_numeric_status(self, key):
"""Extract the numeric value from the statuses object."""
value = self._get_status(key)
if value and any(i.isdigit() for i in value):
return float(re.sub("[^0-9.]", "", value))
return None | 0.007435 |
def cluster_del_slots(self, slot, *slots):
"""Set hash slots as unbound in receiving node."""
slots = (slot,) + slots
if not all(isinstance(s, int) for s in slots):
raise TypeError("All parameters must be of type int")
fut = self.execute(b'CLUSTER', b'DELSLOTS', *slots)
... | 0.005848 |
def percentage(columns, maximum=100, name=None):
"""
Creates the grammar for a Numeric (N) field storing a percentage and
accepting only the specified number of characters.
It is possible to set the maximum allowed value. By default this is 100
(for 100%), and if modified it is expected to be reduc... | 0.001041 |
def combined_credits(self, **kwargs):
"""
Get the combined (movie and TV) credits for a specific person id.
To get the expanded details for each TV record, call the /credit method
with the provided credit_id. This will provide details about which
episode and/or season the cred... | 0.00542 |
def read(self):
'''Execute the expression and capture its output, similar to backticks
or $() in the shell. This is a wrapper around run() which captures
stdout, decodes it, trims it, and returns it directly.'''
result = self.stdout_capture().run()
stdout_str = decode_with_univer... | 0.005181 |
def kmeans_segmentation(image, k, kmask=None, mrf=0.1):
"""
K-means image segmentation that is a wrapper around `ants.atropos`
ANTsR function: `kmeansSegmentation`
Arguments
---------
image : ANTsImage
input image
k : integer
integer number of classes
kmask : ANTsImag... | 0.0121 |
def _check_model_types(self, models):
""" Check types of passed models for correctness and in case raise exception
:rtype: set
:returns: set of models that are valid for the class"""
if not hasattr(models, "__iter__"):
models = {models}
if not all([isinstance(model, ... | 0.009346 |
def _unparse_entry_record(self, entry):
"""
:type entry: Dict[string, List[string]]
:param entry: Dictionary holding an entry
"""
for attr_type in sorted(entry.keys()):
for attr_value in entry[attr_type]:
self._unparse_attr(attr_type, attr_value) | 0.006369 |
def current_ioloop(io_loop):
'''
A context manager that will set the current ioloop to io_loop for the context
'''
orig_loop = tornado.ioloop.IOLoop.current()
io_loop.make_current()
try:
yield
finally:
orig_loop.make_current() | 0.007407 |
def media_post(self, media_file, mime_type=None, description=None, focus=None):
"""
Post an image. `media_file` can either be image data or
a file name. If image data is passed directly, the mime
type has to be specified manually, otherwise, it is
determined from the file name. `... | 0.004548 |
def add_function(self, func):
""" Record line profiling information for the given Python function.
"""
try:
# func_code does not exist in Python3
code = func.__code__
except AttributeError:
import warnings
warnings.warn("Could not extract a... | 0.003831 |
def delete_user(self, user_id, **kwargs): # noqa: E501
"""Delete a user. # noqa: E501
An endpoint for deleting a user. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/users/{user-id} -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a synchronous ... | 0.001892 |
def filter_redundant(self, ids):
"""
Return all non-redundant ids from a list
"""
sids = set(ids)
for id in ids:
sids = sids.difference(self.ancestors(id, reflexive=False))
return sids | 0.008197 |
def _create(self, **kwargs):
'''Allow creation of draft policy and ability to publish a draft
Draft policies only exist in 12.1.0 and greater versions of TMOS.
But there must be a method to create a draft, then publish it.
:raises: MissingRequiredCreationParameter
'''
... | 0.001582 |
def main():
"""Script that finds and runs flatc built from source."""
if len(sys.argv) < 2:
sys.stderr.write('Usage: run_flatc.py flatbuffers_dir [flatc_args]\n')
return 1
cwd = os.getcwd()
flatc = ''
flatbuffers_dir = sys.argv[1]
for path in FLATC_SEARCH_PATHS:
current = os.path.join(flatbuffer... | 0.020101 |
def _makepretty(printout, stack):
'''
Pretty print the stack trace and environment information
for debugging those hard to reproduce user problems. :)
'''
printout.write('======== Salt Debug Stack Trace =========\n')
traceback.print_stack(stack, file=printout)
printout.write('==============... | 0.002849 |
def dataframe(self):
"""
Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string abbreviation of the
team, such as 'DET'.
"""
fields_to_include = {
'abbreviation': self.abbreviation,
'a... | 0.000615 |
def _FixedSizer(value_size):
"""Like _SimpleSizer except for a fixed-size field. The input is the size
of one value."""
def SpecificSizer(field_number, is_repeated, is_packed):
tag_size = _TagSize(field_number)
if is_packed:
local_VarintSize = _VarintSize
def PackedFieldSize(value):
... | 0.020888 |
def report(self):
"""
Print network statistics.
"""
logging.info("network inputs: %s", " ".join(map(str, self.input_variables)))
logging.info("network targets: %s", " ".join(map(str, self.target_variables)))
logging.info("network parameters: %s", " ".join(map(str, self.al... | 0.012469 |
def predict_mhcii_binding(job, peptfile, allele, univ_options, mhcii_options):
"""
Predict binding for each peptide in `peptfile` to `allele` using the IEDB mhcii binding
prediction tool.
:param toil.fileStore.FileID peptfile: The input peptide fasta
:param str allele: Allele to predict binding aga... | 0.004124 |
def create_marker_index(self):
"""
Create the index that will keep track of the tasks if necessary.
"""
if not self.es.indices.exists(index=self.marker_index):
self.es.indices.create(index=self.marker_index) | 0.007968 |
def _merge(self, old, new, use_equals=False):
"""Helper to merge which handles merging one value."""
if old is None:
return new
if new is None:
return old
if (old == new) if use_equals else (old is new):
return old
raise ValueError("Incompatible values: %s != %s" % (old, new)) | 0.012698 |
def is_os(name, version_id=None):
'''Return True if OS name in /etc/lsb-release of host given by fabric param
`-H` is the same as given by argument, False else.
If arg version_id is not None only return True if it is the same as in
/etc/lsb-release, too.
Args:
name: 'Debian GNU/Linux', 'Ub... | 0.001235 |
def get_region_products(self, region):
"""获得指定区域的产品信息
Args:
- region: 区域,如:"nq"
Returns:
返回该区域的产品信息,若失败则返回None
"""
regions, retInfo = self.list_regions()
if regions is None:
return None
for r in regions:
if r.get... | 0.005263 |
def format_field(self, value, format_spec):
"""Override :meth:`string.Formatter.format_field` to have our
default format_spec for :class:`datetime.Datetime` objects, and to
let None yield an empty string rather than ``None``."""
if isinstance(value, datetime) and not format_spec:
... | 0.004115 |
def filtered_notebook_metadata(notebook):
"""Notebook metadata, filtered for metadata added by Jupytext itself"""
metadata = copy(notebook.metadata)
metadata = filter_metadata(metadata,
notebook.metadata.get('jupytext', {}).get('notebook_metadata_filter'),
... | 0.004525 |
def writeXMLFile(filename, content):
""" Used only for debugging to write out intermediate files"""
xmlfile = open(filename, 'w')
# pretty print
content = etree.tostring(content, pretty_print=True)
xmlfile.write(content)
xmlfile.close() | 0.003846 |
def expose(self, key=None):
"""
Expose the decorated method for this L{Exposer} with the given key. A
method which is exposed will be able to be retrieved by this
L{Exposer}'s C{get} method with that key. If no key is provided, the
key is the method name of the exposed method.
... | 0.001569 |
def validateArchiveList(archiveList):
""" Validates an archiveList.
An ArchiveList must:
1. Have at least one archive config. Example: (60, 86400)
2. No archive may be a duplicate of another.
3. Higher precision archives' precision must evenly divide all lower precision archives' precision.
4. Lower precisi... | 0.013908 |
def ticket_skips(self, ticket_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/ticket_skips#list-skips-for-the-current-account"
api_path = "/api/v2/tickets/{ticket_id}/skips.json"
api_path = api_path.format(ticket_id=ticket_id)
return self.call(api_path, **kwargs) | 0.009615 |
def add_answer_at_time(self, record, now):
"""Adds an answer if if does not expire by a certain time"""
if record is not None:
if now == 0 or not record.is_expired(now):
self.answers.append((record, now))
if record.rrsig is not None:
self.a... | 0.00565 |
def update_environment(self, environment_name, description=None, option_settings=[], tier_type=None, tier_name=None,
tier_version='1.0'):
"""
Updates an application version
"""
out("Updating environment: " + str(environment_name))
messages = self.ebs.va... | 0.008511 |
def interpolate_logscale_single(start, end, coefficient):
""" Cosine interpolation """
return np.exp(np.log(start) + (np.log(end) - np.log(start)) * coefficient) | 0.005917 |
def open_group(store=None, mode='a', cache_attrs=True, synchronizer=None, path=None,
chunk_store=None):
"""Open a group using file-mode-like semantics.
Parameters
----------
store : MutableMapping or string, optional
Store or path to directory in file system or name of zip file.
... | 0.00072 |
def __tdfs(j, k, head, next, post, stack):
"""
Depth-first search and postorder of a tree rooted at node j.
"""
top = 0
stack[0] = j
while (top >= 0):
p = stack[top]
i = head[p]
if i == -1:
top -= 1
post[k] = p
k += 1
else:
... | 0.002457 |
def main(fixer_pkg, args=None):
"""Main program.
Args:
fixer_pkg: the name of a package where the fixers are located.
args: optional; a list of command line arguments. If omitted,
sys.argv[1:] is used.
Returns a suggested exit status (0, 1, 2).
"""
# Set up option par... | 0.000637 |
def clone(self, data=None, shared_data=True, new_type=None, link=True,
*args, **overrides):
"""Clones the object, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
... | 0.003593 |
def markAsDelivered(self, thread_id, message_id):
"""
Mark a message as delivered
:param thread_id: User/Group ID to which the message belongs. See :ref:`intro_threads`
:param message_id: Message ID to set as delivered. See :ref:`intro_threads`
:return: Whether the request was s... | 0.006757 |
def main():
"""
Example application that opens a device that has been exposed to the network
with ser2sock or similar serial-to-IP software.
"""
try:
# Retrieve an AD2 device that has been exposed with ser2sock on localhost:10000.
device = AlarmDecoder(SocketDevice(interface=(HOSTNAM... | 0.005245 |
def get_all_file_report_pages(self, query):
""" Get File Report (All Pages).
:param query: a VirusTotal Intelligence search string in accordance with the file search documentation.
:return: All JSON responses appended together.
"""
responses = []
r = self.get_hashes_from... | 0.004545 |
def login(self):
"""
Perform IAM cookie based user login.
"""
access_token = self._get_access_token()
try:
super(IAMSession, self).request(
'POST',
self._session_url,
headers={'Content-Type': 'application/json'},
... | 0.00369 |
def geometrize_shapes(
shapes: DataFrame, *, use_utm: bool = False
) -> DataFrame:
"""
Given a GTFS shapes DataFrame, convert it to a GeoPandas
GeoDataFrame and return the result.
The result has a ``'geometry'`` column of WGS84 LineStrings
instead of the columns ``'shape_pt_sequence'``, ``'shape... | 0.000952 |
def artist_undelete(self, artist_id):
"""Lets you undelete artist (Requires login) (UNTESTED) (Only Builder+).
Parameters:
artist_id (int):
"""
return self._get('artists/{0}/undelete.json'.format(artist_id),
method='POST', auth=True) | 0.009901 |
def _em_conversion(orig_units, conv_data, to_units=None, unit_system=None):
"""Convert between E&M & MKS base units.
If orig_units is a CGS (or MKS) E&M unit, conv_data contains the
corresponding MKS (or CGS) unit and scale factor converting between them.
This must be done by replacing the expression o... | 0.001092 |
def _inject():
""" Inject functions and constants from PyOpenGL but leave out the
names that are deprecated or that we provide in our API.
"""
# Get namespaces
NS = globals()
GLNS = _GL.__dict__
# Get names that we use in our API
used_names = []
used_names.extend([names[0] ... | 0.005008 |
def InitFromApiFlow(self, f, cron_job_id=None):
"""Shortcut method for easy legacy cron jobs support."""
if f.flow_id:
self.run_id = f.flow_id
elif f.urn:
self.run_id = f.urn.Basename()
self.started_at = f.started_at
self.cron_job_id = cron_job_id
flow_state_enum = api_plugins_flow.... | 0.006944 |
def relevent_issue(issue, after):
"""Returns True iff this issue is something we should show in the changelog."""
return (closed_issue(issue, after) and
issue_completed(issue) and
issue_section(issue)) | 0.008584 |
def _parse_create_args(client, args):
"""Converts CLI arguments to args for VSManager.create_instance.
:param dict args: CLI arguments
"""
data = {
"hourly": args.get('billing', 'hourly') == 'hourly',
"cpus": args.get('cpu', None),
"ipv6": args.get('ipv6', None),
"disks"... | 0.001321 |
def verify(self, obj):
"""Verify that the object conforms to this verifier's schema
Args:
obj (object): A python object to verify
Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thrown with at least the reaso... | 0.005904 |
def resolve(object):
"""Look up the name of a source using a resolver"""
import re
sesame_cmd = 'curl -s http://cdsweb.u-strasbg.fr/viz-bin/nph-sesame/-oI?'+string.replace(object,' ','')
f = os.popen(sesame_cmd)
lines = f.readlines()
f.close()
for line in lines:
if re.searc... | 0.015625 |
def _get_service_state(service_id: str):
"""Get the Service state object for the specified id."""
LOG.debug('Getting state of service %s', service_id)
services = get_service_id_list()
service_ids = [s for s in services if service_id in s]
if len(service_ids) != 1:
ret... | 0.00404 |
def blockmix_salsa8(BY, Yi, r):
"""Blockmix; Used by SMix"""
start = (2 * r - 1) * 16
X = BY[start:start+16] # BlockMix - 1
tmp = [0]*16
for i in xrange(2 * r): # BlockMix - 2
#blockxor(BY, i * 16, X, 0, 16) # BlockMix -... | 0.006878 |
def hidden_cursor(self):
"""Return a context manager that hides the cursor while inside it and
makes it visible on leaving."""
self.stream.write(self.hide_cursor)
try:
yield
finally:
self.stream.write(self.normal_cursor) | 0.007042 |
def _getPredictedField(options):
""" Gets the predicted field and it's datatype from the options dictionary
Returns: (predictedFieldName, predictedFieldType)
"""
if not options['inferenceArgs'] or \
not options['inferenceArgs']['predictedField']:
return None, None
predictedField = options['inferen... | 0.017926 |
def serialize_math(ctx, document, elem, root):
"""Serialize math element.
Math objects are not supported at the moment. This is wht we only show error message.
"""
_div = etree.SubElement(root, 'span')
if ctx.options['embed_styles']:
_div.set('style', 'border: 1px solid red')
_div.text... | 0.004435 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.