text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def build(cls, data, *args, **kwargs):
"""
Constructs a classification or regression tree in a single batch by
analyzing the given data.
"""
assert isinstance(data, Data)
if data.is_continuous_class:
fitness_func = gain_variance
else:
fitne... | 0.00431 |
def pb_id(self, pb_id: str):
"""Set the PB Id for this device."""
# FIXME(BMo) instead of creating the object to check if the PB exists
# use a method on PB List?
# ProcessingBlock(pb_id)
self.set_state(DevState.ON)
self._pb_id = pb_id | 0.006803 |
def is_prime( n ):
"""Return True if x is prime, False otherwise.
We use the Miller-Rabin test, as given in Menezes et al. p. 138.
This test is not exact: there are composite values n for which
it returns True.
In testing the odd numbers from 10000001 to 19999999,
about 66 composites got past the first te... | 0.036541 |
def create_from_table(cls, tab_e):
"""
Parameters
----------
tab_e : `~astropy.table.Table`
EBOUNDS table.
"""
convert_sed_cols(tab_e)
try:
emin = np.array(tab_e['e_min'].to(u.MeV))
emax = np.array(tab_e['e_max'].to(u.M... | 0.007976 |
def fetch_official_missions(data_dir, start_date, end_date):
"""
:param data_dir: (str) directory in which the output file will be saved
:param start_date: (datetime) first date of the range to be scraped
:param end_date: (datetime) last date of the range to be scraped
"""
official_missions = Of... | 0.002155 |
def tf_if(condition, a, b):
"""
Implements an if condition in tensorflow.
:param condition: A boolean condition.
:param a: Case a.
:param b: Case b.
:return: A if condition was true, b otherwise.
"""
int_condition = tf.to_float(tf.to_int64(condition))
return a * int_condition + (1 - ... | 0.002959 |
def get_from(input_file, property_names):
'''
Reads a geojson and returns a list of value tuples, each value corresponding to a
property in property_names.
Args:
input_file (str): File name.
property_names: List of strings; each string is a property name.
Returns:
List ... | 0.003155 |
def api_key_post(params, request_path, _async=False):
"""
from 火币demo, 构造post请求并调用post方法
:param params:
:param request_path:
:return:
"""
method = 'POST'
timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
params_to_sign = {
'AccessKeyId': ACCESS_KEY,
... | 0.004132 |
def _redirect_edge(self, u_id, v_id, new_v_id):
"""Redirect the layer to a new node.
Change the edge originally from `u_id` to `v_id` into an edge from `u_id` to `new_v_id`
while keeping all other property of the edge the same.
"""
layer_id = None
for index, edge_tuple in... | 0.003604 |
def append_data(self, data_buffer):
""" Append data to this audio stream
:Parameters:
`data_buffer` : str, basestring, Bytes
a buffer with a length multiple of (sample_width * channels)
"""
if len(data_buffer) % (self.sample_width * self.channels) != 0:
... | 0.006073 |
def hash_func(name):
"""Hash the string using a hash algorithm found in
tombkeeper/Shellcode_Template_in_C.
"""
ret = 0
for char in name:
ret = ((ret << 5) + ret + ord(char)) & 0xffffffff
return hex(ret) | 0.004255 |
def _parse(self):
"""
Parse atomic data of the XML file.
"""
atom_counter = 0
structure_build = self.structure_builder
residues = self._extract_residues()
cur_model = None
cur_chain = None
structure_build.init_se... | 0.00938 |
def set_coords(self, x=0, y=0, z=0, t=0):
"""
set coords of agent in an arbitrary world
"""
self.coords = {}
self.coords['x'] = x
self.coords['y'] = y
self.coords['z'] = z
self.coords['t'] = t | 0.007813 |
def _aload16(ins):
''' Loads a 16 bit value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
'''
output = _addr(ins.quad[2])
output.append('ld e, (hl)')
output.append('inc hl')
output.append('ld d, (hl)')
output.append('ex de, hl')
out... | 0.002778 |
def InitLocCheck(self):
"""
make an interactive grid in which users can edit locations
"""
# if there is a location without a name, name it 'unknown'
self.contribution.rename_item('locations', 'nan', 'unknown')
# propagate lat/lon values from sites table
self.cont... | 0.004575 |
def select(self):
"""
Makes this fit the selected fit on the GUI that is it's parent
(Note: may be moved into GUI soon)
"""
if self.GUI==None: return
self.GUI.current_fit = self
if self.tmax != None and self.tmin != None:
self.GUI.update_bounds_boxes()... | 0.017094 |
def take_complement(list_, index_list):
""" Returns items in ``list_`` not indexed by index_list """
mask = not_list(index_to_boolmask(index_list, len(list_)))
return compress(list_, mask) | 0.005 |
def set_time(self, timestamp):
"""
set Device time (pass datetime object)
:param timestamp: python datetime object
"""
command = const.CMD_SET_TIME
command_string = pack(b'I', self.__encode_time(timestamp))
cmd_response = self.__send_command(command, command_stri... | 0.004425 |
def add_state(self):
"""Adds a new state"""
sid = len(self.states)
self.states.append(DFAState(sid))
return sid | 0.013986 |
async def CreateModel(self, cloud_tag, config, credential, name, owner_tag, region):
'''
cloud_tag : str
config : typing.Mapping[str, typing.Any]
credential : str
name : str
owner_tag : str
region : str
Returns -> typing.Union[_ForwardRef('Number'), str, t... | 0.004057 |
def get_websensors(self):
"""
Get sensors with defined tag as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.sensors if self.tag & i.tags} | 0.018265 |
def json_clean(obj):
"""Clean an object to ensure it's safe to encode in JSON.
Atomic, immutable objects are returned unmodified. Sets and tuples are
converted to lists, lists are copied and dicts are also copied.
Note: dicts whose keys could cause collisions upon encoding (such as a dict
wit... | 0.003117 |
def daynum_to_date(daynum, max_days=1000000):
""" Convert a number of days to a date. If it's out of range, default to a
max date. If it is not a number (or a numeric string), return None. Using
a max_days of more than 2932896 (9999-12-31) will throw an exception if the
specified daynum exceeds the max.... | 0.001458 |
def append_new_text(destination, text, join_str=None):
"""
This method provides the functionality of adding text appropriately
underneath the destination node. This will be either to the destination's
text attribute or to the tail attribute of the last child.
"""
if join_str is None:
joi... | 0.001174 |
def get_modes(self, zone):
"""Returns the set of modes the device can be assigned."""
self._populate_full_data()
device = self._get_device(zone)
return device['thermostat']['allowedModes'] | 0.009091 |
def nearby(self, expand=50):
""" Returns a new Region that includes the nearby neighbourhood of the the current region.
The new region is defined by extending the current region's dimensions
all directions by range number of pixels. The center of the new region remains the
same.
... | 0.008264 |
def get_variable_value_for_variation(self, variable, variation):
""" Get the variable value for the given variation.
Args:
variable: The Variable for which we are getting the value.
variation: The Variation for which we are getting the variable value.
Returns:
The variable value or None ... | 0.008915 |
def broadcast_event(self, event, *args):
"""
This is sent to all in the sockets in this particular Namespace,
including itself.
"""
pkt = dict(type="event",
name=event,
args=args,
endpoint=self.ns_name)
for sessid,... | 0.00489 |
def fetch_arc_errors(self):
'''
Evaluates the current tree of the arc and provides a list of errors that
the user should correct.
'''
error_list = []
hnode = self.validate_first_element()
if hnode:
error_list.append({'hook_error': hnode})
rnode... | 0.004115 |
def add_at(self, index: int, requester: int, track: dict):
""" Adds a track at a specific index in the queue. """
self.queue.insert(min(index, len(self.queue) - 1), AudioTrack().build(track, requester)) | 0.013636 |
def _validate_volumes(input_volumes):
'''Check input_volumes contains a valid list of volumes.
Parameters
----------
input_volumes : list
list of volume values. Castable to numbers.
'''
if not (input_volumes is None or isinstance(input_volumes, list)):
raise TypeError("input_vo... | 0.0016 |
def mad(y_true, y_pred):
"""Median absolute deviation
"""
y_true, y_pred = _mask_nan(y_true, y_pred)
return np.mean(np.abs(y_true - y_pred)) | 0.00641 |
def load_SUEWS_Forcing_met_df_pattern(path_input, forcingfile_met_pattern):
"""Short summary.
Parameters
----------
forcingfile_met_pattern : type
Description of parameter `forcingfile_met_pattern`.
Returns
-------
type
Description of returned object.
"""
# list o... | 0.00047 |
def __regkey_value(self, path, name='', start_key=None):
r'''Return the data of value mecabrc at MeCab HKEY node.
On Windows, the path to the mecabrc as set in the Windows Registry is
used to deduce the path to libmecab.dll.
Returns:
The full path to the mecabrc on W... | 0.001458 |
def makeImages(self):
"""Make spiral images in sectors and steps.
Plain, reversed,
sectorialized, negative sectorialized
outline, outline reversed, lonely
only nodes, only edges, both
"""
# make layout
self.makeLayout()
self.setAgraph()
# ... | 0.014881 |
def _parse_list(self, text, i):
"""Parse a list from source text starting at i."""
res = []
end_match = self.end_list_re.match(text, i)
old_current_type = self.current_type
while not end_match:
list_item, i = self._parse(text, i)
res.append(list_item)
... | 0.003896 |
def iou_coe(output, target, threshold=0.5, axis=(1, 2, 3), smooth=1e-5):
"""Non-differentiable Intersection over Union (IoU) for comparing the
similarity of two batch of data, usually be used for evaluating binary image segmentation.
The coefficient between 0 to 1, and 1 means totally match.
Parameters... | 0.00417 |
def from_cli(opt, dyn_range_fac=1, precision='single',
inj_filter_rejector=None):
"""Parses the CLI options related to strain data reading and conditioning.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attri... | 0.002198 |
def threaded_per_region(q, params):
"""
Helper for multithreading on a per-region basis
:param q:
:param params:
:return:
"""
while True:
try:
params['region'] = q.get()
method = params['method']
method(params)
except Exception as e:
... | 0.002577 |
def wif(self, s):
"""
Parse a WIF.
Return a :class:`Key <pycoin.key.Key>` or None.
"""
data = self.parse_b58_hashed(s)
if data is None or not data.startswith(self._wif_prefix):
return None
data = data[len(self._wif_prefix):]
is_compressed = (le... | 0.004032 |
def get_vlan_brief_output_vlan_vlan_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "... | 0.003221 |
def write_buffers(self, conn, locked=True):
''' Write any buffer headers and payloads to the given connection.
Args:
conn (object) :
May be any object with a ``write_message`` method. Typically,
a Tornado ``WSHandler`` or ``WebSocketClientConnection``
... | 0.002548 |
def query_list_of_words(target_word, list_of_words, edit_distance=1):
"""
Checks whether a target word is within editing distance of any one in a set of keywords.
Inputs: - target_word: A string containing the word we want to search in a list.
- list_of_words: A python list of words.
... | 0.00495 |
def is_title(p):
"""
Certain p tags are denoted as ``Title`` tags. This function will return
True if the passed in p tag is considered a title.
"""
w_namespace = get_namespace(p, 'w')
styles = p.xpath('.//w:pStyle', namespaces=p.nsmap)
if len(styles) == 0:
return False
style = st... | 0.002618 |
def _setup_metric_group_values(self):
"""
Return the list of MetricGroupValues objects for this metrics response,
by processing its metrics response string.
The lines in the metrics response string are::
MetricsResponse: MetricsGroup{0,*}
<empty... | 0.000506 |
def whois(ip_address):
"""Whois client for Python"""
whois_ip = str(ip_address)
try:
query = socket.gethostbyname(whois_ip)
except Exception:
query = whois_ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("whois.ripe.net", 43))
s.send(query.encode("utf8") +... | 0.001163 |
def bbox(self, out_crs=None):
"""
Return data bounding box.
Parameters
----------
out_crs : ``rasterio.crs.CRS``
rasterio CRS object (default: CRS of process pyramid)
Returns
-------
bounding box : geometry
Shapely geometry object... | 0.003604 |
def sitetree_breadcrumbs(parser, token):
"""Parses sitetree_breadcrumbs tag parameters.
Two notation types are possible:
1. Two arguments:
{% sitetree_breadcrumbs from "mytree" %}
Used to render breadcrumb path for "mytree" site tree.
2. Four arguments:
{% site... | 0.003155 |
def get_fqn(base_fqn, delimiter, name=None):
"""Return the fully qualified name of an object within this context.
If the name passed already appears to be a fully qualified name, it
will be returned with no further processing.
"""
if name and name.startswith("%s%s" % (base_fqn, delimiter)):
... | 0.002506 |
def iter_content(self, chunk_size=1024):
"""Return the file content as an iterable stream."""
r = self._session.get(self.content, stream=True)
return r.iter_content(chunk_size) | 0.01 |
def get(self, key, default=None):
"""Returns a token by text or local ID, with a default.
A given text image may be associated with more than one symbol ID. This will return the first definition.
Note:
User defined symbol IDs are always one-based. Symbol zero is a special symbol ... | 0.005177 |
def get_parent_families(self, family_id):
"""Gets the parent families of the given ``id``.
arg: family_id (osid.id.Id): the ``Id`` of the ``Family`` to
query
return: (osid.relationship.FamilyList) - the parent families of
the ``id``
raise: NotFound - ... | 0.002893 |
def is_venv(directory, executable='python'):
"""
:param directory: base directory of python environment
"""
path=os.path.join(directory, 'bin', executable)
return os.path.isfile(path) | 0.009852 |
def hosts_append(hostsfile='/etc/hosts', ip_addr=None, entries=None):
'''
Append a single line to the /etc/hosts file.
CLI Example:
.. code-block:: bash
salt '*' dnsutil.hosts_append /etc/hosts 127.0.0.1 ad1.yuk.co,ad2.yuk.co
'''
host_list = entries.split(',')
hosts = parse_hosts(... | 0.00222 |
def get_shake_info(self, ticket):
"""
获取摇周边的设备及用户信息
详情请参考
http://mp.weixin.qq.com/wiki/3/34904a5db3d0ec7bb5306335b8da1faf.html
:param ticket: 摇周边业务的ticket,可在摇到的URL中得到,ticket生效时间为30分钟
:return: 设备及用户信息
"""
res = self._post(
'shakearound/user/get... | 0.004202 |
async def clear(self):
"""Manually expire all sessions in the pool."""
for session in list(self.values()):
if session.state != STATE_CLOSED:
await session._remote_closed()
self.sessions.clear()
super(SessionManager, self).clear() | 0.006897 |
def text_to_speech(text, synthesizer, synth_args, sentence_break):
"""
Converts given text to a pydub AudioSegment using a specified speech
synthesizer. At the moment, IBM Watson's text-to-speech API is the only
available synthesizer.
:param text:
The text that will be synthesized to audio.... | 0.002644 |
def _filter_version_specific_options(self, tmos_ver, **kwargs):
'''Filter version-specific optional parameters
Some optional parameters only exist in v12.1.0 and greater,
filter these out for earlier versions to allow backward comatibility.
'''
if LooseVersion(tmos_ver) < Loose... | 0.002625 |
def intersects(self, b):
""" Return True if a part of the two bounds overlaps.
"""
return max(self.x, b.x) < min(self.x+self.width, b.x+b.width) \
and max(self.y, b.y) < min(self.y+self.height, b.y+b.height) | 0.012195 |
def reset_stats_history(self):
"""Reset the stats history (dict of GlancesAttribute)."""
if self.history_enable():
reset_list = [a['name'] for a in self.get_items_history_list()]
logger.debug("Reset history for plugin {} (items: {})".format(self.plugin_name, reset_list))
... | 0.008571 |
def check_array(array, accept_sparse=None, dtype="numeric", order=None,
copy=False, force_all_finite=True, ensure_2d=True,
allow_nd=False, ensure_min_samples=1, ensure_min_features=1,
warn_on_dtype=False):
"""Input validation on an array, list, sparse matrix or simila... | 0.000164 |
def start(self):
'''
Start the fuzzing session
If fuzzer already running, it will return immediatly
'''
if self._started:
self.logger.warning('called while fuzzer is running. ignoring.')
return
self._started = True
assert(self.model)
... | 0.000773 |
def remove_perm(perm, user_or_group, forum=None):
""" Remove a permission to a user (anonymous or not) or a group. """
user, group = get_identity(user_or_group)
perm = ForumPermission.objects.get(codename=perm)
if user:
UserForumPermission.objects.filter(
forum=forum,
per... | 0.003534 |
def save_ckpt(
sess=None, mode_name='model.ckpt', save_dir='checkpoint', var_list=None, global_step=None, printable=False
):
"""Save parameters into `ckpt` file.
Parameters
------------
sess : Session
TensorFlow Session.
mode_name : str
The name of the model, default is ``mo... | 0.003098 |
def _expectation(p, obj1, feat1, obj2, feat2, nghp=None):
"""
Nota Bene: if only one object is passed, obj1 is
associated with x_n, whereas obj2 with x_{n+1}
"""
if obj2 is None:
gaussian = Gaussian(p.mu[:-1], p.cov[0, :-1])
return expectation(gaussian, (obj1, feat1), nghp=nghp)
... | 0.001869 |
def execute(api):
"""Executes operation.
Args:
api: The base API object
Returns:
A response body object
"""
try:
return api.execute()
except Exception as exception:
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
_print_error('%s: Exception %s: %s' % (now, ... | 0.012371 |
def check(self, obj, prefix=None):
"""Recursively look for :class:`.LocalSetting`s in ``obj``.
``obj`` can be a dict, tuple, or list. Other types are skipped.
This will prompt to get the value of local settings (excluding
those that have had prompting disabled) that haven't already
... | 0.004415 |
def _generateFind(self, **kwargs):
"""Generator which yields matches on AXChildren."""
for needle in self._generateChildren():
if needle._match(**kwargs):
yield needle | 0.009479 |
def eurominder_explorer():
"""Generate interactive data exploration tool
Output is an html page, rendered to 'eurominder_explorer.html' in the output directory.
Data structure (only relevant items are shown below):
.. code-block:: none
{
"nuts2Features": [{"geometry": [<boundary ... | 0.002767 |
def dim_range_key(eldim):
"""
Returns the key to look up a dimension range.
"""
if isinstance(eldim, dim):
dim_name = repr(eldim)
if dim_name.startswith("'") and dim_name.endswith("'"):
dim_name = dim_name[1:-1]
else:
dim_name = eldim.name
return dim_name | 0.003175 |
def fromProfileName(cls, name):
"""Return an `Origin` from a given configuration profile name.
:see: `ProfileStore`.
"""
session = bones.SessionAPI.fromProfileName(name)
return cls(session) | 0.008696 |
def viewBoxAxisRange(viewBox, axisNumber):
""" Calculates the range of an axis of a viewBox.
"""
rect = viewBox.childrenBoundingRect() # taken from viewBox.autoRange()
if rect is not None:
if axisNumber == X_AXIS:
return rect.left(), rect.right()
elif axisNumber == Y_AXIS:
... | 0.004926 |
def consistency(self, consistency):
"""
Sets the consistency level for the operation. See :class:`.ConsistencyLevel`.
.. code-block:: python
for user in User.objects(id=3).consistency(CL.ONE):
print(user)
"""
clone = copy.deepcopy(self)
clone... | 0.008152 |
def batch_workflow_status(self, batch_workflow_id):
"""Checks GBDX batch workflow status.
Args:
batch workflow_id (str): Batch workflow id.
Returns:
Batch Workflow status (str).
"""
self.logger.debug('Get status of batch workflow: ' + batch_workflow_... | 0.003766 |
def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 4:
return self.print_help()
text_format = gf.safe_unicode(self.actual_arguments[0])
if text_format == u"list":
... | 0.002996 |
def find_resistance(record):
"""Infer the antibiotics resistance of the given record.
Arguments:
record (`~Bio.SeqRecord.SeqRecord`): an annotated sequence.
Raises:
RuntimeError: when there's not exactly one resistance cassette.
"""
for feature in record.features:
labels =... | 0.002907 |
def create_profile(ctx, package):
"""Creates an importable Maltego profile (*.mtz) file."""
from canari.commands.create_profile import create_profile
create_profile(ctx.config_dir, ctx.project, package) | 0.004673 |
def add_node(self, n, layers=None, attr_dict=None, **attr):
"""Add a single node n and update node attributes.
Parameters
----------
n : node
A node can be any hashable Python object except None.
layers : set of str or None
the set of layers the node belo... | 0.000911 |
def deps_from_pydit_json(requires, runtime=True):
"""Parses dependencies returned by pydist.json, since versions
uses brackets we can't use pkg_resources to parse and we need a separate
method
Args:
requires: list of dependencies as written in pydist.json of the package
runtime: are the ... | 0.000484 |
def start_instances(instances, region):
'''Start all the instances given by its ids'''
if not instances: return
conn = ec2_connect(region)
log("Starting instances {0}.".format(instances))
conn.start_instances(instances)
log("Done") | 0.007843 |
def cmd_cammsg(self, args):
'''cammsg'''
params = [0, 0, 0, 0, 1, 0, 0]
# fill in any args passed by user
for i in range(min(len(args),len(params))):
params[i] = float(args[i])
print("Sent DIGICAM_CONTROL CMD_LONG")
self.master.mav.command_long_send(
... | 0.01676 |
def save(self, path, verbose=False):
"""Save the suite to disk.
Args:
path (str): Path to save the suite to. If a suite is already saved
at `path`, then it will be overwritten. Otherwise, if `path`
exists, an error is raised.
"""
path = os.pat... | 0.001234 |
def _pre_process_cfg(self):
"""
Pre-process the acyclic CFG.
- Change all FakeRet edges to normal edges when necessary (e.g. the normal/expected return edge does not exist)
"""
for _, dst, data in self._acyclic_cfg.graph.edges(data=True):
if 'jumpkind' in data and dat... | 0.010568 |
def close(self):
"""
Close the connection to the AMQP compliant broker.
"""
if self.channel is not None: self.channel.close()
if self.__connection is not None: self.__connection.close() | 0.017778 |
def smart_text(s, encoding="utf-8", strings_only=False, errors="strict"):
"""Return a unicode object representing 's'.
Treats bytes using the 'encoding' codec.
If strings_only is True, don't convert (some) non-string-like objects.
"""
if isinstance(s, six.text_type):
return s
... | 0.000941 |
def heightmap_new(w: int, h: int, order: str = "C") -> np.ndarray:
"""Return a new numpy.ndarray formatted for use with heightmap functions.
`w` and `h` are the width and height of the array.
`order` is given to the new NumPy array, it can be 'C' or 'F'.
You can pass a NumPy array to any heightmap fu... | 0.001129 |
async def trigger_event(self, event, *args):
"""Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses,
as it performs the routing of events to methods. However, this
method can be overriden if special dispatching rules are ... | 0.002255 |
def toXml(self):
"""
Saves this profile toolbar as XML information.
:return <xml.etree.ElementTree.Element>
"""
xtoolbar = ElementTree.Element('toolbar')
prof = self._currentProfile
if prof is not None:
xtoolbar.set('cur... | 0.012987 |
def build_ingest_fs(self):
"""Return a pyfilesystem subdirectory for the ingested source files"""
base_path = 'ingest'
if not self.build_fs.exists(base_path):
self.build_fs.makedir(base_path, recursive=True, allow_recreate=True)
return self.build_fs.opendir(base_path) | 0.009524 |
def expand_entry(entry, ignore_xs=0x0):
"""Turn all Xs which are not marked in `ignore_xs` into ``0``\ s and
``1``\ s.
The following will expand any Xs in bits ``1..3``\ ::
>>> entry = RoutingTableEntry(set(), 0b0100, 0xfffffff0 | 0b1100)
>>> list(expand_entry(entry, 0xfffffff1)) == [
... | 0.002121 |
def draw_circle(ctx, x, y, radius, cairo_color):
"""
Draw a circle.
:param radius: radius in pixels
:param cairo_color: normalized rgb color
"""
ctx.new_path()
ctx.set_source_rgb(cairo_color.red, cairo_color.green, cairo_color.blue)
ctx.arc(x, y, radius, 0, 2 * pi)
ctx.fill() | 0.003205 |
def call_fdel(self, obj) -> None:
"""Remove the predefined custom value and call the delete function."""
self.fdel(obj)
try:
del vars(obj)[self.name]
except KeyError:
pass | 0.008811 |
def opensearch(self, query, results=10, redirect=True):
""" Execute a MediaWiki opensearch request, similar to search box
suggestions and conforming to the OpenSearch specification
Args:
query (str): Title to search for
results (int): Number of pages with... | 0.001642 |
def line_nbr_from_position(self, y_pos):
"""
Returns the line number from the y_pos.
:param y_pos: Y pos in the editor
:return: Line number (0 based), -1 if out of range
"""
editor = self._editor
height = editor.fontMetrics().height()
for top, line, block... | 0.004577 |
def get_interface_detail_output_interface_if_description(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output"... | 0.002315 |
def onfini(self, func):
'''
Add a function/coroutine/Base to be called on fini().
'''
if isinstance(func, Base):
self.tofini.add(func)
return
assert self.anitted
self._fini_funcs.append(func) | 0.007576 |
def setup_exchange(self, exchange_name):
"""Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC
command. When it is complete, the on_exchange_declareok method will
be invoked by pika.
:param str|unicode exchange_name: The name of the exchange to declare
"""
... | 0.003584 |
def modify_main_app(app, config: Config):
"""
Modify the app we're serving to make development easier, eg.
* modify responses to add the livereload snippet
* set ``static_root_url`` on the app
* setup the debug toolbar
"""
app._debug = True
dft_logger.debug('livereload enabled: %s', '✓' ... | 0.003799 |
def create_equipamento(self):
"""Get an instance of equipamento services facade."""
return Equipamento(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | 0.008696 |
def _run_snpeff(snp_in, out_format, data):
"""Run effects prediction with snpEff, skipping if snpEff database not present.
"""
snpeff_db, datadir = get_db(data)
if not snpeff_db:
return None, None
assert os.path.exists(os.path.join(datadir, snpeff_db)), \
"Did not find %s snpEff gen... | 0.002114 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.