text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def from_dict(cls, eas_from_nios):
"""Converts extensible attributes from the NIOS reply."""
if not eas_from_nios:
return
return cls({name: cls._process_value(ib_utils.try_value_to_bool,
eas_from_nios[name]['value'])
fo... | 0.005797 |
def to_flags(value):
"""Return a (flags, ednsflags) tuple which encodes the rcode.
@param value: the rcode
@type value: int
@raises ValueError: rcode is < 0 or > 4095
@rtype: (int, int) tuple
"""
if value < 0 or value > 4095:
raise ValueError('rcode must be >= 0 and <= 4095')
v... | 0.002577 |
def determine_reach_subtype(event_name):
"""Returns the category of reach rule from the reach rule instance.
Looks at a list of regular
expressions corresponding to reach rule types, and returns the longest
regexp that matches, or None if none of them match.
Parameters
----------
evidence ... | 0.001189 |
def __initialize_ui(self):
"""
Initializes the Widget ui.
"""
self.__clear_button.setCursor(Qt.ArrowCursor)
if self.__ui_clear_image and self.__ui_clear_clicked_image:
pixmap = QPixmap(self.__ui_clear_image)
clicked_pixmap = QPixmap(self.__ui_clear_clicke... | 0.0059 |
def _load_hangul_syllable_types():
"""
Helper function for parsing the contents of "HangulSyllableType.txt" from the Unicode Character Database (UCD) and
generating a lookup table for determining whether or not a given Hangul syllable is of type "L", "V", "T", "LV" or
"LVT". For more info on the UCD, s... | 0.006421 |
def run(action: str, args: dict) -> int:
"""
Runs the specified command action and returns the return status code
for exit.
:param action:
The action to run
:param args:
The arguments parsed for the specified action
"""
if args.get('show_version_info'):
return ru... | 0.002821 |
def gen_mapname():
""" Generate a uniq mapfile pathname. """
filepath = None
while (filepath is None) or (os.path.exists(os.path.join(config['mapfiles_dir'], filepath))):
filepath = '%s.map' % _gen_string()
return filepath | 0.00813 |
def from_datetime(cls, generation_time):
"""Create a dummy ObjectId instance with a specific generation time.
This method is useful for doing range queries on a field
containing :class:`ObjectId` instances.
.. warning::
It is not safe to insert a document containing an Objec... | 0.001343 |
def _hide_tick_lines_and_labels(axis):
"""
Set visible property of ticklines and ticklabels of an axis to False
"""
for item in axis.get_ticklines() + axis.get_ticklabels():
item.set_visible(False) | 0.004525 |
def multithread_download_photos(photos):
"""Use multiple threads to download photos
:param photos: The photos to be downloaded
:type photos: list of dicts
"""
from concurrent import futures
global counter
counter = len(photos)
cpu_num = multiprocessing.cpu_count()
with futures.Threa... | 0.002237 |
def view_path(self):
"""
It returns view_path as string like: 'app_name.module_mane.func_name'
"""
return u"{0}.{1}.{2}".format(self.app_name, self.module_name, self.func_name) | 0.014423 |
def hget(self, key):
"""Read data from Redis for the provided key.
Args:
key (string): The key to read in Redis.
Returns:
(any): The response data from Redis.
"""
data = self.r.hget(self.hash, key)
if data is not None and not isinstance(data, str... | 0.004963 |
def smart_generic_inlineformset_factory(model, request, form=ModelForm, formset=BaseGenericInlineFormSet,
ct_field='content_type', fk_field='object_id', fields=None, exclude=None,
extra=3, can_order=False, can_delete=True, min_num=None, max... | 0.003687 |
def dead(name,
enable=None,
sig=None,
init_delay=None,
**kwargs):
'''
Ensure that the named service is dead by stopping the service if it is running
name
The name of the init or rc script used to manage the service
enable
Set the service to be enable... | 0.001543 |
def get_uri_template(urlname, args=None, prefix=""):
'''
Utility function to return an URI Template from a named URL in django
Copied from django-digitalpaper.
Restrictions:
- Only supports named urls! i.e. url(... name="toto")
- Only support one namespace level
- Only returns the first URL... | 0.00042 |
def LockedWrite(self, cache_data):
"""Acquire an interprocess lock and write a string.
This method safely acquires the locks then writes a string
to the cache file. If the string is written successfully
the function will return True, if the write fails for any
reason it will ret... | 0.002151 |
def radio(self, radio):
'''
Get songs belong to a specific genre.
:param radio: genre to listen to
:rtype: a :class:`Radio` object
Genres:
This list is incomplete because there isn't an English translation for
some genres.
Please look at the sources for... | 0.000496 |
def run_select_calculation(self):
"""Run the CifSelectCalculation on the CifData output node of the CifFilterCalculation."""
inputs = {
'cif': self.ctx.cif,
'code': self.inputs.cif_select,
'parameters': self.inputs.cif_select_parameters,
'metadata': {
... | 0.006547 |
def send_stderr(cls, sock, payload):
"""Send the Stderr chunk over the specified socket."""
cls.write_chunk(sock, ChunkType.STDERR, payload) | 0.006757 |
def create_function(FunctionName=None, Runtime=None, Role=None, Handler=None, Code=None, Description=None, Timeout=None, MemorySize=None, Publish=None, VpcConfig=None, DeadLetterConfig=None, Environment=None, KMSKeyArn=None, TracingConfig=None, Tags=None):
"""
Creates a new Lambda function. The function metadat... | 0.005204 |
def register(self, app, options):
"""Register the blueprint to the mach9 app."""
url_prefix = options.get('url_prefix', self.url_prefix)
# Routes
for future in self.routes:
# attach the blueprint name to the handler so that it can be
# prefixed properly in the r... | 0.001176 |
def setPadMode(self, mode):
"""Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5"""
_baseDes.setPadMode(self, mode)
for key in (self.__key1, self.__key2, self.__key3):
key.setPadMode(mode) | 0.028037 |
def get(self, key, timeout=None):
"""Given a key, returns an element from the redis table"""
key = self.pre_identifier + key
# Check to see if we have this key
unpickled_entry = self.client.get(key)
if not unpickled_entry:
# No hit, return nothing
return N... | 0.002448 |
def get_abstracts(self, refresh=True):
"""Return a list of ScopusAbstract objects using ScopusSearch."""
return [ScopusAbstract(eid, refresh=refresh)
for eid in self.get_document_eids(refresh=refresh)] | 0.008584 |
def prompt(message, default=None, strip=True, suffix=' '):
""" Print a message and prompt user for input. Return user input. """
if default is not None:
prompt_text = "{0} [{1}]{2}".format(message, default, suffix)
else:
prompt_text = "{0}{1}".format(message, suffix)
input_value = get_i... | 0.002045 |
def require(*mods):
"""Simple decorator for requiring names to be importable.
Examples
--------
In [1]: @require('numpy')
...: def norm(a):
...: import numpy
...: return numpy.linalg.norm(a,2)
"""
names = []
for mod in mods:
if isinstance(mod, M... | 0.012007 |
def transform_paragraph(self, paragraph, epochs=50, ignore_missing=False):
"""
Transform an iterable of tokens into its vector representation
(a paragraph vector).
Experimental. This will return something close to a tf-idf
weighted average of constituent token vectors by fitting... | 0.001007 |
def neg_log_likelihood(self, x, standard=False):
""" Calculate Log Likelihood with particular mean and std
x must be 2D. [batch_size * eqsamples* iwsamples, num_latent]
"""
x_reshape = tf.reshape(x, [self.batch_size, self.eq_samples, self.iw_samples, self.num_latent])
c = - 0.5 *... | 0.005865 |
def _compile_lock(self, query, value):
"""
Compile the lock into SQL
:param query: A QueryBuilder instance
:type query: QueryBuilder
:param value: The lock value
:type value: bool or str
:return: The compiled lock
:rtype: str
"""
if isin... | 0.004008 |
def __patch_pipe_methods(tango_device_klass, pipe):
"""
Checks if the read and write methods have the correct signature.
If a read/write method doesn't have a parameter (the traditional
Pipe), then the method is wrapped into another method to make
this work.
:param tango_device_klass: a DeviceI... | 0.001631 |
def _cmd_create(self):
"""Create a migration in the current or new revision folder
"""
assert self._message, "need to supply a message for the \"create\" command"
if not self._revisions:
self._revisions.append("1")
# get the migration folder
rev_folder = self... | 0.003456 |
def color_print(s, color=None, highlight=None, end='\n', file=sys.stdout,
**kwargs):
"""
From http://stackoverflow.com/a/287944/610569
See also https://gist.github.com/Sheljohn/68ca3be74139f66dbc6127784f638920
"""
if color in palette and color != 'default':
s = palette[color]... | 0.003072 |
def from_properties(cls, angle, axis, invert, translation):
"""Initialize a transformation based on the properties"""
rot = Rotation.from_properties(angle, axis, invert)
return Complete(rot.r, translation) | 0.008734 |
def exit(code=0, text=''):
"""Exit and print text (if defined) to stderr if code > 0 or stdout
otherwise.
>>> exit(code=1, text='Invalid directory path')
"""
if not isinstance(text, basestring_type):
text = unicode_type(text)
if code > 0:
if text:
if not isinstance... | 0.001942 |
def public_ip_addresses_list_all(**kwargs):
'''
.. versionadded:: 2019.2.0
List all public IP addresses within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_network.public_ip_addresses_list_all
'''
result = {}
netconn = __utils__['azurearm.get_client']... | 0.00295 |
def attach(self, upstream):
"""Attach an upstream to the last upstream. Can be removed with detach"""
if upstream == self.last_upstream():
raise Exception("Can't attach a cache to itself")
self._prior_upstreams.append(self.last_upstream())
self.last_upstream().upstream = u... | 0.009174 |
def match_rules_context(tree, rules, parent_context={}):
"""Recursively matches a Tree structure with rules and returns context
Args:
tree (Tree): Parsed tree structure
rules (dict): See match_rules
parent_context (dict): Context of parent call
Returns:
dict: Context matched... | 0.002237 |
def FileHeader(self, zip64=None):
"""Return the per-file header as a string."""
dt = self.date_time
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
if self.flag_bits & 0x08:
# Set these to zero because we write them... | 0.001485 |
def setup(executor):
"""Set up log, process and signal handlers"""
# pylint: disable=unused-argument
def signal_handler(signal_to_handle, frame):
# We would do nothing here but just exit
# Just catch the SIGTERM and then cleanup(), registered with atexit, would invoke
Log.info('signal_handler invoked ... | 0.013199 |
def _getadvanced(self, index):
"""
Advanced indexing (for sets, lists, or ndarrays).
"""
index = [asarray(i) for i in index]
shape = index[0].shape
if not all([i.shape == shape for i in index]):
raise ValueError("shape mismatch: indexing arrays could not be br... | 0.00252 |
def _generate_date_indicators(catalog, tolerance=0.2, only_numeric=False):
"""Genera indicadores relacionados a las fechas de publicación
y actualización del catálogo pasado por parámetro. La evaluación de si
un catálogo se encuentra actualizado o no tiene un porcentaje de
tolerancia hasta que se lo con... | 0.000242 |
def isspecword(somestr):
"""
Checks that some string is a special word
:param str somestr:
It is some string that will be checked for special word.
The special word is a string that contains only alphabetic characters,
its length not less 1 character and not more 2 characters and
a... | 0.052899 |
def plot_phase_offsets(dio_cross,chan_per_coarse=8,feedtype='l',ax1=None,ax2=None,legend=True,**kwargs):
'''
Plots the calculated phase offsets of each coarse channel along with
the UV (or QU) noise diode spectrum for comparison
'''
#Get ON-OFF ND spectra
Idiff,Qdiff,Udiff,Vdiff,freqs = get_diff... | 0.038385 |
def get_uid(value):
"""Takes a brain or object and returns a valid UID.
In this case, the object may come from portal_archivist, so we will
need to do a catalog query to get the UID of the current version
"""
if not value:
return ''
# Is value a brain?
if ICatalogBrain.providedBy(val... | 0.000971 |
def field_date_to_json(self, day):
"""Convert a date to a date triple."""
if isinstance(day, six.string_types):
day = parse_date(day)
return [day.year, day.month, day.day] if day else None | 0.008929 |
def __get_default_location():
"""
Returns the current process's default cache location folder.
The folder is determined lazily on first call.
"""
if not FileCache.__default_location:
tmp = tempfile.mkdtemp("suds-default-cache")
FileCache.__default_locati... | 0.00432 |
def FreezeTimestamp(self):
"""Freezes the timestamp used for resolve/delete database queries.
Frozen timestamp is used to consistently limit the datastore resolve and
delete queries by time range: from 0 to self.frozen_timestamp. This is
done to avoid possible race conditions, like accidentally deletin... | 0.001852 |
def fill_subparser(subparser):
"""Sets up a subparser to download audio of YouTube videos.
Adds the compulsory `--youtube-id` flag.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `youtube_audio` command.
"""
subparser.add_argument(
... | 0.001957 |
def typed_hash_key(*args, **kwargs):
"""Return a typed cache key for the specified hashable arguments."""
key = hash_key(*args, **kwargs)
key += tuple(type(v) for v in args)
key += tuple(type(v) for _, v in sorted(kwargs.items()))
return key | 0.003817 |
def version():
'''
Return the version of the FreeType library being used as a tuple of
( major version number, minor version number, patch version number )
'''
amajor = FT_Int()
aminor = FT_Int()
apatch = FT_Int()
library = get_handle()
FT_Library_Version(library, byref(amajor), byre... | 0.002506 |
def proxy_arp(self, **kwargs):
"""Set interface administrative state.
Args:
int_type (str): Type of interface. (gigabitethernet,
tengigabitethernet, etc).
name (str): Name of interface. (1/0/5, 1/0/10, etc).
enabled (bool): Is proxy-arp enabled? (True... | 0.000526 |
def to_frame(self, slot=1):
"""
Return the current configuration as a YubiKeyFrame object.
"""
data = self.to_string()
payload = data.ljust(64, yubico_util.chr_byte(0x0))
if slot is 1:
if self._update_config:
command = SLOT.UPDATE1
... | 0.002695 |
def score(self, x, y, w=None, **kwargs):
'''Compute R^2 coefficient of determination for a given labeled input.
Parameters
----------
x : ndarray (num-examples, num-inputs)
An array containing data to be fed into the network. Multiple
examples are arranged as row... | 0.003988 |
def next_item(self):
"""Get a single item from the queue."""
queue = self.queue
try:
item = queue.get(block=True, timeout=5)
return item
except Exception:
return None | 0.008547 |
def group(self):
"""
Returns the periodic table group of the element.
"""
z = self.Z
if z == 1:
return 1
if z == 2:
return 18
if 3 <= z <= 18:
if (z - 2) % 8 == 0:
return 18
elif (z - 2) % 8 <= 2:
... | 0.002759 |
def terminate(self, include_watchman=True):
"""Terminates pantsd and watchman.
N.B. This should always be called under care of the `lifecycle_lock`.
"""
super(PantsDaemon, self).terminate()
if include_watchman:
self.watchman_launcher.terminate() | 0.007353 |
def fetch_git_package(self, config):
"""Make a remote git repository available for local use.
Args:
config (dict): git config dictionary
"""
# only loading git here when needed to avoid load errors on systems
# without git installed
from git import Repo
... | 0.001167 |
def run_setup(script_path, egg_base=None):
# type: (str, Optional[str]) -> Distribution
"""Run a `setup.py` script with a target **egg_base** if provided.
:param S script_path: The path to the `setup.py` script to run
:param Optional[S] egg_base: The metadata directory to build in
:raises FileNotFo... | 0.000408 |
def on_key_down(self, event):
"""
If user does command v,
re-size window in case pasting has changed the content size.
"""
keycode = event.GetKeyCode()
meta_down = event.MetaDown() or event.GetCmdDown()
if keycode == 86 and meta_down:
# treat it as if ... | 0.005305 |
def getCfgFilesInDirForTask(aDir, aTask, recurse=False):
""" This is a specialized function which is meant only to keep the
same code from needlessly being much repeated throughout this
application. This must be kept as fast and as light as possible.
This checks a given directory for .cfg f... | 0.001098 |
def generate_skip_gram_data_set(self, token_list):
'''
Generate the Skip-gram's pair.
Args:
token_list: The list of tokens.
Returns:
zip of Tuple(Training N-gram data, Target N-gram data)
'''
n_gram_tuple_zip = self.generate_tuple_z... | 0.003623 |
def getMapScale(self, latitude, level, dpi=96):
'''
returns the map scale on the dpi of the screen
'''
dpm = dpi / 0.0254 # convert to dots per meter
return self.getGroundResolution(latitude, level) * dpm | 0.008163 |
def escape(self):
"""Determine whether or not to escape content of this class.
This defaults to `True` for most classes.
"""
if self._escape is not None:
return self._escape
if self._default_escape is not None:
return self._default_escape
return T... | 0.006192 |
def dft_postprocess_data(arr, real_grid, recip_grid, shift, axes,
interp, sign='-', op='multiply', out=None):
"""Post-process the Fourier-space data after DFT.
This function multiplies the given data with the separable
function::
q(xi) = exp(+- 1j * dot(x[0], xi)) * s * ph... | 0.000183 |
def write_min_max(self, file):
""" Writes minimum and maximum values to a table.
"""
report = CaseReport(self.case)
col1_header = "Attribute"
col1_width = 19
col2_header = "Minimum"
col3_header = "Maximum"
col_width = 22
sep = "="*col1_width +... | 0.007782 |
def geohash(self, key, member, *members, **kwargs):
"""Returns members of a geospatial index as standard geohash strings.
:rtype: list[str or bytes or None]
"""
return self.execute(
b'GEOHASH', key, member, *members, **kwargs
) | 0.007143 |
def show_tracebacks(self):
""" Show tracebacks """
if self.broker.tracebacks:
for tb in self.broker.tracebacks.values():
# tb = "Traceback {0}".format(str(tb))
self.logit(str(tb), self.pid, self.user, "insights-run", logging.ERROR) | 0.010309 |
def dump_links(self, o):
"""Dump links."""
return {
'self': url_for('.bucket_api', bucket_id=o.id, _external=True),
'versions': url_for(
'.bucket_api', bucket_id=o.id, _external=True) + '?versions',
'uploads': url_for(
'.bucket_api', bu... | 0.005362 |
def cancel_operation(
self, name, retry=gapic_v1.method.DEFAULT, timeout=gapic_v1.method.DEFAULT
):
"""Starts asynchronous cancellation on a long-running operation.
The server makes a best effort to cancel the operation, but success is
not guaranteed. Clients can use :meth:`get_oper... | 0.001704 |
def viterbi_binary(prob, transition, p_state=None, p_init=None, return_logp=False):
'''Viterbi decoding from binary (multi-label), discriminative state predictions.
Given a sequence of conditional state predictions `prob[s, t]`,
indicating the conditional likelihood of state `s` being active
conditiona... | 0.004106 |
def listRuns(self, run_num=-1, logical_file_name="", block_name="", dataset=""):
"""
API to list all runs in DBS. At least one parameter is mandatory.
:param logical_file_name: List all runs in the file
:type logical_file_name: str
:param block_name: List all runs in the block
... | 0.007994 |
def _fugacity(T, P, x):
"""Fugacity equation for humid air
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
x : float
Mole fraction of water-vapor, [-]
Returns
-------
fv : float
fugacity coefficient, [MPa]
Notes
--... | 0.000686 |
def as_field_error(node, secid):
""" convert a fieldExceptions element to a FieldError or FieldError array """
assert node.name() == 'fieldExceptions'
if node.isArray():
return [XmlHelper.as_field_error(node.getValue(_), secid) for _ in range(node.numValues())]
else:
... | 0.005637 |
def manipulate(self, stored_instance, component_instance):
"""
Stores the given StoredInstance bean.
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance
"""
# Store the stored instance...
self._ipopo_instan... | 0.004619 |
def to_dot(self) -> str:
"""
Provide a '.dot' representation of all State in the register.
"""
txt = ""
txt += "digraph S%d {\n" % id(self)
if self.label is not None:
txt += '\tlabel="%s";\n' % (self.label + '\l').replace('\n', '\l')
txt += "\trankdir=... | 0.007194 |
def parsed_whois(self, query, **kwargs):
"""Pass in a domain name"""
return self._results('parsed-whois', '/v1/{0}/whois/parsed'.format(query), cls=ParsedWhois, **kwargs) | 0.016129 |
def main():
"""Budou main method for the command line tool.
"""
args = docopt(__doc__)
if args['--version']:
print(__version__)
sys.exit()
result = parse(
args['<source>'],
segmenter=args['--segmenter'],
language=args['--language'],
classname=args['--classname'])
print(resul... | 0.020115 |
def set_log_file_maximum_size(self, logFileMaxSize):
"""
Set the log file maximum size in megabytes
:Parameters:
#. logFileMaxSize (number): The maximum size in Megabytes of a logging file.
Once exceeded, another logging file as logFileBasename_N.logFileExtension
... | 0.007645 |
def animate(self, animation, static, score, best, appear):
"""Handle animation."""
# Create a surface of static parts in the animation.
surface = pygame.Surface((self.game_width, self.game_height), 0)
surface.fill(self.BACKGROUND)
# Draw all static tiles.
for y in range... | 0.00438 |
async def _create_connection(self, req: 'ClientRequest',
traces: List['Trace'],
timeout: 'ClientTimeout') -> ResponseHandler:
"""Create connection.
Has same keyword arguments as BaseEventLoop.create_connection.
"""
if req... | 0.007143 |
def area(poly):
"""Calculation of zone area"""
poly_xy = []
num = len(poly)
for i in range(num):
poly[i] = poly[i][0:2] + (0,)
poly_xy.append(poly[i])
return surface.area(poly) | 0.004717 |
def segment_area(self):
'''Returns the area of the corresponding arc segment.
>>> Arc((0,0), 2, 0, 360, True).segment_area()
12.566...
>>> Arc((0,0), 2, 0, 180, True).segment_area()
6.283...
>>> Arc((0,0), 2, 0, 90, True).segment_area()
1.14159...
... | 0.004658 |
def show_cursor(self, show):
"""Show or hide the cursor. Cursor is shown if show is True."""
if show:
self.displaycontrol |= LCD_CURSORON
else:
self.displaycontrol &= ~LCD_CURSORON
self.write8(LCD_DISPLAYCONTROL | self.displaycontrol) | 0.006873 |
def _get_stddevs(self, stddev_types, rrup):
"""
Return standard deviations as defined in equation 3.5.5-2 page 151
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
for stddev_type in stddev_types)
std = np.zeros_like(rrup)
std[rru... | 0.0033 |
def predict_array(self, arr):
"""
Args:
arr: a numpy array to be used as input to the model for prediction purposes
Returns:
a numpy array containing the predictions from the model
"""
if not isinstance(arr, np.ndarray): raise OSError(f'Not valid numpy arr... | 0.012438 |
def graph_from_dataframe(
dataframe,
threshold_by_percent_unique=0.1,
threshold_by_count_unique=None,
node_id_columns=[],
node_property_columns=[],
edge_property_columns=[],
node_type_key="type",
edge_type_key="type",
collapse_edges=True,
edge_agg_key="weight",
):
"""
Bui... | 0.000139 |
def fso_makedirs(self, path, mode=None):
'overlays os.makedirs()'
path = self.abs(path)
cur = '/'
segments = path.split('/')
for idx, seg in enumerate(segments):
cur = os.path.join(cur, seg)
try:
st = self.fso_stat(cur)
except OSError:
st = None
if st is None:... | 0.013035 |
def dot(x_gpu, y_gpu, transa='N', transb='N', handle=None, target=None):
"""
Dot product of two arrays.
For 1D arrays, this function computes the inner product. For 2D
arrays of shapes `(m, k)` and `(k, n)`, it computes the matrix
product; the result has shape `(m, n)`.
Parameters
--------... | 0.001039 |
def stats_per36(self, kind='R', summary=False):
"""Returns a DataFrame of per-36-minutes stats."""
return self._get_stats_table('per_minute', kind=kind, summary=summary) | 0.010811 |
def to_tikz(self, line, circuit, end=None):
"""
Generate the TikZ code for one line of the circuit up to a certain
gate.
It modifies the circuit to include only the gates which have not been
drawn. It automatically switches to other lines if the gates on those
lines have... | 0.003436 |
def get_ordered_options(self, hidden=False):
"""
:param hidden: whether to return hidden option
:type hidden: bool
:returns: **ordered** list of options pre-serialised (as_dict)
:rtype: list `[opt_dict, ...]`
"""
return [opt.as_dict() for opt in self.options.value... | 0.01 |
def on_config_value_changed(self, config_m, prop_name, info):
"""Callback when a config value has been changed
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config ... | 0.004435 |
def is_internet_available(ips=CONNECTION_IPS, timeout=1.0):
"""
Returns if an internet connection is available.
:param ips: Address ips to check against.
:type ips: list
:param timeout: Timeout in seconds.
:type timeout: int
:return: Is internet available.
:rtype: bool
"""
whil... | 0.001684 |
def _gti_dirint_gte_90_kt_prime(aoi, solar_zenith, solar_azimuth, times,
kt_prime):
"""
Determine kt' values to be used in GTI-DIRINT AOI >= 90 deg case.
See Marion 2015 Section 2.2.
For AOI >= 90 deg: average of the kt_prime values for 65 < AOI < 80
in each day's mo... | 0.000571 |
def _show_feedback_label(self, message, seconds=None):
"""Display a message in lbl_feedback, which times out after some
number of seconds.
"""
if seconds is None:
seconds = CONFIG['MESSAGE_DURATION']
logger.debug('Label feedback: "{}"'.format(message))
self.... | 0.003846 |
def fit(self, min_ndata_factor=3, max_poly_order_factor=5, min_poly_order=2):
"""
Fit the input data to the 'numerical eos', the equation of state employed
in the quasiharmonic Debye model described in the paper:
10.1103/PhysRevB.90.174107.
credits: Cormac Toher
Args:
... | 0.001123 |
def exportdb(outdir):
"""Export all anchore images to JSON files"""
ecode = 0
try:
imgdir = os.path.join(outdir, "images")
feeddir = os.path.join(outdir, "feeds")
storedir = os.path.join(outdir, "storedfiles")
for d in [outdir, imgdir, feeddir, storedir]:
if not ... | 0.002079 |
def _compute_comparator(string, idx):
# type: (str, int) -> Optional[Callable[[Any, Any], bool]]
"""
Tries to compute the LDAP comparator at the given index
Valid operators are :
* = : equality
* <= : less than
* >= : greater than
* ~= : approximate
:param string: A LDAP filter st... | 0.000828 |
def _run(self, cmd):
"""
Helper function to run commands
Parameters
----------
cmd : list
Arguments to git command
"""
# This is here in case the .gitconfig is not accessible for
# some reason.
environ = os.environ.copy()
... | 0.006124 |
def delete_features(host_name, client_name, client_pass, feature_names=None):
"""
Remove a number of numerical features in the client. If a list is not provided, remove all features.
Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted.
- cli... | 0.00354 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.