text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def op_at_code_loc(code, loc, opc):
"""Return the instruction name at code[loc] using
opc to look up instruction names. Returns 'got IndexError'
if code[loc] is invalid.
`code` is instruction bytecode, `loc` is an offset (integer) and
`opc` is an opcode module from `xdis`.
"""
try:
... | 0.00241 |
def _resetID(self):
"""Reset all ID fields."""
# Dirty.. .=))
self._setID((None,) * len(self._sqlPrimary))
self._new = True | 0.012903 |
def depth_limited_search(problem, limit=50):
"[Fig. 3.17]"
def recursive_dls(node, problem, limit):
if problem.goal_test(node.state):
return node
elif node.depth == limit:
return 'cutoff'
else:
cutoff_occurred = False
for child in node.expa... | 0.001412 |
def gen_tokens(self):
"""
>>> list(Program("ls").gen_tokens())
['ls']
>>> list(Program("ls -a").gen_tokens())
['ls', '-a']
>>> list(Program("cd /; pwd").gen_tokens())
['cd', '/', None, 'pwd']
>>> list(Program("'cd /; pwd'").gen_tokens())
['cd /; pw... | 0.000986 |
def retry(*dargs, **dkw):
"""Wrap a function with a new `Retrying` object.
:param dargs: positional arguments passed to Retrying object
:param dkw: keyword arguments passed to the Retrying object
"""
# support both @retry and @retry() as valid syntax
if len(dargs) == 1 and callable(dargs[0]):
... | 0.001259 |
def get_negative_cycle(self):
'''
API:
get_negative_cycle(self)
Description:
Finds and returns negative cost cycle using 'cost' attribute of
arcs. Return value is a list of nodes representing cycle it is in
the following form; n_1-n_2-...-n_k, when... | 0.002484 |
def last_error(self):
"""Get the output of the last command exevuted."""
if not len(self.log):
raise RuntimeError('Nothing executed')
try:
errs = [l for l in self.log if l[1] != 0]
return errs[-1][2]
except IndexError:
# odd case where th... | 0.01023 |
def warn(self, collection):
"""Checks this code element for documentation related problems."""
if not self.has_docstring():
collection.append("WARNING: no docstring on code element {}".format(self.name)) | 0.012987 |
def count_words(text, to_lower=True, delimiters=DEFAULT_DELIMITERS):
"""
If `text` is an SArray of strings or an SArray of lists of strings, the
occurances of word are counted for each row in the SArray.
If `text` is an SArray of dictionaries, the keys are tokenized and the
values are the counts. C... | 0.001751 |
def DynamicNestedSampler(loglikelihood, prior_transform, ndim,
bound='multi', sample='auto', periodic=None,
update_interval=None, first_update=None,
npdim=None, rstate=None, queue_size=None, pool=None,
use_pool=None, log... | 0.000136 |
def remap( x, oMin, oMax, nMin, nMax ):
"""Map to a 0 to 1 scale
http://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio
"""
#range check
if oMin == oMax:
log.warning("Zero input range, unable to rescale")
return x
if nMin == nMa... | 0.015015 |
def main() -> None:
"""
Command-line handler for the ``find_bad_openxml`` tool.
Use the ``--help`` option for help.
"""
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
description="""
Tool to scan rescued Microsoft Office OpenXML files (produced by the
find_reco... | 0.000197 |
def centroid_sources(data, xpos, ypos, box_size=11, footprint=None,
error=None, mask=None, centroid_func=centroid_com):
"""
Calculate the centroid of sources at the defined positions.
A cutout image centered on each input position will be used to
calculate the centroid position. T... | 0.0002 |
def get_node(self, name):
"""Retrieve a node from the graph.
Given a node's name the corresponding Node
instance will be returned.
If one or more nodes exist with that name a list of
Node instances is returned.
An empty list is returned otherwise.
... | 0.030466 |
def get_desc2nts_fnc(self, hdrgo_prt=True, section_prt=None,
top_n=None, use_sections=True):
"""Return grouped, sorted namedtuples in either format: flat, sections."""
# RETURN: flat list of namedtuples
nts_flat = self.get_nts_flat(hdrgo_prt, use_sections)
if nts... | 0.01315 |
def unirange(a, b):
"""Returns a regular expression string to match the given non-BMP range."""
if b < a:
raise ValueError("Bad character range")
if a < 0x10000 or b < 0x10000:
raise ValueError("unirange is only defined for non-BMP ranges")
if sys.maxunicode > 0xffff:
# wide bui... | 0.001235 |
def apply_chromatic_adaptation_on_color(color, targ_illum, adaptation='bradford'):
"""
Convenience function to apply an adaptation directly to a Color object.
"""
xyz_x = color.xyz_x
xyz_y = color.xyz_y
xyz_z = color.xyz_z
orig_illum = color.illuminant
targ_illum = targ_illum.lower()
... | 0.003021 |
def normalize_lons(l1, l2):
"""
An international date line safe way of returning a range of longitudes.
>>> normalize_lons(20, 30) # no IDL within the range
[(20, 30)]
>>> normalize_lons(-17, +17) # no IDL within the range
[(-17, 17)]
>>> normalize_lons(-178, +179)
[(-180, -178), (179... | 0.00112 |
def get(self, identity):
"""
Constructs a DocumentPermissionContext
:param identity: Identity of the user to whom the Sync Document Permission applies.
:returns: twilio.rest.sync.v1.service.document.document_permission.DocumentPermissionContext
:rtype: twilio.rest.sync.v1.servi... | 0.008183 |
def ansi(color, text):
"""Wrap text in an ansi escape sequence"""
code = COLOR_CODES[color]
return '\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM) | 0.006211 |
def _surfdens(self,R,z,phi=0.,t=0.):
"""
NAME:
_surfdens
PURPOSE:
evaluate the surface density for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | 0.022 |
def get_polygons_coordinates(geometry):
"""
Extract exterior coordinates from polygon(s) to pass to OSM in a query by
polygon. Ignore the interior ("holes") coordinates.
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to extract exterior coordinates from
... | 0.00211 |
def hide_alert(self, id, **kwargs): # noqa: E501
"""Hide a specific integration alert # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.hide_alert(id, async_re... | 0.002326 |
def update_permissions_rejected_analysis_requests():
"""
Maps and updates the permissions for rejected analysis requests so lab clerks, clients, owners and
RegulatoryInspector can see rejected analysis requests on lists.
:return: None
"""
workflow_tool = api.get_tool("portal_workflow")
work... | 0.001645 |
def find_le_index(self, k):
'Return last item with a key <= k. Raise ValueError if not found.'
i = bisect_right(self._keys, k)
if i:
return i - 1
raise ValueError('No item found with key at or below: %r' % (k,)) | 0.007813 |
async def send_endpoint(self, endpoint: str) -> None:
"""
Send anchor's own endpoint attribute to ledger (and endpoint cache),
if ledger does not yet have input value. Specify None to clear.
Raise BadIdentifier on endpoint not formatted as '<ip-address>:<port>',
BadLedgerTxn on ... | 0.005269 |
def with_organisation(self, organisation):
"""Add an organisation segment.
Args:
organisation (str): Official name of an administrative body
holding an election.
Returns:
IdBuilder
Raises:
ValueError
"""
if organisati... | 0.003868 |
def quorum(name, **kwargs):
'''
Quorum state
This state checks the mon daemons are in quorum. It does not alter the
cluster but can be used in formula as a dependency for many cluster
operations.
Example usage in sls file:
.. code-block:: yaml
quorum:
sesceph.quorum:
... | 0.001122 |
def nested_model(model, nested_fields):
"""
Return :class:`zsl.db.model.app_model import AppModel` with the nested
models attached. ``nested_fields`` can be a simple list as model
fields, or it can be a tree definition in dict with leafs as keys with
``None`` value
"""
# type... | 0.001085 |
def _current_user_manager(self, session=None):
"""Return the current user, or SYSTEM user."""
if session is None:
session = db.session()
try:
user = g.user
except Exception:
return session.query(User).get(0)
if sa.orm.object_session(user) is ... | 0.002584 |
def _makeHttpRequest(self, method, route, payload):
""" Make an HTTP Request for the API endpoint. This method wraps
the logic about doing failure retry and passes off the actual work
of doing an HTTP request to another method."""
url = self._constructUrl(route)
log.debug('Full... | 0.000907 |
def is_not_from_subdomain(self, response, site_dict):
"""
Ensures the response's url isn't from a subdomain.
:param obj response: The scrapy response
:param dict site_dict: The site object from the JSON-File
:return bool: Determines if the response's url is from a subdomain
... | 0.00432 |
def _prefix_from_ip_int(self, ip_int):
"""Return prefix length from the bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format
Returns:
An integer, the prefix length.
Raises:
ValueError: If the input intermingles zeroes & ... | 0.002242 |
def pnum_to_group(mesh_shape, group_dims, pnum):
"""Group number for grouped allreduce.
Args:
mesh_shape: a Shape
group_dims: a list of integers (the dimensions reduced over)
pnum: an integer
Returns:
an integer
"""
coord = pnum_to_processor_coordinates(mesh_shape, pnum)
remaining_shape = ... | 0.01105 |
def serve(self, app_docopt=DEFAULT_DOC, description=''):
''' Configure from cli and run the server '''
exit_status = 0
if isinstance(app_docopt, str):
args = docopt(app_docopt, version=description)
elif isinstance(app_docopt, dict):
args = app_docopt
else... | 0.001276 |
def request(self, command=None):
"""command text
view: Execution user view exec
Configuration system view exec
"""
node = new_ele("CLI")
node.append(validated_element(command))
# sub_ele(node, view).text = command
return self._request(node) | 0.006452 |
def _authstr(self, auth):
"""Convert auth to str so that it can be hashed"""
if type(auth) is dict:
return '{' + ','.join(["{0}:{1}".format(k, auth[k]) for k in sorted(auth.keys())]) + '}'
return auth | 0.012712 |
def get_bids(session, project_ids=[], bid_ids=[], limit=10, offset=0):
"""
Get the list of bids
"""
get_bids_data = {}
if bid_ids:
get_bids_data['bids[]'] = bid_ids
if project_ids:
get_bids_data['projects[]'] = project_ids
get_bids_data['limit'] = limit
get_bids_data['off... | 0.001372 |
def CheckSameObj(obj0, obj1, LFields=None):
""" Check if two variables are the same instance of a ToFu class
Checks a list of attributes, provided by LField
Parameters
----------
obj0 : tofu object
A variable refering to a ToFu object of any class
obj1 : tofu object
A... | 0.009659 |
def get_intercom_data(self):
"""Specify the data sent to Intercom API according to event type"""
data = {
"event_name": self.get_type_display(), # event type
"created_at": calendar.timegm(self.created.utctimetuple()), # date
"metadata": self.metadata
}
... | 0.004902 |
def scaleBy(self, value, origin=None, width=False, height=False):
"""
%s
**width** indicates if the glyph's width should be scaled.
**height** indicates if the glyph's height should be scaled.
The origin must not be specified when scaling the width or height.
"""
... | 0.002294 |
def run(self):
"""Build the Fortran library, all python extensions and the docs."""
print('---- BUILDING ----')
_build.run(self)
# build documentation
print('---- BUILDING DOCS ----')
docdir = os.path.join(self.build_lib, 'pyshtools', 'doc')
self.mkpath(docdir)
... | 0.003717 |
def generate_configuration(directory):
"""
Generates a Sphinx configuration in `directory`.
Parameters
----------
directory : str
Base directory to use
"""
# conf.py file for Sphinx
conf = osp.join(get_module_source_path('spyder.plugins.help.utils'),
'co... | 0.003953 |
def open(self):
"""Generator that opens and yields filehandles using appropriate facilities:
test if path represents a local file or file over URL, if file is compressed
or not.
:return: Filehandle to be processed into an instance.
"""
is_url = self.is_url(self.path)
... | 0.003481 |
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first f... | 0.001316 |
def _dequantize(q, params):
"""Dequantize q according to params."""
if not params.quantize:
return q
return tf.to_float(tf.bitcast(q, tf.int16)) * params.quantization_scale | 0.021978 |
def do_create_virtualenv(python=None, site_packages=False, pypi_mirror=None):
"""Creates a virtualenv."""
click.echo(
crayons.normal(fix_utf8("Creating a virtualenv for this project…"), bold=True), err=True
)
click.echo(
u"Pipfile: {0}".format(crayons.red(project.pipfile_location, bold=... | 0.002674 |
def end_profiling(profiler, filename, sorting=None):
"""
Helper function to stop the profiling process and write out the profiled
data into the given filename. Before this, sort the stats by the passed sorting.
:param profiler: An already started profiler (probably by start_profiling).
:type profil... | 0.003724 |
def visualize_explanation(explanation, label=None):
"""
Given the output of the explain() endpoint, produces a terminal visual that plots response strength over a sequence
"""
if not sys.version_info[:2] >= (3, 5):
raise IndicoError("Python >= 3.5+ is required for explanation visualization")
... | 0.00549 |
def run(self, *args):
"""List, add or delete entries from the blacklist.
By default, it prints the list of entries available on
the blacklist.
"""
params = self.parser.parse_args(args)
entry = params.entry
if params.add:
code = self.add(entry)
... | 0.004167 |
def update_dimensions(self, dims):
"""
Update multiple dimension on the cube.
.. code-block:: python
cube.update_dimensions([
{'name' : 'ntime', 'global_size' : 10,
'lower_extent' : 2, 'upper_extent' : 7 },
{'name' : 'na', 'global_siz... | 0.002822 |
def dataverse_download_doi(doi,
local_fname=None,
file_requirements={},
clobber=False):
"""
Downloads a file from the Dataverse, using a DOI and set of metadata
parameters to locate the file.
Args:
doi (str): Digit... | 0.001208 |
def render_koji(self):
"""
if there is yum repo specified, don't pick stuff from koji
"""
phase = 'prebuild_plugins'
plugin = 'koji'
if not self.dj.dock_json_has_plugin_conf(phase, plugin):
return
if self.spec.yum_repourls.value:
logger.in... | 0.001555 |
def findNode( self, objectName ):
"""
Looks up the node based on the inputed node name.
:param objectName | <str>
"""
for item in self.items():
if ( isinstance(item, XNode) and
item.objectName() == objectName ):
retu... | 0.023055 |
def fixed_poch(a, n):
"""Implementation of the Pochhammer symbol :math:`(a)_n` which handles negative integer arguments properly.
Need conditional statement because scipy's impelementation of the Pochhammer
symbol is wrong for negative integer arguments. This function uses the
definition from
h... | 0.006322 |
def _move(self, from_state=None, to_state=None, when=None, mode=None):
"""
Internal helper to move a task from one state to another (e.g. from
QUEUED to DELAYED). The "when" argument indicates the timestamp of the
task in the new state. If no to_state is specified, the task will be
... | 0.002971 |
def get_password(self, service, username):
"""Get password of the username for the service
"""
items = self._find_passwords(service, username)
if not items:
return None
secret = items[0].secret
return (
secret
if isinstance(secret, six... | 0.005249 |
def set_channel(self, channel):
""" Set the radio channel to be used """
if channel != self.current_channel:
_send_vendor_setup(self.handle, SET_RADIO_CHANNEL, channel, 0, ())
self.current_channel = channel | 0.00813 |
def set(self, instance, value, **kwargs):
"""Adds the value to the existing text stored in the field,
along with a small divider showing username and date of this entry.
"""
if not value:
return
value = value.strip()
date = DateTime().rfc822()
user = g... | 0.002506 |
def _create_scales(hist: HistogramBase, vega: dict, kwargs: dict):
"""Find proper scales for axes."""
if hist.ndim == 1:
bins0 = hist.bins.astype(float)
else:
bins0 = hist.bins[0].astype(float)
xlim = kwargs.pop("xlim", "auto")
ylim = kwargs.pop("ylim", "auto")
if xlim is "auto... | 0.002217 |
def set_condition(self, condition = True):
"""
Sets a new condition callback for the breakpoint.
@see: L{__init__}
@type condition: function
@param condition: (Optional) Condition callback function.
"""
if condition is None:
self.__condition = True
... | 0.010695 |
def arcovar(x, order):
r"""Simple and fast implementation of the covariance AR estimate
This code is 10 times faster than :func:`arcovar_marple` and more importantly
only 10 lines of code, compared to a 200 loc for :func:`arcovar_marple`
:param array X: Array of complex data samples
:param int o... | 0.001672 |
def debugger(self,force=False):
"""Call the pydb/pdb debugger.
Keywords:
- force(False): by default, this routine checks the instance call_pdb
flag and does not actually invoke the debugger if the flag is false.
The 'force' option forces the debugger to activate even if t... | 0.007177 |
def setSeed(self, value):
"""
Sets the seed to value.
"""
self.seed = value
random.seed(self.seed)
if self.verbosity >= 0:
print("Conx using seed:", self.seed) | 0.009132 |
def accessibility(graph):
"""
Accessibility matrix (transitive closure).
@type graph: graph, digraph, hypergraph
@param graph: Graph.
@rtype: dictionary
@return: Accessibility information for each node.
"""
recursionlimit = getrecursionlimit()
setrecursionlimit(max(len(graph.node... | 0.005495 |
def choices_label(choices: tuple, value) -> str:
"""
Iterates (value,label) list and returns label matching the choice
:param choices: [(choice1, label1), (choice2, label2), ...]
:param value: Value to find
:return: label or None
"""
for key, label in choices:
if key == value:
... | 0.002841 |
def get_config(config_file=None, config_values=None, load_project_conf=True):
"""Loads config file and returns its content."""
config_values = config_values or {}
config_settings = {}
default_conf = _get_default_conf()
user_conf = _get_user_conf(config_file) if config_file else {}
# load projec... | 0.001664 |
def _distance_squared(self, p2: "Point2") -> Union[int, float]:
""" Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process. """
return (self[0] - p2[0]) ** 2 + (self[1] - p2[1]) ** 2 | 0.01083 |
def read_key_value_pairs_from_file(*path):
"""
Read key value pairs from a file (each pair on a separate line).
Key and value are separated by ' ' as often used by the kernel.
@return a generator of tuples
"""
with open(os.path.join(*path)) as f:
for line in f:
yield line.spl... | 0.00303 |
def get_asset_query_session(self, proxy=None):
"""Gets the ``OsidSession`` associated with the asset query service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetQuerySession) - an
``AssetQuerySession``
raise: NullArgument - ``proxy`` is ``null... | 0.002793 |
def solve(self, **kwargs):
"""
The kwargs required depend upon the script type.
hash160_lookup:
dict-like structure that returns a secret exponent for a hash160
existing_script:
existing solution to improve upon (optional)
sign_value:
the integer value to sign (derived from t... | 0.001226 |
def set_widgets(self):
"""Set widgets on the Extra Keywords tab."""
existing_inasafe_field = self.parent.get_existing_keyword(
'inasafe_fields')
# Remove old container and parameter
if self.parameter_container:
self.kwExtraKeywordsGridLayout.removeWidget(
... | 0.000736 |
def uploadPackages(self, directory):
"""
Not working. Am not able ot figure out how to upload. IT return status 200OK with this code but do not store the files.
In tomcat.log (IM) there?s a complaint about character encoding whn uploading file. Not sure how to rectiy it in requests post ... | 0.015171 |
def _execute_pep8(pep8_options, source):
"""Execute pycodestyle via python method calls."""
class QuietReport(pycodestyle.BaseReport):
"""Version of checker that does not print."""
def __init__(self, options):
super(QuietReport, self).__init__(options)
self.__full_error... | 0.000732 |
def get_component(self, component_name):
"""
Looks up a component by its name.
Args:
component_name: The name of the component to look up.
Returns:
The component for the provided name or None if there is no such component.
"""
mapping = self.get_c... | 0.007335 |
def optimizer_setter(
net, param, value, optimizer_attr='optimizer_', optimizer_name='optimizer'
):
"""Handle setting of optimizer parameters such as learning rate and
parameter group specific parameters such as momentum.
The parameters ``optimizer_attr`` and ``optimizer_name`` can be specified... | 0.003831 |
def get_stub(source, generic=False):
"""Get the stub code for a source code.
:sig: (str, bool) -> str
:param source: Source code to generate the stub for.
:param generic: Whether to produce generic stubs.
:return: Generated stub code.
"""
generator = StubGenerator(source, generic=generic)
... | 0.002695 |
def Parse(self):
"""Parse the file."""
if not self._file:
logging.error("Couldn't open file")
return
# Limit read size to 5MB.
self.input_dat = self._file.read(1024 * 1024 * 5)
if not self.input_dat.startswith(self.FILE_HEADER):
logging.error("Invalid index.dat file %s", self._fil... | 0.011804 |
def require_repeated_start():
"""Enable repeated start conditions for I2C register reads. This is the
normal behavior for I2C, however on some platforms like the Raspberry Pi
there are bugs which disable repeated starts unless explicitly enabled with
this function. See this thread for more details:
... | 0.004883 |
def decorate(cls, app, *args, run_middleware=False, with_context=False,
**kwargs):
"""
This is a decorator that can be used to apply this plugin to a specific
route/view on your app, rather than the whole app.
:param app:
:type app: Sanic | Blueprint
:par... | 0.000574 |
def get_item(self, obj):
"""Return a result item.
:param obj: Instance object
:returns: a dictionnary with at least `id` and `text` values
"""
return {"id": obj.id, "text": self.get_label(obj), "name": obj.name} | 0.007937 |
def get_v_eff_stress_at_depth(self, y_c):
"""
Determine the vertical effective stress at a single depth z_c.
:param y_c: float, depth from surface
"""
sigma_v_c = self.get_v_total_stress_at_depth(y_c)
pp = self.get_hydrostatic_pressure_at_depth(y_c)
sigma_veff_c ... | 0.005495 |
def get_developer_certificate(self, developer_certificate_id, authorization, **kwargs): # noqa: E501
"""Fetch an existing developer certificate to connect to the bootstrap server. # noqa: E501
This REST API is intended to be used by customers to fetch an existing developer certificate (a certificate ... | 0.001211 |
def do_edit_settings(fake):
"""Opens legit settings in editor."""
path = resources.user.open('config.ini').name
click.echo('Legit Settings:\n')
for (option, _, description) in legit_settings.config_defaults:
click.echo(columns([crayons.yellow(option), 25], [description, None]))
click.echo... | 0.002079 |
def pointOnCircle(cx, cy, radius, angle):
"""
Calculates the coordinates of a point on a circle given the center point,
radius, and angle.
"""
angle = math.radians(angle) - (math.pi / 2)
x = cx + radius * math.cos(angle)
if x < cx:
x = math.ceil(x)
else:
x = math.floor(x)... | 0.002151 |
def distinguish(self, how=True):
"""Distinguishes this thing (POST). Calls :meth:`narwal.Reddit.distinguish`.
:param how: either True, False, or 'admin'
"""
return self._reddit.distinguish(self.name, how=how) | 0.016 |
def _reference_keys(self, reference):
""" Returns a list of all of keys for a given reference.
:param reference: a :string:
:rtype: A :list: of reference keys.
"""
if not isinstance(reference, six.string_types):
raise TypeError(
'When using ~ to refer... | 0.005607 |
def findbestparams_ho(xsamples):
""" Minimize sum of square differences of H_sho-<H_sho> for timesamples """
return np.abs(leastsq(deltaH_ho,np.array([10.,10.,10.]), Dfun = Jac_deltaH_ho, args=(xsamples,))[0])[:3] | 0.031674 |
def assoc2(self, assets_by_site, assoc_dist, mode, asset_refs):
"""
Associated a list of assets by site to the site collection used
to instantiate GeographicObjects.
:param assets_by_sites: a list of lists of assets
:param assoc_dist: the maximum distance for association
... | 0.00103 |
def is_any_down(self):
"""Is any button depressed?"""
for key in range(len(self.current_state.key_states)):
if self.is_down(key):
return True
return False | 0.009709 |
def wrap(self, text):
"""wrap(text : string) -> [string]
Reformat the single paragraph in 'text' so it fits in lines of
no more than 'self.width' columns, and return a list of wrapped
lines. Tabs in 'text' are expanded with string.expandtabs(),
and all other whitespace characte... | 0.003384 |
def _get_threshold(self, graph, benchmark, entry_name):
"""
Compute the regression threshold in asv.conf.json.
"""
if graph.params.get('branch'):
branch_suffix = '@' + graph.params.get('branch')
else:
branch_suffix = ''
max_threshold = None
... | 0.004255 |
def color(self):
"""Function color in IDA View"""
color = idc.GetColor(self.ea, idc.CIC_FUNC)
if color == 0xFFFFFFFF:
return None
return color | 0.010695 |
def _handle_request_exception(self, e):
"""This method handle HTTPError exceptions the same as how tornado does,
leave other exceptions to be handled by user defined handler function
maped in class attribute `EXCEPTION_HANDLERS`
Common HTTP status codes:
200 OK
3... | 0.003058 |
def iterate(self, max_iter=None):
"""Yields items from the mux, and handles stream exhaustion and
replacement.
"""
if max_iter is None:
max_iter = np.inf
# Calls Streamer's __enter__, which calls activate()
with self as active_mux:
# Main sampling... | 0.001724 |
def _init_actions(self, create_standard_actions):
""" Init context menu action """
menu_advanced = QtWidgets.QMenu(_('Advanced'))
self.add_menu(menu_advanced)
self._sub_menus = {
'Advanced': menu_advanced
}
if create_standard_actions:
# Undo
... | 0.000424 |
def make_directory(self, directory_name, *args, **kwargs):
""" :meth:`.WNetworkClientProto.make_directory` method implementation
"""
previous_path = self.session_path()
try:
self.session_path(directory_name)
os.mkdir(self.full_path())
finally:
self.session_path(previous_path) | 0.033898 |
def demo(args):
"""
%prog demo
Draw sample gene features to illustrate the various fates of duplicate
genes - to be used in a book chapter.
"""
p = OptionParser(demo.__doc__)
opts, args = p.parse_args(args)
fig = plt.figure(1, (8, 5))
root = fig.add_axes([0, 0, 1, 1])
panel_sp... | 0.004825 |
def get_page_text(self, project, wiki_identifier, path=None, recursion_level=None, version_descriptor=None, include_content=None, **kwargs):
"""GetPageText.
[Preview API] Gets metadata or content of the wiki page for the provided path. Content negotiation is done based on the `Accept` header sent in the... | 0.005751 |
def get_project_export(self, project_id):
""" Get project info for export """
try:
result = self._request('/getprojectexport/',
{'projectid': project_id})
return TildaProject(**result)
except NetworkError:
return [] | 0.006452 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.