text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def jcal2jd(year, month, day):
"""Julian calendar date to Julian date.
The input and output are for the proleptic Julian calendar,
i.e., no consideration of historical usage of the calendar is
made.
Parameters
----------
year : int
Year as an integer.
month : int
Month ... | 0.000561 |
def getAdditionalImages(self):
'''
The same as calling ``client.getAdditionalImages(build.setID)``.
:returns: A list of URL strings.
:rtype: list
'''
self._additionalImages = self._client.getAdditionalImages(self.setID)
return self._additionalImages | 0.006515 |
def write_dict_to_file(file_path, obj):
"""
Write a dictionary of string keys to a file
"""
lines = []
for key, value in obj.items():
lines.append(key + ':' + repr(value) + '\n')
with open(file_path, 'w+') as file:
file.writelines(lines)
return None | 0.00339 |
def save_file(data, export_file):
"""Write data to a file."""
create_dir(os.path.dirname(export_file))
try:
with open(export_file, "w") as file:
file.write(data)
except PermissionError:
logging.warning("Couldn't write to %s.", export_file) | 0.003521 |
def refresh_stats(self):
"""
only need this when generating terrain (sea = 100 - perc_land at start).
This function forces a recount, otherwise just call the variables
"""
self.tot_pix = 0
self.tot_sea = 0
self.tot_land = 0
self.tot_blocked = 0
for... | 0.006993 |
def slice(self, x, y, width):
"""
Provide a slice of data from the buffer at the specified location
:param x: The X origin
:param y: The Y origin
:param width: The width of slice required
:return: The slice of tuples from the current double-buffer
"""
ret... | 0.005571 |
def execute(self):
"""Generate local DB, pulling metadata and data from RWSConnection"""
logging.info('Requesting view metadata for project %s' % self.project_name)
project_csv_meta = self.rws_connection.send_request(ProjectMetaDataRequest(self.project_name))
# Process it into a set of... | 0.004912 |
def update_keywords(self):
"""653 Free Keywords."""
for field in record_get_field_instances(self.record, '653', ind1='1'):
subs = field_get_subfields(field)
new_subs = []
if 'a' in subs:
for val in subs['a']:
new_subs.extend([('9', ... | 0.003824 |
def readShocks(self):
'''
Reads values of shock variables for the current period from history arrays. For each var-
iable X named in self.shock_vars, this attribute of self is set to self.X_hist[self.t_sim,:].
This method is only ever called if self.read_shocks is True. This can be ac... | 0.015083 |
def _read_mulliken(self):
"""
Parses Mulliken charges. Also parses spins given an unrestricted SCF.
"""
if self.data.get('unrestricted', []):
header_pattern = r"\-+\s+Ground-State Mulliken Net Atomic Charges\s+Atom\s+Charge \(a\.u\.\)\s+Spin\s\(a\.u\.\)\s+\-+"
tab... | 0.002801 |
def isentropic_efficiency(P1, P2, k, eta_s=None, eta_p=None):
r'''Calculates either isentropic or polytropic efficiency from the other
type of efficiency.
.. math::
\eta_s = \frac{(P_2/P_1)^{(k-1)/k}-1}
{(P_2/P_1)^{\frac{k-1}{k\eta_p}}-1}
.. math::
\eta_p = \frac{\left(k - 1\ri... | 0.000568 |
def create_data_types(self):
"""Map of standard playbook variable types to create method."""
return {
'Binary': self.create_binary,
'BinaryArray': self.create_binary_array,
'KeyValue': self.create_key_value,
'KeyValueArray': self.create_key_value_array,
... | 0.003795 |
def decompress(content, encoding, filename='N/A'):
"""
Decompress file content.
Required:
content (bytes): a file to be compressed
encoding: None (no compression) or 'gzip'
Optional:
filename (str:default:'N/A'): Used for debugging messages
Raises:
NotImplementedError if an unsupported ... | 0.017995 |
def set(self, opts, popsize=None, ccovfac=1, verbose=True):
"""Compute strategy parameters as a function
of dimension and population size """
alpha_cc = 1.0 # cc-correction for mueff, was zero before
def conedf(df, mu, N):
"""used for computing separable learning rate"""
... | 0.007708 |
def _bselect(self, selection, start_bindex, end_bindex):
""" add the given buffer indices to the given QItemSelection, both byte and char panes """
selection.select(self._model.index2qindexb(start_bindex), self._model.index2qindexb(end_bindex))
selection.select(self._model.index2qindexc(start_bi... | 0.013699 |
def parse(self):
"""
The function for parsing the JSON response to the vars dictionary.
"""
try:
self.vars['handle'] = self.json['handle'].strip()
except (KeyError, ValueError):
log.debug('Handle missing, json_output: {0}'.format(json.dumps(
... | 0.00088 |
def signal(signal=None):
'''
Signals Apache Solr to start, stop, or restart. Obviously this is only
going to work if the minion resides on the solr host. Additionally Solr
doesn't ship with an init script so one must be created.
signal : str (None)
The command to pass to the apache solr ini... | 0.001032 |
def summary_permutation(context_counts,
context_to_mut,
seq_context,
gene_seq,
score_dir,
num_permutations=10000,
min_frac=0.0,
min_recur=2,
... | 0.000938 |
def create_action(self):
"""Create actions associated with this widget."""
actions = {}
act = QAction(QIcon(ICON['step_prev']), 'Previous Step', self)
act.setShortcut('[')
act.triggered.connect(self.step_prev)
actions['step_prev'] = act
act = QAction(QIcon(ICON[... | 0.001487 |
def use_plenary_asset_composition_view(self):
"""Pass through to provider AssetCompositionSession.use_plenary_asset_composition_view"""
self._object_views['asset_composition'] = PLENARY
# self._get_provider_session('asset_composition_session') # To make sure the session is tracked
for se... | 0.008114 |
def _create_for_element(cls, element_obj, conn, namespace, classname,
propname=None, methodname=None, parametername=None):
# pylint: disable=line-too-long
"""
Return a new :class:`~pywbem.ValueMapping` instance for the specified
CIM element.
If a `Val... | 0.001092 |
def get_handler_stats(self):
''' Return handler read statistics
Returns a dictionary of managed handler data read statistics. The
format is primarily controlled by the
:func:`SocketStreamCapturer.dump_all_handler_stats` function::
{
<capture address>: <list ... | 0.005464 |
def describe_instance_health(self, load_balancer_name, instances=None):
"""
Get current state of all Instances registered to an Load Balancer.
:type load_balancer_name: string
:param load_balancer_name: The name of the Load Balancer
:type instances: List of strings
:par... | 0.003015 |
def download(name, filenames):
'''
Download a file from the virtual folder to the current working directory.
The files with the same names will be overwirtten.
\b
NAME: Name of a virtual folder.
FILENAMES: Paths of the files to be uploaded.
'''
with Session() as session:
try:
... | 0.00198 |
def generate_antonym(self, input_word):
""" Generate an antonym using a Synset
and its lemmas.
"""
results = []
synset = wordnet.synsets(input_word)
for i in synset:
if i.pos in ['n','v']:
for j in i.lemmas:
if j.antonyms():
... | 0.019928 |
def license(self, license):
"""
Sets the license of this DatasetPatchRequest.
Dataset license. Find additional info for allowed values [here](https://data.world/license-help).
:param license: The license of this DatasetPatchRequest.
:type: str
"""
allowed_values ... | 0.005935 |
def reset(self, clear=False):
""" Resets the widget to its initial state if ``clear`` parameter or
``clear_on_kernel_restart`` configuration setting is True, otherwise
prints a visual indication of the fact that the kernel restarted, but
does not clear the traces from previous usage of t... | 0.002992 |
def version_upload(fname,username="nibjb"):
"""Only scott should do this. Upload new version to site."""
print("popping up pasword window...")
password=TK_askPassword("FTP LOGIN","enter password for %s"%username)
if not password:
return
print("username:",username)
print("password:","*"*(... | 0.018106 |
def install(ctx, services, delete_after_install=False):
"""Install a honeypot service from the online library, local path or zipfile."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
... | 0.004093 |
def general_acquisition_info(metadata):
"""
General sentence on data acquisition. Should be first sentence in MRI data
acquisition section.
Parameters
----------
metadata : :obj:`dict`
The metadata for the dataset.
Returns
-------
out_str : :obj:`str`
Output string ... | 0.001212 |
def mag_to_fnu(self, mag):
"""SDSS *primed* magnitudes to F_ν. The primed magnitudes are the "USNO"
standard-star system defined in Smith+ (2002AJ....123.2121S) and
Fukugita+ (1996AJ....111.1748F). This system is anchored to the AB
magnitude system, and as far as I can tell it is not kno... | 0.002547 |
def temporary_path(self):
"""
A context manager that enables a reasonably short, general and
magic-less way to solve the :ref:`AtomicWrites`.
* On *entering*, it will create the parent directories so the
temporary_path is writeable right away.
This step uses :py:m... | 0.003153 |
def pyxwriter(self):
"""Update the pyx file."""
model = self.Model()
if hasattr(self, 'Parameters'):
model.parameters = self.Parameters(vars(self))
else:
model.parameters = parametertools.Parameters(vars(self))
if hasattr(self, 'Sequences'):
mo... | 0.003436 |
def get_cookbook_dirs(self, base_dir=None):
"""Find cookbook directories."""
if base_dir is None:
base_dir = self.env_root
cookbook_dirs = []
dirs_to_skip = set(['.git'])
for root, dirs, files in os.walk(base_dir): # pylint: disable=W0612
dirs[:] = [d fo... | 0.003401 |
def _pull_out_unaffected_blocks_rhs(rest, rhs, out_port, in_port):
"""Similar to :func:`_pull_out_unaffected_blocks_lhs` but on the RHS of a
series product self-feedback.
"""
_, block_index = rhs.index_in_block(in_port)
rest = tuple(rest)
bs = rhs.block_structure
(nbefore, nblock, nafter) = ... | 0.000915 |
def existing_analysis(using):
"""
Get the existing analysis for the `using` Elasticsearch connection
"""
es = connections.get_connection(using)
index_name = settings.ELASTICSEARCH_CONNECTIONS[using]['index_name']
if es.indices.exists(index=index_name):
return stringer(es.indices.get_sett... | 0.004739 |
def _is_xml_mode(self):
'''
Is Zypper's output is in XML format?
:return:
'''
return [itm for itm in self.XML_DIRECTIVES if itm in self.__cmd] and True or False | 0.014925 |
def remove_subproducts(self):
"""Removes all archived files subproducts associated with this DP"""
if not self.fullpath or not self.archived:
raise RuntimeError("""Can't remove a non-archived data product""")
for root, dirs, files in os.walk(self.subproduct_dir(), topdown=False):
... | 0.006359 |
def _glob_events_files(self, paths, recursive):
"""Find all tf events files under a list of paths recursively. """
event_files = []
for path in paths:
dirs = tf.gfile.Glob(path)
dirs = filter(lambda x: tf.gfile.IsDirectory(x), dirs)
for dir in dirs:
if recursive:
dir_fil... | 0.015152 |
def load(xmlstr):
"""
Loads the contents for this walkthrough from XML.
:param xmlstr | <str>
:return <XWalkthrough> || None
"""
try:
xml = ElementTree.fromstring(xmlstr)
except StandardError:
return No... | 0.010929 |
def divide(self, data_source_factory):
"""Divides the task according to the number of workers."""
data_length = data_source_factory.length()
data_interval_length = data_length / self.workers_number() + 1
current_index = 0
self.responses = []
while current_index < data_le... | 0.003527 |
def get_shark_field(self, fields):
"""
:fields: str[]
"""
out = super(BACK, self).get_shark_field(fields)
out.update({'acked_seqs': self.acked_seqs,
'bitmap_str': self.bitmap_str})
return out | 0.007722 |
def define_attribute(self, name, atype, data=None):
"""
Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'.
For nominal attributes, pass the possible values as data.
For date attributes, pass the format as data.
"""
... | 0.007519 |
def channel_ready_future(channel):
"""Creates a Future that tracks when a Channel is ready.
Cancelling the Future does not affect the channel's state machine.
It merely decouples the Future from channel state machine.
Args:
channel: A Channel object.
Returns:
A Future object that matures when the... | 0.002878 |
def validate(self, val):
"""
Validates that the val is in the list of values for this Enum.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
val
... | 0.003774 |
def optimise_signal(self, analytes, min_points=5,
threshold_mode='kde_first_max',
threshold_mult=1., x_bias=0, filt=True,
weights=None, mode='minimise',
samples=None, subset=None):
"""
Optimise data selectio... | 0.005905 |
def _docstring(self):
"""
Generate a docstring for the generated source file.
:return: new docstring
:rtype: str
"""
s = '"""' + "\n"
s += "webhook2lambda2sqs generated function source\n"
s += "this code was generated by webhook2lambda2sqs v%s\n" % VERSIO... | 0.003017 |
def parse(binary, **params):
"""Turns a TAR file into a frozen sample."""
binary = io.BytesIO(binary)
collection = list()
with tarfile.TarFile(fileobj=binary, mode='r') as tar:
for tar_info in tar.getmembers():
content_type, encoding = mimetypes.guess_type(tar_info.name)
... | 0.001715 |
def do(self, **kwargs):
"""
Here for compatibility with legacy clients only - DO NOT USE!!!
This is sort of mix of "append" and "insert": it puts commands in the list,
with some half smarts about which commands go at the front or back.
If you add multiple commands to the back in ... | 0.005445 |
def SetModel( self, model, adapter=None ):
"""Set our model object (root of the tree)"""
self.model = model
if adapter is not None:
self.adapter = adapter
self.UpdateDrawing() | 0.018265 |
def update_default(self, new_default, respect_none=False):
"""Update our current default with the new_default.
Args:
new_default: New default to set.
respect_none: Flag to determine if ``None`` is a valid value.
"""
if new_default is not None:
self.d... | 0.004728 |
def visit_delete(self, node): # XXX check if correct
"""return an astroid.Delete node as string"""
return "del %s" % ", ".join(child.accept(self) for child in node.targets) | 0.015873 |
def simplify(self) -> None:
"""Simplify this expression."""
self.raw = cast(T, z3.simplify(self.raw)) | 0.017094 |
def relevant_items(df):
"""
Dataframe with items used by cultural projects,
filtered by date and price.
"""
start_date = datetime(2013, 1, 1)
df['DataProjeto'] = pd.to_datetime(df['DataProjeto'])
# get only projects newer than start_date
# and items with price > 0
df = df[df.DataPr... | 0.002525 |
def user_provenance(self, document): # type: (ProvDocument) -> None
"""Add the user provenance."""
self.self_check()
(username, fullname) = _whoami()
if not self.full_name:
self.full_name = fullname
document.add_namespace(UUID)
document.add_namespace(ORCID)... | 0.001623 |
def get_appapi_params(self, prepay_id, timestamp=None, nonce_str=None):
"""
获取 APP 支付参数
:param prepay_id: 统一下单接口返回的 prepay_id 参数值
:param timestamp: 可选,时间戳,默认为当前时间戳
:param nonce_str: 可选,随机字符串,默认自动生成
:return: 签名
"""
data = {
'appid': self.appid,... | 0.002981 |
def get_release_task_attachments(self, project, release_id, environment_id, attempt_id, plan_id, type):
"""GetReleaseTaskAttachments.
[Preview API]
:param str project: Project ID or project name
:param int release_id:
:param int environment_id:
:param int attempt_id:
... | 0.00657 |
def format_lines(statements, lines):
"""Nicely format a list of line numbers.
Format a list of line numbers for printing by coalescing groups of lines as
long as the lines represent consecutive statements. This will coalesce
even if there are gaps between statements.
For example, if `statements` ... | 0.002088 |
def get_instance(self, payload):
"""
Build an instance of UserChannelInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance
:rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelInstance... | 0.007547 |
def getTypeDefinition(self, attribute=None):
"""If attribute is None, "type" is assumed, return the corresponding
representation of the global type definition (TypeDefinition),
or the local definition if don't find "type". To maintain backwards
compat, if attribute is provided call base... | 0.003509 |
def add_user_to_group(username, group):
"""Add a user to a group"""
cmd = ['gpasswd', '-a', username, group]
log("Adding user {} to group {}".format(username, group))
subprocess.check_call(cmd) | 0.004785 |
def get_sphere(coords, r=4, vox_dims=(2, 2, 2), dims=(91, 109, 91)):
""" # Return all points within r mm of coordinates. Generates a cube
and then discards all points outside sphere. Only returns values that
fall within the dimensions of the image."""
r = float(r)
xx, yy, zz = [slice(-r / vox_dims[i... | 0.001377 |
def p_type_ref(self, p):
'type_ref : ID args nullable'
p[0] = AstTypeRef(
path=self.path,
lineno=p.lineno(1),
lexpos=p.lexpos(1),
name=p[1],
args=p[2],
nullable=p[3],
ns=None,
) | 0.007018 |
def _eq(self, other):
"""Compare two nodes for equality."""
return (self.type, self.children) == (other.type, other.children) | 0.014184 |
def query_target_count(self, target):
"""Return the target count"""
reply = NVCtrlQueryTargetCountReplyRequest(display=self.display,
opcode=self.display.get_extension_major(extname),
target_type=target.type())
retu... | 0.005682 |
def _udf_name_and_parent_from_path(self, udf_path):
# type: (bytes) -> Tuple[bytes, udfmod.UDFFileEntry]
'''
An internal method to find the parent directory record and name given a
UDF path. If the parent is found, return a tuple containing the basename
of the path and the paren... | 0.006075 |
def get_vnetwork_vms_input_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_vms = ET.Element("get_vnetwork_vms")
config = get_vnetwork_vms
input = ET.SubElement(get_vnetwork_vms, "input")
name = ET.SubElement(input, "name... | 0.004425 |
def p_definition_list(p):
"""
definition_list : definition definition_list
| definition
"""
if len(p) == 3:
p[0] = p[1] + p[2]
elif len(p) == 2:
p[0] = p[1]
else:
raise RuntimeError("Invalid production rules 'p_action_list'") | 0.003413 |
def pairwise_align_sequences_to_representative(self, gapopen=10, gapextend=0.5, outdir=None,
engine='needle', parse=True, force_rerun=False):
"""Pairwise all sequences in the sequences attribute to the representative sequence. Stores the alignments
in t... | 0.007434 |
def _compute_lcptab(self, string, suftab):
"""Computes the LCP array in O(n) based on the input string & its suffix array.
Kasai et al. (2001).
"""
n = len(suftab)
rank = [0] * n
for i in xrange(n):
rank[suftab[i]] = i
lcptab = np.zeros(n, dtype=np.in... | 0.0048 |
def resource_from_data(self, data_element, resource=None):
"""
Converts the given data element to a resource.
:param data_element: object implementing
:class:`everest.representers.interfaces.IExplicitDataElement`
"""
return self._mapping.map_to_resource(data_element,... | 0.0059 |
def exclude_items(items, any_all=any, ignore_case=False, normalize_values=False, **kwargs):
"""Exclude items by matching metadata.
Note:
Metadata values are lowercased when ``normalized_values`` is ``True``,
so ``ignore_case`` is automatically set to ``True``.
Parameters:
items (list): A list of item dicts o... | 0.026359 |
def max_len(iterable, minimum=0):
"""Return the len() of the longest item in ``iterable`` or ``minimum``.
>>> max_len(['spam', 'ham'])
4
>>> max_len([])
0
>>> max_len(['ham'], 4)
4
"""
try:
result = max(map(len, iterable))
except ValueError:
result = minimum
... | 0.002717 |
async def read(self, *, decode: bool=False) -> Any:
"""Reads body part data.
decode: Decodes data following by encoding
method from Content-Encoding header. If it missed
data remains untouched
"""
if self._at_eof:
return b''
data = byt... | 0.007968 |
def is_method_of(method, object):
"""Decide whether ``method`` is contained within the MRO of ``object``."""
if not callable(method) or not hasattr(method, "__name__"):
return False
if inspect.ismethod(method):
return method.__self__ is object
for cls in inspect.getmro(object.__class__):... | 0.002364 |
def update(self, other_context):
"""
Updates this lookup set with the inputted options.
:param other_context | <dict> || <orb.Context>
"""
# convert a context instance into a dictionary
if isinstance(other_context, orb.Context):
other_context = copy.copy... | 0.003887 |
def TK_message(title,msg):
"""use the GUI to pop up a message."""
root = tkinter.Tk()
root.withdraw() #hide tk window
root.attributes("-topmost", True) #always on top
root.lift() #bring to top
tkinter.messagebox.showwarning(title, msg)
root.destroy() | 0.028777 |
def _create_target_dir_if_needed(self, target, depth_limit=20):
"""Creates the directory for the path given, recursively creating
parent directories when needed"""
if depth_limit <= 0:
raise FtpCreateDirsException('Depth limit exceeded')
if not target:
return
... | 0.003922 |
def setPlainText(self, txt, mimetype='text/x-python', encoding='utf-8'):
"""
Extends QCodeEdit.setPlainText to allow user to setPlainText without
mimetype (since the python syntax highlighter does not use it).
"""
try:
self.syntax_highlighter.docstrings[:] = []
... | 0.004024 |
def derivatives(self, x, y, n_sersic, R_sersic, k_eff, center_x=0, center_y=0):
"""
returns df/dx and df/dy of the function
"""
x_ = x - center_x
y_ = y - center_y
r = np.sqrt(x_**2 + y_**2)
if isinstance(r, int) or isinstance(r, float):
r = max(self._... | 0.005525 |
def ordinal_encoding(X_in, mapping=None, cols=None, handle_unknown='value', handle_missing='value'):
"""
Ordinal encoding uses a single column of integers to represent the classes. An optional mapping dict can be passed
in, in this case we use the knowledge that there is some true order to the c... | 0.003521 |
def has_add_permission(self):
"""
Returns a boolean if the current user has permission to add another object of the same
type which is being viewed/edited.
"""
has_permission = False
if self.user is not None:
# We don't check for the object level permission -... | 0.006957 |
def spelling(self):
"""Return the spelling of the entity pointed at by the cursor."""
if not hasattr(self, '_spelling'):
self._spelling = conf.lib.clang_getCursorSpelling(self)
return self._spelling | 0.008511 |
def refresh_oauth_credential(self):
"""Refresh session's OAuth 2.0 credentials if they are stale."""
if self.session.token_type == auth.SERVER_TOKEN_TYPE:
return
credential = self.session.oauth2credential
if credential.is_stale():
refresh_session = refresh_access... | 0.005249 |
def set_status(self, message=None, console_url=None, status_links=None):
"""Sets the current status of this pipeline.
This method is purposefully non-transactional. Updates are written to the
datastore immediately and overwrite all existing statuses.
Args:
message: (optional) Overall status mess... | 0.005598 |
def _lnk_delete_link(self, link_name):
"""Removes a link from disk"""
translated_name = '/' + self._trajectory_name + '/' + link_name.replace('.','/')
link = self._hdf5file.get_node(where=translated_name)
link._f_remove() | 0.01581 |
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
"""
formatstr = str(self.resolve_option("format"))
expanded = self.storagehandler.expand(formatstr)
self._output.append(Token(exp... | 0.005764 |
def _generate_ngram_table(self, output_dir, labels, results):
"""Returns an HTML table containing data on each n-gram in
`results`."""
html = []
grouped = results.groupby(constants.NGRAM_FIELDNAME)
row_template = self._generate_ngram_row_template(labels)
for name, group i... | 0.004073 |
def to_bytes(self):
'''
Create bytes from properties
'''
# Verify that the properties make sense
self.sanitize()
# Write the next header type
bitstream = BitStream('uint:8=%d' % self.next_header)
# Add the reserved bits
bitstream += BitStream(8)
... | 0.002729 |
def find_characteristic(self, uuid):
"""Return the first child characteristic found that has the specified
UUID. Will return None if no characteristic that matches is found.
"""
for char in self.list_characteristics():
if char.uuid == uuid:
return char
... | 0.006006 |
async def probe_message(self, _message, context):
"""Handle a probe message.
See :meth:`AbstractDeviceAdapter.probe`.
"""
client_id = context.user_data
await self.probe(client_id) | 0.00905 |
def getActiveProperties(self):
""" Returns the non-zero accidental dignities. """
score = self.getScoreProperties()
return {key: value for (key, value) in score.items()
if value != 0} | 0.008969 |
def f0(E, fermi, T):
"""
Returns the equilibrium fermi-dirac.
Args:
E (float): energy in eV
fermi (float): the fermi level in eV
T (float): the temperature in kelvin
"""
return 1. / (1. + np.exp((E - fermi) / (_cd("Boltzmann constant in eV/K") * T))) | 0.006803 |
def limit (s, length=72):
"""If the length of the string exceeds the given limit, it will be cut
off and three dots will be appended.
@param s: the string to limit
@type s: string
@param length: maximum length
@type length: non-negative integer
@return: limited string, at most length+3 char... | 0.003774 |
def segment(text: str) -> str:
"""
Enhanced Thai Character Cluster (ETCC)
:param string text: word input
:return: etcc
"""
if not text or not isinstance(text, str):
return ""
if re.search(r"[เแ]" + _C + r"[" + "".join(_UV) + r"]" + r"\w", text):
search = re.findall(r"[เแ]... | 0.00213 |
def expr_labelfunc(leaf_renderer=str, fallback=str):
"""Factory for function ``labelfunc(expr, is_leaf)``
It has the following behavior:
* If ``is_leaf`` is True, return ``leaf_renderer(expr)``.
* Otherwise,
- if `expr` is an Expression, return a custom string similar to
:func:`~qnet.p... | 0.001013 |
def parse(expected, query):
"""
Parse query parameters.
:type expected: `dict` mapping `bytes` to `callable`
:param expected: Mapping of query argument names to argument parsing
callables.
:type query: `dict` mapping `bytes` to `list` of `bytes`
:param query: Mapping of query argumen... | 0.001408 |
def _make_marker_token(self, type_):
"""Make a token that has no content"""
tok = Token(type_,
'',
self.line,
self.line_num,
self.start,
self.start)
return tok | 0.007067 |
def create_file_from_stream(
self, share_name, directory_name, file_name, stream, count,
content_settings=None, metadata=None, progress_callback=None,
max_connections=1, max_retries=5, retry_wait=1.0, timeout=None):
'''
Creates a new file from a file/stream, or updates the conten... | 0.001585 |
def check_categories(lines):
'''
find out how many row and col categories are available
'''
# count the number of row categories
rcat_line = lines[0].split('\t')
# calc the number of row names and categories
num_rc = 0
found_end = False
# skip first tab
for inst_string in rcat_line[1:]:
if ins... | 0.023622 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.