text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_vnetwork_dvs_output_vnetwork_dvs_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvs = ET.Element("get_vnetwork_dvs")
config = get_vnetwork_dvs
output = ET.SubElement(get_vnetwork_dvs, "output")
vnetwork_dvs = ET... | 0.003731 |
def status(self):
""" Status of this SMS. Can be ENROUTE, DELIVERED or FAILED
The actual status report object may be accessed via the 'report' attribute
if status is 'DELIVERED' or 'FAILED'
"""
if self.report == None:
return SentSms.ENROUTE
else:
... | 0.014019 |
def load_locale_prefixdata_file(prefixdata, filename, locale=None, overall_prefix=None, separator=None):
"""Load per-prefix data from the given file, for the given locale and prefix.
We assume that this file:
- is encoded in UTF-8
- may have comment lines (starting with #) and blank lines
- has ... | 0.004027 |
def content_type(self) -> Optional[ContentTypeHeader]:
"""The ``Content-Type`` header."""
try:
return cast(ContentTypeHeader, self[b'content-type'][0])
except (KeyError, IndexError):
return None | 0.008264 |
def parse_options():
"""
parse_options() -> opts, args
Parse any command-line options given returning both
the parsed options and arguments.
"""
parser = optparse.OptionParser(usage=USAGE, version=VERSION)
parser.add_option("-o", "--ontology",
action="store", type="string", default="", dest="ontology",
... | 0.033531 |
def forward(self, x):
"""Compute forward-pass of this module on ``x``.
Parameters
----------
x : `torch.autograd.variable.Variable`
Input of this layer. The contained tensor must have shape
``extra_shape + operator.domain.shape``, and
``len(extra_shap... | 0.000608 |
def node_stat_copy(self, node_or_char, node=None):
"""Return a node's stats, prepared for pickling, in a dictionary."""
if node is None:
node = node_or_char
else:
node = self._real.character[node_or_char].node[node]
return {
k: v.unwrap() if hasattr(v,... | 0.005291 |
def _textOutput(self, gaObjects):
"""
Prints out the specified Variant objects in a VCF-like form.
"""
for variantAnnotation in gaObjects:
print(
variantAnnotation.id, variantAnnotation.variant_id,
variantAnnotation.variant_annotation_set_id,
... | 0.002469 |
def read(self, symbol, chunk_range=None, filter_data=True, **kwargs):
"""
Reads data for a given symbol from the database.
Parameters
----------
symbol: str, or list of str
the symbol(s) to retrieve
chunk_range: object
corresponding range object f... | 0.00226 |
def is_primitive(value):
"""
Checks if value has primitive type.
Primitive types are: numbers, strings, booleans, date and time.
Complex (non-primitive types are): objects, maps and arrays
:param value: a value to check
:return: true if the value has primitive type and... | 0.010526 |
def get_servers(self, topic):
"""We're assuming that the static list of servers can serve the given
topic, since we have to preexisting knowledge about them.
"""
return (nsq.node.ServerNode(sh) for sh in self.__server_hosts) | 0.011628 |
def run(self, args):
"""
Deletes a single project specified by project_name in args.
:param args Namespace arguments parsed from the command line
"""
project = self.fetch_project(args, must_exist=True, include_children=False)
if not args.force:
delete_prompt =... | 0.009042 |
def QA_fetch_get_future_min(code, start, end, frequence='1min', ip=None, port=None):
'期货数据 分钟线'
ip, port = get_extensionmarket_ip(ip, port)
apix = TdxExHq_API()
type_ = ''
start_date = str(start)[0:10]
today_ = datetime.date.today()
lens = QA_util_get_trade_gap(start_date, today_)
global... | 0.004386 |
def start(self, http_daemon=None): # pylint: disable=unused-argument
"""Actually restart the process if the module is external
Try first to stop the process and create a new Process instance
with target start_module.
Finally start process.
:param http_daemon: Not used here but ... | 0.002602 |
def s_connect(self, server, port, r_server=None):
"""
Link a server.
Required arguments:
* server - Server to link with.
* port - Port to use.
Optional arguments:
* r_server=None - Link r_server with server.
"""
with self.lock:
if not r... | 0.007233 |
def create_item(self, hash_key, start=0, extra_attrs=None):
'''
Hook point for overriding how the CouterPool creates a DynamoDB item
for a given counter when an existing item can't be found.
'''
table = self.get_table()
now = datetime.utcnow().replace(microsecond=0).isofo... | 0.00319 |
def optional(e, default=Ignore):
"""
Create a PEG function to optionally match an expression.
"""
def match_optional(s, grm=None, pos=0):
try:
return e(s, grm, pos)
except PegreError:
return PegreResult(s, default, (pos, pos))
return match_optional | 0.003247 |
def export_public_key(user_id, env=None, sp=subprocess):
"""Export GPG public key for specified `user_id`."""
args = gpg_command(['--export', user_id])
result = check_output(args=args, env=env, sp=sp)
if not result:
log.error('could not find public key %r in local GPG keyring', user_id)
... | 0.00277 |
def fix_axon_peri(hobj):
"""Replace reconstructed axon with a stub
:param hobj: hoc object
"""
for i,sec in enumerate(hobj.axon):
hobj.axon[i] = None
for i,sec in enumerate(hobj.all):
if 'axon' in sec.name():
hobj.all[i] = None
hobj.all = [sec for sec in hobj.all if... | 0.005229 |
def _parse(data, obj_name, attr_map):
"""parse xml data into a python map"""
parsed_xml = minidom.parseString(data)
parsed_objects = []
for obj in parsed_xml.getElementsByTagName(obj_name):
parsed_obj = {}
for (py_name, xml_name) in attr_map.items():
parsed_obj[py_name] = _ge... | 0.00237 |
async def list_networks(request: web.Request) -> web.Response:
"""
Get request will return a list of discovered ssids:
GET /wifi/list
200 OK
{ "list": [
{
ssid: string // e.g. "linksys", name to connect to
signal: int // e.g. 100; arbitrary signal strength, more is be... | 0.000901 |
def _mark_html_fields_as_safe(self, page):
"""
Mark the html content as safe so we don't have to use the safe
template tag in all cms templates:
"""
page.title = mark_safe(page.title)
page.content = mark_safe(page.content)
return page | 0.006897 |
def isSelfSigned(self):
"""
Return True if the certificate is self signed:
- issuer and subject are the same
- the signature of the certificate is valid.
"""
if self.issuer == self.subject:
return self.isIssuerCert(self)
return False | 0.006557 |
def _onKeyUp(self, evt):
"""Release key."""
key = self._get_key(evt)
#print 'release key', key
evt.Skip()
FigureCanvasBase.key_release_event(self, key, guiEvent=evt) | 0.014634 |
def threads():
'''
This tests the performance of the processor's scheduler
CLI Example:
.. code-block:: bash
salt '*' sysbench.threads
'''
# Test data
thread_yields = [100, 200, 500, 1000]
thread_locks = [2, 4, 8, 16]
# Initializing the test variables
test_command = ... | 0.001299 |
def _Rzderiv(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rzderiv
PURPOSE:
evaluate the mixed R,z derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | 0.014286 |
def process_form(self, instance, field, form, empty_marker = None,
emptyReturnsMarker = False):
""" Some special field handling for disabled fields, which don't
get submitted by the browser but still need to be written away.
"""
bsc = getToolByName(instance, 'bika_se... | 0.009346 |
def metzner_mcmc_slow(Z, n_samples, n_thin=1, random_state=None):
"""Metropolis Markov chain Monte Carlo sampler for reversible transition
matrices
Parameters
----------
Z : np.array, shape=(n_states, n_states)
The effective count matrix, the number of observed transitions
between s... | 0.002735 |
def check_bad_data(raw_data, prepend_data_headers=None, trig_count=None):
"""Checking FEI4 raw data array for corrupted data.
"""
consecutive_triggers = 16 if trig_count == 0 else trig_count
is_fe_data_header = logical_and(is_fe_word, is_data_header)
trigger_idx = np.where(is_trigger_word(raw_data) ... | 0.002451 |
def _ord_to_str(ordinal, weights):
"""Reverse function of _str_to_ord."""
chars = []
for weight in weights:
if ordinal == 0:
return "".join(chars)
ordinal -= 1
index, ordinal = divmod(ordinal, weight)
chars.append(_ALPHABET[index])
return "".join(chars) | 0.021201 |
def get_sanitize_files(self):
"""
Return list of all sanitize files provided by the user on the command line.
N.B.: We only support one sanitize file at the moment, but
this is likely to change in the future
"""
if self.parent.config.option.sanitize_with is not No... | 0.007143 |
def handle(self, *args, **options):
"""
With no arguments, find the first user in the system with the
is_superuser or is_staff flag set to true, or just the first user in
the system period.
With a single argument, look for the user with that value as the
USERNAME_FIELD v... | 0.001889 |
def _MultiStream(cls, fds):
"""Method overriden by subclasses to optimize the MultiStream behavior."""
for fd in fds:
fd.Seek(0)
while True:
chunk = fd.Read(cls.MULTI_STREAM_CHUNK_SIZE)
if not chunk:
break
yield fd, chunk, None | 0.014235 |
def master_using_raster(mdf, raster, endpoint=False):
""" get single master based on the raster
Parameters
----------
mdf : asammdf.MDF
measurement object
raster : float
new raster
endpoint=False : bool
include maximum time stamp in the new master
Returns
------... | 0.000588 |
def filter_lines(input_file, output_file, translate=lambda line: line):
""" Translate all the lines of a single file """
filepath, lines = get_lines([input_file])[0]
return filepath, [(tag, translate(line=line, tag=tag)) for (tag, line) in lines] | 0.007752 |
def dchisq(psr,formbats=False,renormalize=True):
"""Return gradient of total chisq for the current timing solution,
after removing noise-averaged mean residual, and ignoring deleted points."""
if formbats:
psr.formbats()
res, err = psr.residuals(removemean=False)[psr.deleted == 0], psr.toa... | 0.01771 |
def release():
"""
Create a new release and upload it to PyPI.
"""
if not is_working_tree_clean():
print('Your working tree is not clean. Refusing to create a release.')
return
print('Rebuilding the AUTHORS file to check for modifications...')
authors()
if not is_working_t... | 0.000649 |
def consumer_group(self, group, keys, consumer=None):
"""
Create a named :py:class:`ConsumerGroup` instance for the given key(s).
:param group: name of consumer group
:param keys: stream identifier(s) to monitor. May be a single stream
key, a list of stream keys, or a key-to... | 0.002706 |
def create_signature(public_key, private_key, data, scheme='ecdsa-sha2-nistp256'):
"""
<Purpose>
Return a (signature, scheme) tuple.
>>> requested_scheme = 'ecdsa-sha2-nistp256'
>>> public, private = generate_public_and_private(requested_scheme)
>>> data = b'The quick brown fox jumps over the lazy ... | 0.010388 |
def attitude_encode(self, time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed):
'''
The attitude in the aeronautical frame (right-handed, Z-down, X-front,
Y-right).
time_boot_ms : Timestamp (milliseconds since system boot) (uint32... | 0.006445 |
def make_structure_from_geos(geos):
'''Creates a structure out of a list of geometry objects.'''
model_structure=initialize_res(geos[0])
for i in range(1,len(geos)):
model_structure=add_residue(model_structure, geos[i])
return model_structure | 0.014981 |
def gaussian(N=1000, draw=True, show=True, seed=42, color=None, marker='sphere'):
"""Show N random gaussian distributed points using a scatter plot."""
import ipyvolume as ipv
rng = np.random.RandomState(seed) # pylint: disable=no-member
x, y, z = rng.normal(size=(3, N))
if draw:
if color... | 0.003442 |
def filter(self, func):
"""Returns a packet list filtered by a truth function. This truth
function has to take a packet as the only argument and return a boolean value.""" # noqa: E501
return self.__class__([x for x in self.res if func(x)],
name="filtered %s" % sel... | 0.006042 |
def items(self):
"""Settings as key-value pair.
"""
return [(section, dict(self.conf.items(section, raw=True))) for \
section in [section for section in self.conf.sections()]] | 0.018957 |
def ssh_session(key_filename,
username,
ip_address,
*cli):
""" opens a ssh shell to the host """
local('ssh -t -i %s %s@%s %s' % (key_filename,
username,
ip_address,
... | 0.002717 |
def getuserinfo(self, default=None, encoding='utf-8', errors='strict'):
"""Return the decoded userinfo subcomponent of the URI authority, or
`default` if the original URI reference did not contain a
userinfo field.
"""
userinfo = self.userinfo
if userinfo is None:
... | 0.004866 |
def get_blob(self, index):
"""Return a blob with the event at the given index"""
self.log.info("Retrieving blob #{}".format(index))
if index > len(self.event_offsets) - 1:
self.log.info("Index not in cache, caching offsets")
self._cache_offsets(index, verbose=False)
... | 0.002786 |
def __get_numbered_paths(filepath):
"""Append numbers in sequential order to the filename or folder name
Numbers should be appended before the extension on a filename."""
format = '%s (%%d)%s' % splitext_files_only(filepath)
return map(lambda n: format % n, itertools.count(1)) | 0.017544 |
def subscribe(self, handler):
"""Adds a new event handler."""
assert callable(handler), "Invalid handler %s" % handler
self.handlers.append(handler) | 0.011628 |
def get_field_mapping(self):
"""Obtain metadata from current state of the widget.
Null or empty list will be removed.
:returns: Dictionary of values by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict
"""
field_mapping = self.field_mapping_wid... | 0.003185 |
def populate_readme(
version, circleci_build, appveyor_build, coveralls_build, travis_build
):
"""Populates ``README.rst`` with release-specific data.
This is because ``README.rst`` is used on PyPI.
Args:
version (str): The current version.
circleci_build (Union[str, int]): The CircleC... | 0.000943 |
def setDatasets(self, datasets):
"""
Sets the dataset list for this chart to the inputed data.
:param datasets | [<XChartDataset>, ..]
"""
self.clearDatasets()
self._datasets = datasets
for dataset in datasets:
self._ad... | 0.012048 |
def parse_bytes_str(value):
"""
Given a value return the integer number of bytes it represents.
Trailing "MB" causes the value multiplied by 1024*1024
:param value:
:return: int number of bytes represented by value.
"""
if type(value) == str:
if "MB" i... | 0.004124 |
def gen_toyn(f, nsample, ntoy, bound, accuracy=10000, quiet=True, **kwd):
"""
just alias of gentoy for nample and then reshape to ntoy,nsample)
:param f:
:param nsample:
:param bound:
:param accuracy:
:param quiet:
:param kwd:
:return:
"""
return gen_toy(f, nsample * ntoy, bo... | 0.005362 |
def _add_arguments(self):
"""Adds arguments to parser."""
self._parser.add_argument(
'-v', '--version',
action='store_true',
help="show program's version number and exit")
self._parser.add_argument(
'-a', '--alias',
nargs='?',
... | 0.001503 |
def _ParseFileData(self, knowledge_base, file_object):
"""Parses file content (data) for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_object (dfvfs.FileIO): file-like object that contains the artifact
value data.
Raises... | 0.004605 |
def interfaces(self) -> GraphQLInterfaceList:
"""Get provided interfaces."""
try:
interfaces = resolve_thunk(self._interfaces)
except GraphQLError:
raise
except Exception as error:
raise TypeError(f"{self.name} interfaces cannot be resolved: {error}")
... | 0.006234 |
def load(self, mdl_file):
"""
load model from file. fv_type is not set with this function. It is expected to set it before.
"""
import dill as pickle
mdl_file_e = op.expanduser(mdl_file)
sv = pickle.load(open(mdl_file_e, "rb"))
self.mdl = sv["mdl"]
# sel... | 0.004208 |
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid
'''
serv = _get_serv(ret=None)
serv.setex('load:{0}'.format(jid), _get_ttl(), salt.utils.json.dumps(load)) | 0.004878 |
def as_tuple(self):
"""
:rtype: (str, object)
"""
if self._as_tuple is None:
self._as_tuple = self.converted.items()[0]
return self._as_tuple | 0.010363 |
def errdp(marker, number):
"""
Substitute a double precision number for the first occurrence of
a marker found in the current long error message.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/errdp_c.html
:param marker: A substring of the error message to be replaced.
:type marker: s... | 0.001883 |
def vm_profiles_config(path,
providers,
env_var='SALT_CLOUDVM_CONFIG',
defaults=None):
'''
Read in the salt cloud VM config file
'''
if defaults is None:
defaults = VM_CONFIG_DEFAULTS
overrides = salt.config.load_config(
... | 0.001238 |
def fd_decompress(amp, phase, sample_frequencies, out=None, df=None,
f_lower=None, interpolation='inline_linear'):
"""Decompresses an FD waveform using the given amplitude, phase, and the
frequencies at which they are sampled at.
Parameters
----------
amp : array
The ampli... | 0.001333 |
def Up(self, n = 1, dl = 0):
"""上方向键n次
"""
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.up_key, n) | 0.044118 |
def correct_spelling(text_string):
'''
Splits string and converts words not found within a pre-built dictionary to their
most likely actual word based on a relative probability dictionary. Returns edited
string as type str.
Keyword argument:
- text_string: string instance
Exceptions raise... | 0.004813 |
def best_prefix(self, system=None):
"""Optional parameter, `system`, allows you to prefer NIST or SI in
the results. By default, the current system is used (Bit/Byte default
to NIST).
Logic discussion/notes:
Base-case, does it need converting?
If the instance is less than one Byte, return the instance as a B... | 0.000637 |
def add_synchronous_cb(self, cb):
'''
Add an expectation of a callback to release a synchronous transaction.
'''
if self.connection.synchronous or self._synchronous:
wrapper = SyncWrapper(cb)
self._pending_events.append(wrapper)
while wrapper._read:
... | 0.001596 |
def lasso_leftdown(self, event=None):
"""leftdown event handler for lasso mode"""
try:
self.report_leftdown(event=event)
except:
return
if event.inaxes:
# set lasso color
color='goldenrod'
cmap = getattr(self.conf, 'cmap', None... | 0.007653 |
def broadcast_tx(self, address, amount, secret, secondsecret=None, vendorfield=''):
"""broadcasts a transaction to the peerslist using ark-js library"""
peer = random.choice(self.PEERS)
park = Park(
peer,
4001,
constants.ARK_NETHASH,
'1.1.1'
... | 0.009434 |
def libvlc_vlm_add_vod(p_instance, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux):
'''Add a vod, with one input.
@param p_instance: the instance.
@param psz_name: the name of the new vod media.
@param psz_input: the input MRL.
@param i_options: number of additional options.
@p... | 0.006645 |
def Animation_setPaused(self, animations, paused):
"""
Function path: Animation.setPaused
Domain: Animation
Method name: setPaused
Parameters:
Required arguments:
'animations' (type: array) -> Animations to set the pause state of.
'paused' (type: boolean) -> Paused state to set to.
No r... | 0.044471 |
def setup(working_dir, interactive=False):
"""
Do one-time initialization.
Call this to set up global state.
"""
# set up our implementation
log.debug("Working dir: {}".format(working_dir))
if not os.path.exists( working_dir ):
os.makedirs( working_dir, 0700 )
node_config = load... | 0.011881 |
def tags(self):
'Return a thread local :class:`dossier.web.Tags` client.'
if self._tags is None:
config = global_config('dossier.tags')
self._tags = self.create(Tags, config=config)
return self._tags | 0.008097 |
def find_hass_config():
"""Try to find HASS config."""
if "HASSIO_TOKEN" in os.environ:
return "/config"
config_dir = default_hass_config_dir()
if os.path.isdir(config_dir):
return config_dir
raise ValueError(
"Unable to automatically find the location of Home Assistant "
... | 0.002762 |
def _reconstruct(keyvals, dialect, keep_order=False,
sort_attribute_values=False):
"""
Reconstructs the original attributes string according to the dialect.
Parameters
==========
keyvals : dict
Attributes from a GFF/GTF feature
dialect : dict
Dialect containing... | 0.000347 |
def get_payload(self):
"""Return Payload."""
payload = bytes([self.node_id])
payload += bytes([self.state])
payload += bytes(self.current_position.raw)
payload += bytes(self.target.raw)
payload += bytes(self.current_position_fp1.raw)
payload += bytes(self.current_... | 0.00491 |
def run(dest, router, args, deadline=None, econtext=None):
"""
Run the command specified by `args` such that ``PATH`` searches for SSH by
the command will cause its attempt to use SSH to execute a remote program
to be redirected to use mitogen to execute that program using the context
`dest` instead... | 0.000473 |
def request(schema):
"""
Decorate a function with a request schema.
"""
def wrapper(func):
setattr(func, REQUEST, schema)
return func
return wrapper | 0.005405 |
def write_header(self, chunk):
"""Write to header.
Note: the header stream is only available to write before write body.
:param chunk: content to write to header
:except TChannelError:
Raise TChannelError if the response's flush() has been called
"""
if se... | 0.002699 |
async def executor(func, *args, **kwargs):
'''
Execute a function in an executor thread.
Args:
todo ((func,args,kwargs)): A todo tuple.
'''
def syncfunc():
return func(*args, **kwargs)
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, syncfunc) | 0.003185 |
def _deep_type(obj, checked, checked_len, depth = None, max_sample = None, get_type = None):
"""checked_len allows to operate with a fake length for checked.
This is necessary to ensure that each depth level operates based
on the same checked list subset. Otherwise our recursion detection
mechanism can ... | 0.005172 |
def lsumdiffsquared(x,y):
"""
Takes pairwise differences of the values in lists x and y, squares
these differences, and returns the sum of these squares.
Usage: lsumdiffsquared(x,y)
Returns: sum[(x[i]-y[i])**2]
"""
sds = 0
for i in range(len(x)):
sds = sds + (x[i]-y[i])**2
return sds | 0.006431 |
def sample_posterior(x,post,nsamples=1):
""" Returns nsamples from a tabulated posterior (not necessarily normalized)
"""
cdf = post.cumsum()
cdf /= cdf.max()
u = rand.random(size=nsamples)
inds = np.digitize(u,cdf)
return x[inds] | 0.01938 |
def update_custom_service_account(self, account, nickname, password):
"""
修改客服帐号。
:param account: 客服账号的用户名
:param nickname: 客服账号的昵称
:param password: 客服账号的密码
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/customservi... | 0.004016 |
def set_status(self, instance, status):
"""Sets the field status for up to 5 minutes."""
status_key = self.get_status_key(instance)
cache.set(status_key, status, timeout=300) | 0.010101 |
def _read(self):
"""Get next packet from transport.
:return: parsed packet in a tuple with message type and payload
:rtype: :py:class:`collections.namedtuple`
"""
raw_response = self.transport.receive()
response = Packet.parse(raw_response)
# FIXME
if re... | 0.005085 |
def do_rating_by_request(parser, token):
"""
Retrieves the ``Vote`` cast by a user on a particular object and
stores it in a context variable. If the user has not voted, the
context variable will be 0.
Example usage::
{% rating_by_request request on instance as vote %}
"""
... | 0.009079 |
def seoify_hyperlink(hyperlink):
"""Modify a hyperlink to make it SEO-friendly by replacing
hyphens with spaces and trimming multiple spaces.
:param hyperlink: URL to attempt to grab SEO from """
last_slash = hyperlink.rfind('/')
return re.sub(r' +|-', ' ', hyperlink[last_slash + 1:]) | 0.003268 |
def _lookup_key_parse(table_keys):
"""Return the order in which the stacks should be executed.
Args:
dependencies (dict): a dictionary where each key should be the
fully qualified name of a stack whose value is an array of
fully qualified stack names that the stack depends on. T... | 0.001901 |
def nfilter4(consens, hidx, arrayed):
""" applies max haplotypes filter returns pass and consens"""
## if less than two Hs then there is only one allele
if len(hidx) < 2:
return consens, 1
## store base calls for hetero sites
harray = arrayed[:, hidx]
## remove any reads that have N o... | 0.008887 |
def translations_lists(self):
'''Iterator over lists of content translations'''
return (getattr(self.generator, name) for name in
self.info.get('translations_lists', [])) | 0.009901 |
def find(pattern, root=os.curdir):
'''Helper around 'locate' '''
hits = ''
for F in locate(pattern, root):
hits = hits + F + '\n'
l = hits.split('\n')
if(not len(l[-1])): l.pop()
if len(l) == 1 and not len(l[0]):
return None
else:
return l | 0.010309 |
def _auth_key(nonce, username, password):
"""Get an auth key to use for authentication.
"""
digest = _password_digest(username, password)
md5hash = hashlib.md5()
data = "%s%s%s" % (nonce, username, digest)
md5hash.update(data.encode('utf-8'))
return _unicode(md5hash.hexdigest()) | 0.003257 |
def post(self, request):
"""
Save the provided data using the class' serializer.
Args:
request:
The request being made.
Returns:
An ``APIResponse`` instance. If the request was successful
the response will have a 200 status code and c... | 0.002829 |
def handle_integrity_error(cls, exception):
"""Handle integrity error exceptions."""
m = re.match(cls.MYSQL_INSERT_ERROR_REGEX,
exception.statement)
if not m:
raise exception
model = find_model_by_table_name(m.group('table'))
if not model:
... | 0.003231 |
def crop_or_pad(im, size, value=0):
"""
Crops an image in the center.
Parameters
----------
size : tuple, (height, width)
Finally size after cropping.
"""
diff = [im.shape[index] - size[index] for index in (0, 1)]
im2 = im[diff[0]//2:diff[0]//2 + size[0], diff[1]//2:diff[1]//2 +... | 0.002907 |
def send_music_message(
self,
user_id,
url,
hq_url,
thumb_media_id,
title=None,
description=None,
kf_account=None
):
"""
发送音乐消息。
注意如果你遇到了缩略图不能正常显示的问题, 不要慌张; 目前来看是微信服务器端的问题。
对此我们也无能为力 ( `#197 <https://github.com/whtsky/We... | 0.002335 |
def forget(self,rs):
"""
Remove a room from the list of managed rooms.
:Parameters:
- `rs`: the state object of the room.
:Types:
- `rs`: `MucRoomState`
"""
try:
del self.rooms[rs.room_jid.bare().as_unicode()]
except KeyError:
... | 0.008929 |
def _auth(self, username, password, pkey, key_filenames, allow_agent, look_for_keys):
"""
Try, in order:
- The key passed in, if one was passed in.
- Any key we can find through an SSH agent (if allowed).
- Any "id_rsa" or "id_dsa" key discoverable in ~/.ssh/ (if all... | 0.003794 |
def wrap_viscm(cmap, dpi=100, saveplot=False):
'''Evaluate goodness of colormap using perceptual deltas.
:param cmap: Colormap instance.
:param dpi=100: dpi for saved image.
:param saveplot=False: Whether to save the plot or not.
'''
from viscm import viscm
viscm(cmap)
fig = plt.gcf(... | 0.005338 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.