repo
stringlengths 1
29
| path
stringlengths 24
332
| code
stringlengths 39
579k
|
---|---|---|
CWR-API-0.0.40 | CWR-API-0.0.40//cwr/parser/encoder/standart/record.pyclass:CwrRecordEncoder/try_encode | @staticmethod
def try_encode(field_encoders, entity_dict):
"""
Inner encoding and try return string from entity dictionary
:param field_encoders:
:param entity_dict:
:return:
"""
result = ''
for field_encoder in field_encoders:
try:
result += field_encoder.encode(entity_dict)
except KeyError as e:
return False
return result
|
text_models | text_models//vocabulary.pyclass:Vocabulary/get_date | @staticmethod
def get_date(filename):
"""
Obtain the date from the filename. The format is YYMMDD.
:param filename: Filename
:type filename: str
:rtype: datetime
"""
import datetime
d = filename.split('/')[-1].split('.')[0]
return datetime.datetime(year=int(d[:2]) + 2000, month=int(d[2:4]), day
=int(d[-2:]))
|
pya2l-0.0.1 | pya2l-0.0.1//pya2l/parser/grammar/parser.pyclass:A2lParser/p_header_optional_list_optional | @staticmethod
def p_header_optional_list_optional(p):
"""header_optional_list_optional : empty
| header_optional_list"""
p[0] = tuple() if p[1] is None else p[1]
|
bdsf | bdsf//functions.pyfile:/functions.py:function:gaus_pixval/gaus_pixval | def gaus_pixval(g, pix):
""" Calculates the value at a pixel pix due to a gaussian object g. """
from .const import fwsig, pi
from math import sin, cos, exp
cen = g.centre_pix
peak = g.peak_flux
bmaj_p, bmin_p, bpa_p = g.size_pix
a4 = bmaj_p / fwsig
a5 = bmin_p / fwsig
a6 = (bpa_p + 90.0) * pi / 180.0
spa = sin(a6)
cpa = cos(a6)
dr1 = ((pix[0] - cen[0]) * cpa + (pix[1] - cen[1]) * spa) / a4
dr2 = ((pix[1] - cen[1]) * cpa - (pix[0] - cen[0]) * spa) / a5
pixval = peak * exp(-0.5 * (dr1 * dr1 + dr2 * dr2))
return pixval
|
sugartex-0.1.16 | sugartex-0.1.16//versioneer.pyfile:/versioneer.py:function:render_git_describe_long/render_git_describe_long | def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
else:
rendered = pieces['short']
if pieces['dirty']:
rendered += '-dirty'
return rendered
|
PyElastica-0.0.2 | PyElastica-0.0.2//elastica/utils.pyfile:/elastica/utils.py:function:perm_parity/perm_parity | def perm_parity(lst):
"""
Given a permutation of the digits 0..N in order as a list,
returns its parity (or sign): +1 for even parity; -1 for odd.
Parameters
----------
lst
Returns
-------
Credits
-------
Code obtained with thanks from https://code.activestate.com/recipes/578227-generate-the-parity-or-sign-of-a-permutation/
licensed with a MIT License
"""
parity = 1
for i in range(0, len(lst) - 1):
if lst[i] != i:
parity *= -1
mn = min(range(i, len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], lst[i]
return parity
|
mne | mne//viz/evoked.pyfile:/viz/evoked.py:function:_add_nave/_add_nave | def _add_nave(ax, nave):
"""Add nave to axes."""
if nave is not None:
ax.annotate('N$_{\\mathrm{ave}}$=%d' % nave, ha='left', va='bottom',
xy=(0, 1), xycoords='axes fraction', xytext=(0, 5), textcoords=
'offset pixels')
|
AccessControl-4.2 | AccessControl-4.2//src/AccessControl/interfaces.pyclass:IUser/getUserName | def getUserName():
"""Get the name used by the user to log into the system.
Note that this may not be identical to the user's 'getId' (to allow
users to change their login names without changing their identity).
"""
|
cltk-0.1.117 | cltk-0.1.117//cltk/inflection/old_norse/nouns.pyfile:/cltk/inflection/old_norse/nouns.py:function:decline_weak_feminine_noun/decline_weak_feminine_noun | def decline_weak_feminine_noun(ns: str, gs: str, np: str):
"""
Gives the full declension of weak feminine nouns.
>>> decline_weak_feminine_noun("saga", "sögu", "sögur")
saga
sögu
sögu
sögu
sögur
sögur
sögum
sagna
>>> decline_weak_feminine_noun("kona", "konu", "konur")
kona
konu
konu
konu
konur
konur
konum
kvenna
>>> decline_weak_feminine_noun("kirkja", "kirkju", "kirkjur")
kirkja
kirkju
kirkju
kirkju
kirkjur
kirkjur
kirkjum
kirkna
>>> decline_weak_feminine_noun("völva", "völu", "völur")
völva
völu
völu
völu
völur
völur
völum
völna
>>> decline_weak_feminine_noun("speki", "speki", "")
speki
speki
speki
speki
>>> decline_weak_feminine_noun("reiði", "reiði", "")
reiði
reiði
reiði
reiði
>>> decline_weak_feminine_noun("elli", "elli", "")
elli
elli
elli
elli
>>> decline_weak_feminine_noun("frœði", "frœði", "")
frœði
frœði
frœði
frœði
It is to note that the genitive plural of völva is not attested so the given form is analogously reconstructed.
The main pattern is:
-a
-u
-u
-u
-ur
-ur
-um
-na
:param ns: nominative singular
:param gs: genitive singular
:param np: nominative plural
:return:
"""
if ns[-1] == 'i' and gs[-1] == 'i' and not np:
print(ns)
print(ns)
print(ns)
print(ns)
else:
print(ns)
print(gs)
print(gs)
print(gs)
print(np)
print(np)
print(np[:-1] + 'm')
if ns == 'kona':
print('kvenna')
elif ns[-2] == 'v' or ns[-2] == 'j':
print(ns[:-2] + 'na')
else:
print(ns[:-1] + 'na')
|
xiPy-1.0.0rc1 | xiPy-1.0.0rc1//xiPy/paho_mqtt_client.pyfile:/xiPy/paho_mqtt_client.py:function:topic_matches_sub/topic_matches_sub | def topic_matches_sub(sub, topic):
"""Check whether a topic matches a subscription.
For example:
foo/bar would match the subscription foo/# or +/bar
non/matching would not match the subscription non/+/+
"""
result = True
multilevel_wildcard = False
slen = len(sub)
tlen = len(topic)
if slen > 0 and tlen > 0:
if sub[0] == '$' and topic[0] != '$' or topic[0] == '$' and sub[0
] != '$':
return False
spos = 0
tpos = 0
while spos < slen and tpos < tlen:
if sub[spos] == topic[tpos]:
if tpos == tlen - 1:
if spos == slen - 3 and sub[spos + 1] == '/' and sub[spos + 2
] == '#':
result = True
multilevel_wildcard = True
break
spos += 1
tpos += 1
if tpos == tlen and spos == slen - 1 and sub[spos] == '+':
spos += 1
result = True
break
elif sub[spos] == '+':
spos += 1
while tpos < tlen and topic[tpos] != '/':
tpos += 1
if tpos == tlen and spos == slen:
result = True
break
elif sub[spos] == '#':
multilevel_wildcard = True
if spos + 1 != slen:
result = False
break
else:
result = True
break
else:
result = False
break
if not multilevel_wildcard and (tpos < tlen or spos < slen):
result = False
return result
|
dgl_cu100-0.4.3.post2.data | dgl_cu100-0.4.3.post2.data//purelib/dgl/backend/backend.pyfile:/purelib/dgl/backend/backend.py:function:copy_reduce/copy_reduce | def copy_reduce(reducer, graph, target, in_data, out_size, in_map, out_map):
"""Copy target data and perform reduce based on graph structure.
Parameters
----------
reducer : str
Type of reduction: be 'sum', 'max', 'min', 'mean', 'prod', 'none' (no
reduction)
graph : GraphIndex
The graph
target : int
The input target (src, dst, edge)
in_data : Tensor
The input data
out_size : int
Size of first dimension of output data
in_map : tuple
Two input id mapping arrays, one for forward, the other for backward
out_map : tuple
Two output id mapping arrays, one for forward, the other for backward
Returns
-------
Tensor
The result.
"""
pass
|
lifelib | lifelib//projects/ifrs17sim/projection.pyfile:/projects/ifrs17sim/projection.py:function:SizeBenefitAccHosp/SizeBenefitAccHosp | def SizeBenefitAccHosp(t):
"""Accidental hospitalization benefit per policy"""
return 0
|
fluids-0.1.78 | fluids-0.1.78//fluids/fittings.pyfile:/fluids/fittings.py:function:diffuser_curved/diffuser_curved | def diffuser_curved(Di1, Di2, l):
"""Returns loss coefficient for any curved wall pipe expansion
as shown in [1]_.
.. math::
K_1 = \\phi(1.43-1.3\\beta^2)(1-\\beta^2)^2
.. math::
\\phi = 1.01 - 0.624\\frac{l}{d_1} + 0.30\\left(\\frac{l}{d_1}\\right)^2
- 0.074\\left(\\frac{l}{d_1}\\right)^3 + 0.0070\\left(\\frac{l}{d_1}\\right)^4
.. figure:: fittings/curved_wall_diffuser.png
:scale: 25 %
:alt: diffuser curved; after [1]_
Parameters
----------
Di1 : float
Inside diameter of original pipe (smaller), [m]
Di2 : float
Inside diameter of following pipe (larger), [m]
l : float
Length of the curve along the pipe axis, [m]
Returns
-------
K : float
Loss coefficient [-]
Notes
-----
Beta^2 should be between 0.1 and 0.9.
A small mismatch between tabulated values of this function in table 11.3
is observed with the equation presented.
Examples
--------
>>> diffuser_curved(Di1=.25**0.5, Di2=1., l=2.)
0.2299781250000002
References
----------
.. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical
and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.
"""
beta = Di1 / Di2
phi = 1.01 - 0.624 * l / Di1 + 0.3 * (l / Di1) ** 2 - 0.074 * (l / Di1
) ** 3 + 0.007 * (l / Di1) ** 4
return phi * (1.43 - 1.3 * beta ** 2) * (1 - beta ** 2) ** 2
|
att-bill-splitter-0.4.9 | att-bill-splitter-0.4.9//attbillsplitter/entrypoints.pyfile:/attbillsplitter/entrypoints.py:function:print_summary/print_summary | def print_summary():
"""Print wireless monthly summary among users."""
from attbillsplitter.services import run_print_summary
run_print_summary()
|
pdb-tools-2.0.1 | pdb-tools-2.0.1//pdbtools/pdb_head.pyfile:/pdbtools/pdb_head.py:function:pad_line/pad_line | def pad_line(line):
"""Helper function to pad line to 80 characters in case it is shorter"""
size_of_line = len(line)
if size_of_line < 80:
padding = 80 - size_of_line + 1
line = line.strip('\n') + ' ' * padding + '\n'
return line[:81]
|
dolosse | dolosse//hardware/xia/pixie16/list_mode_data_mask.pyclass:ListModeDataMask/channel | @staticmethod
def channel():
""" Provides the mask needed to decode the Channel from Word 0 """
return 15, 0
|
yafowil-2.3.2 | yafowil-2.3.2//src/yafowil/common.pyfile:/src/yafowil/common.py:function:generic_positional_rendering_helper/generic_positional_rendering_helper | def generic_positional_rendering_helper(tagname, message, attrs, rendered,
pos, tag):
"""returns new tag with rendered content dependent on position
tagname
name of new tag, ie. div, p, label and so on
message
text included in new tag
attrs
attributes on new tag
rendered
prior rendered text
pos
position how to place the newtag relative to the prior rendered:
'before'='<newtag>message</newtag>rendered',
'after' ='<newtag>message</newtag>'
'inner-before'= <newtag>message rendered</newtag>
'inner-after'= <newtag>rendered message</newtag>
"""
if pos not in ['before', 'after', 'inner-before', 'inner-after']:
raise ValueError('Invalid value for position "{0}"'.format(pos))
if pos.startswith('inner'):
if pos.endswith('before'):
inner = message, rendered
else:
inner = rendered, message
return tag(tagname, *inner, **attrs)
else:
newtag = tag(tagname, message, **attrs)
if pos == 'before':
return newtag + rendered
return rendered + newtag
|
wrong | wrong//sort/sort.pyfile:/sort/sort.py:function:sort_3/sort_3 | def sort_3(l):
"""
An incorrect implementation of the sort() function. Sorts given list in
reverse order.
"""
l.sort(reverse=True)
|
taskcat-0.9.17 | taskcat-0.9.17//taskcat/_project_generator.pyclass:FilesystemService/generate_file | @staticmethod
def generate_file(content, destination_path):
"""
Given the generated content and a destination path, it will
write that content to a file in that path.
"""
with open(destination_path, 'w') as file_handle:
file_handle.write(content)
|
qtip | qtip//reporter/filters.pyfile:/reporter/filters.py:function:_justify_pair/_justify_pair | def _justify_pair(pair, width=80, padding_with='.'):
"""align first element along the left margin, second along the right, padding spaces"""
n = width - len(pair[0])
return '{key}{value:{c}>{n}}'.format(key=pair[0], value=pair[1], c=
padding_with, n=n)
|
mom-0.1.3 | mom-0.1.3//mom/builtins.pyfile:/mom/builtins.py:function:integer_bit_length/integer_bit_length | def integer_bit_length(number):
"""
Number of bits needed to represent a integer excluding any prefix
0 bits.
:param number:
Integer value. If num is 0, returns 0. Only the absolute value of the
number is considered. Therefore, signed integers will be abs(num)
before the number's bit length is determined.
:returns:
Returns the number of bits in the integer.
"""
if number == 0:
return 0
if number < 0:
number = -number
_ = number & 1
hex_num = '%x' % number
return (len(hex_num) - 1) * 4 + {'0': 0, '1': 1, '2': 2, '3': 2, '4': 3,
'5': 3, '6': 3, '7': 3, '8': 4, '9': 4, 'a': 4, 'b': 4, 'c': 4, 'd':
4, 'e': 4, 'f': 4}[hex_num[0]]
|
smalisca-0.2 | smalisca-0.2//smalisca/modules/module_graph.pyfile:/smalisca/modules/module_graph.py:function:add_edges/add_edges | def add_edges(graph, edges):
"""Add edge(s) to graph
Args:
graph (Graph): Graph to add edge(s) to
edges (list): List of edges
Returns:
Graph: Return the modified graph
"""
for e in edges:
if isinstance(e[0], tuple):
graph.edge(*e[0], **e[1])
else:
graph.edge(*e)
return graph
|
GSAS-II-WONDER_linux-1.0.1 | GSAS-II-WONDER_linux-1.0.1//GSAS-II-WONDER/GSASIIspc.pyfile:/GSAS-II-WONDER/GSASIIspc.py:function:SGPtGroup/SGPtGroup | def SGPtGroup(SGData):
"""
Determine point group of the space group - done after space group symbol has
been evaluated by SpcGroup. Only short symbols are allowed
:param SGData: from :func SpcGroup
:returns: SSGPtGrp & SSGKl (only defaults for Mono & Ortho)
"""
Flds = SGData['SpGrp'].split()
if len(Flds) < 2:
return '', []
if SGData['SGLaue'] == '-1':
if '-' in Flds[1]:
return '-1', [-1]
else:
return '1', [1]
elif SGData['SGLaue'] == '2/m':
if '/' in SGData['SpGrp']:
return '2/m', [-1, 1]
elif '2' in SGData['SpGrp']:
return '2', [-1]
else:
return 'm', [1]
elif SGData['SGLaue'] == 'mmm':
if SGData['SpGrp'].count('2') == 3:
return '222', [-1, -1, -1]
elif SGData['SpGrp'].count('2') == 1:
if SGData['SGPolax'] == 'x':
return '2mm', [-1, 1, 1]
elif SGData['SGPolax'] == 'y':
return 'm2m', [1, -1, 1]
elif SGData['SGPolax'] == 'z':
return 'mm2', [1, 1, -1]
else:
return 'mmm', [1, 1, 1]
elif SGData['SGLaue'] == '4/m':
if '/' in SGData['SpGrp']:
return '4/m', [1, -1]
elif '-' in Flds[1]:
return '-4', [-1]
else:
return '4', [1]
elif SGData['SGLaue'] == '4/mmm':
if '/' in SGData['SpGrp']:
return '4/mmm', [1, -1, 1, 1]
elif '-' in Flds[1]:
if '2' in Flds[2]:
return '-42m', [-1, -1, 1]
else:
return '-4m2', [-1, 1, -1]
elif '2' in Flds[2:]:
return '422', [1, -1, -1]
else:
return '4mm', [1, 1, 1]
elif SGData['SGLaue'] in ['3', '3R']:
if '-' in Flds[1]:
return '-3', [-1]
else:
return '3', [1]
elif SGData['SGLaue'] == '3mR' or 'R' in Flds[0]:
if '2' in Flds[2]:
return '32', [1, -1]
elif '-' in Flds[1]:
return '-3m', [-1, 1]
else:
return '3m', [1, 1]
elif SGData['SGLaue'] == '3m1':
if '2' in Flds[2]:
return '321', [1, -1, 1]
elif '-' in Flds[1]:
return '-3m1', [-1, 1, 1]
else:
return '3m1', [1, 1, 1]
elif SGData['SGLaue'] == '31m':
if '2' in Flds[3]:
return '312', [1, 1, -1]
elif '-' in Flds[1]:
return '-31m', [-1, 1, 1]
else:
return '31m', [1, 1, 1]
elif SGData['SGLaue'] == '6/m':
if '/' in SGData['SpGrp']:
return '6/m', [1, -1]
elif '-' in SGData['SpGrp']:
return '-6', [-1]
else:
return '6', [1]
elif SGData['SGLaue'] == '6/mmm':
if '/' in SGData['SpGrp']:
return '6/mmm', [1, -1, 1, 1]
elif '-' in Flds[1]:
if '2' in Flds[2]:
return '-62m', [-1, -1, 1]
else:
return '-6m2', [-1, 1, -1]
elif '2' in Flds[2:]:
return '622', [1, -1, -1]
else:
return '6mm', [1, 1, 1]
elif SGData['SGLaue'] == 'm3':
if '2' in Flds[1]:
return '23', []
else:
return 'm3', []
elif SGData['SGLaue'] == 'm3m':
if '4' in Flds[1]:
if '-' in Flds[1]:
return '-43m', []
else:
return '432', []
else:
return 'm3m', []
|
temp2temp | temp2temp//temperature.pyclass:Kelvin/to_romer | @staticmethod
def to_romer(kelvin):
""" Convert kelvin to romer """
return (kelvin - 273.15) * (21 / 40) + 7.5
|
icemac.ab.calexport-1.10 | icemac.ab.calexport-1.10//src/icemac/ab/calexport/browser/export.pyfile:/src/icemac/ab/calexport/browser/export.py:function:export_month/export_month | def export_month(form, action):
"""Form handler function exporting the current month."""
calendar = form.getContent().context
form.request.response.redirect(form.url(calendar, 'export-month'))
|
ncbi-genome-download-0.2.12 | ncbi-genome-download-0.2.12//ncbi_genome_download/core.pyfile:/ncbi_genome_download/core.py:function:fill_metadata/fill_metadata | def fill_metadata(jobs, entry, mtable):
"""Fill the metadata table with the info on the downloaded files.
Parameters
----------
jobs: List[DownloadJob]
List of all different file format download jobs for an entry
entry:
An assembly entry describing the current download jobs
mtable:
Metadata table object to write into
Returns
-------
None
"""
for job in jobs:
if job.full_url is not None:
mtable.add(entry, job.local_file)
|
evoke-6.0 | evoke-6.0//evoke/lib/library.pyfile:/evoke/lib/library.py:function:csv_format/csv_format | def csv_format(s):
"""
cleans syntax problems for csv output
"""
s = s.replace('"', "'")
s = s.replace('\n', ' ')
s = s.replace('\x00D', '')
return '"%s"' % s
|
incubator | incubator//core/parsing.pyfile:/core/parsing.py:function:get_name_and_tag/get_name_and_tag | def get_name_and_tag(name):
"""
Split the name if the image into tuple (name, tag).
* name: (str) name of the image
* **return:** tuple:
- repository
- tag
"""
name_parts = name.split(':')
if len(name_parts) == 2:
repo = name_parts[0]
tag = name_parts[1]
else:
repo = name
tag = 'latest'
return repo, tag
|
txkube | txkube//_swagger.pyclass:ITypeModel/pclass_field_for_type | def pclass_field_for_type(required, default):
"""
Create a pyrsistent field for this model object for use with a PClass.
:param bool required: Whether the field should be mandatory or
optional.
:param default: A value which the field will take on if not supplied
with another one at initialization time. May be ``NO_DEFAULT`` to
omit this behavior.
:return: A pyrsistent field descriptor for an attribute which is
usable with values of this type.
"""
|
ibmsecurity | ibmsecurity//isds/available_updates.pyfile:/isds/available_updates.py:function:discover/discover | def discover(isdsAppliance, check_mode=False, force=False):
"""
Discover available updates
"""
return isdsAppliance.invoke_get('Discover available updates',
'/updates/available/discover')
|
ga4gh_client-0.0.5 | ga4gh_client-0.0.5//ga4gh/client/cli.pyfile:/ga4gh/client/cli.py:function:addPhenotypeSearchOptions/addPhenotypeSearchOptions | def addPhenotypeSearchOptions(parser):
"""
Adds options to a phenotype searches command line parser.
"""
parser.add_argument('--phenotype_association_set_id', '-s', default=
None, help=
'Only return phenotypes from this phenotype_association_set.')
parser.add_argument('--phenotype_id', '-p', default=None, help=
'Only return this phenotype.')
parser.add_argument('--description', '-d', default=None, help=
'Only return phenotypes matching this description.')
parser.add_argument('--age_of_onset', '-a', default=None, help=
'Only return phenotypes with this age_of_onset.')
parser.add_argument('--type', '-T', default=None, help=
'Only return phenotypes with this type.')
|
piplapis-python-5.2.1 | piplapis-python-5.2.1//piplapis/error.pyclass:APIError/from_dict | @classmethod
def from_dict(cls, d):
"""Transform the dict to a error object and return the error."""
return cls(d.get('error'), d.get('@http_status_code'), d.get('warnings'))
|
workspace | workspace//scm.pyfile:/scm.py:function:extract_commit_msgs/extract_commit_msgs | def extract_commit_msgs(output, is_git=True):
""" Returns a list of commit msgs from the given output. """
msgs = []
if output:
msg = []
for line in output.split('\n'):
if not line:
continue
is_commit_msg = line.startswith(' ') or not line
if is_commit_msg:
if is_git and line.startswith(' '):
line = line[4:]
msg.append(line)
elif msg:
msgs.append('\n'.join(msg))
msg = []
if msg:
msgs.append('\n'.join(msg))
return msgs
|
fake-bpy-module-2.80-20200428 | fake-bpy-module-2.80-20200428//bpy/ops/mesh.pyfile:/bpy/ops/mesh.py:function:solidify/solidify | def solidify(thickness: float=0.01):
"""Create a solid skin by extruding, compensating for sharp angles
:param thickness: Thickness
:type thickness: float
"""
pass
|
melusine | melusine//prepare_email/metadata_engineering.pyclass:MetaDate/get_dayofweek | @staticmethod
def get_dayofweek(row):
"""Get day of the week from date"""
x = row['date']
try:
return x.dayofweek
except Exception as e:
return 0
|
physics-tenpy-0.5.0 | physics-tenpy-0.5.0//tenpy/algorithms/network_contractor.pyfile:/tenpy/algorithms/network_contractor.py:function:_find_in_sequence/_find_in_sequence | def _find_in_sequence(indices, sequence):
"""Helper function for ncon.
check if the supplied indices appear at the beginning of sequence
Parameters
----------
indices : list of int
sequence : list of int
Returns
-------
idcs : list of int
All the given indices that appear consecutively at the front of sequence
"""
ptr = 0
while ptr < len(sequence) and sequence[ptr] in indices:
ptr = ptr + 1
rtn_indices = sequence[:ptr]
sequence = sequence[ptr:]
return rtn_indices, sequence
|
neocortex | neocortex//app.pyfile:/app.py:function:configure_app/configure_app | def configure_app(app, testing=False):
"""set configuration for application
"""
app.config.from_object('neocortex.config')
if testing is True:
app.config.from_object('neocortex.configtest')
else:
app.config.from_envvar('NEOCORTEX_CONFIG', silent=True)
|
barril-1.9.0 | barril-1.9.0//src/barril/units/_abstractvaluewithquantity.pyclass:AbstractValueWithQuantityObject/CreateWithQuantity | @classmethod
def CreateWithQuantity(cls, quantity, *args, **kwargs):
"""
This is a secondary interface for creating the object with an existing quantity.
:param Quantity quantity:
The quantity for this object
@param args and kwargs: Those are dependent on the actual class -- this parameters
are passed directly to _InternalCreateWithQuantity.
"""
stub = cls.__Stub()
stub.__class__ = cls
stub._InternalCreateWithQuantity(quantity, *args, **kwargs)
return stub
|
pyobo | pyobo//struct/utils.pyfile:/struct/utils.py:function:comma_separate/comma_separate | def comma_separate(elements) ->str:
"""Map a list to strings and make comma separated."""
return ', '.join(map(str, elements))
|
apkkit-0.6.0.1 | apkkit-0.6.0.1//apkkit/portage.pyfile:/apkkit/portage.py:function:_fatal/_fatal | def _fatal(msg):
"""Print a fatal error to the user.
:param str msg:
The message to print.
"""
print('\x1b[01;31m *\x1b[01;39m An APK cannot be created.')
print('\x1b[01;31m *\x1b[00;39m {msg}'.format(msg=msg))
|
Louie-latest-1.3.1 | Louie-latest-1.3.1//louie/saferef.pyclass:BoundMethodWeakref/calculate_key | def calculate_key(cls, target):
"""Calculate the reference key for this reference.
Currently this is a two-tuple of the id()'s of the target
object and the target function respectively.
"""
try:
return id(target.im_self), id(target.im_func)
except AttributeError:
return id(target.__self__), id(target.__func__)
|
capitains-hook-1.0.0 | capitains-hook-1.0.0//Hook/ext.pyclass:HookUI/f_btn | @staticmethod
def f_btn(boolean):
""" Return btn bs3 class depending on status
:param boolean: Boolean
:return: "btn-success" and "btn-danger" depending on boolean
"""
if boolean:
return 'btn-success'
return 'btn-danger'
|
fineart-superset-0.18.5 | fineart-superset-0.18.5//superset/db_engine_specs.pyclass:BaseEngineSpec/extra_table_metadata | @classmethod
def extra_table_metadata(cls, database, table_name, schema_name):
"""Returns engine-specific table metadata"""
return {}
|
h2-3.2.0 | h2-3.2.0//h2/utilities.pyfile:/h2/utilities.py:function:is_informational_response/is_informational_response | def is_informational_response(headers):
"""
Searches a header block for a :status header to confirm that a given
collection of headers are an informational response. Assumes the header
block is well formed: that is, that the HTTP/2 special headers are first
in the block, and so that it can stop looking when it finds the first
header field whose name does not begin with a colon.
:param headers: The HTTP/2 header block.
:returns: A boolean indicating if this is an informational response.
"""
for n, v in headers:
if isinstance(n, bytes):
sigil = b':'
status = b':status'
informational_start = b'1'
else:
sigil = u':'
status = u':status'
informational_start = u'1'
if not n.startswith(sigil):
return False
if n != status:
continue
return v.startswith(informational_start)
|
enaml-0.11.1 | enaml-0.11.1//enaml/core/compiler_helpers.pyfile:/enaml/core/compiler_helpers.py:function:validate_spec/validate_spec | def validate_spec(index, spec):
""" Validate the value for a parameter specialization.
This validator ensures that the value is hashable and not None.
Parameters
----------
index : int
The integer index of the parameter being specialized.
spec : object
The parameter specialization.
Returns
-------
result : object
The validated specialization object.
"""
if spec is None:
msg = 'cannot specialize template parameter %d with None'
raise TypeError(msg % index)
try:
hash(spec)
except TypeError:
msg = "template parameter %d has unhashable type: '%s'"
raise TypeError(msg % (index, type(spec).__name__))
return spec
|
landlab | landlab//components/overland_flow/_links.pyfile:/components/overland_flow/_links.py:function:number_of_vertical_links/number_of_vertical_links | def number_of_vertical_links(shape):
"""Number of vertical links in a structured quad grid.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
int :
Number of vertical links in grid.
Examples
--------
>>> from landlab.components.overland_flow._links import number_of_vertical_links
>>> number_of_vertical_links((3, 4))
8
"""
return (shape[0] - 1) * shape[1]
|
fake-bpy-module-2.78-20200428 | fake-bpy-module-2.78-20200428//bpy/ops/particle.pyfile:/bpy/ops/particle.py:function:hide/hide | def hide(unselected: bool=False):
"""Hide selected particles
:param unselected: Unselected, Hide unselected rather than selected
:type unselected: bool
"""
pass
|
Theano-1.0.4 | Theano-1.0.4//theano/tensor/elemwise_cgen.pyfile:/theano/tensor/elemwise_cgen.py:function:make_declare/make_declare | def make_declare(loop_orders, dtypes, sub):
"""
Produce code to declare all necessary variables.
"""
decl = ''
for i, (loop_order, dtype) in enumerate(zip(loop_orders, dtypes)):
var = sub['lv%i' % i]
decl += """
%(dtype)s* %(var)s_iter;
""" % locals()
for j, value in enumerate(loop_order):
if value != 'x':
decl += (
"""
npy_intp %(var)s_n%(value)i;
ssize_t %(var)s_stride%(value)i;
int %(var)s_jump%(value)i_%(j)i;
"""
% locals())
else:
decl += (
"""
int %(var)s_jump%(value)s_%(j)i;
"""
% locals())
return decl
|
yggdrasil-framework-1.1.1 | yggdrasil-framework-1.1.1//yggdrasil/command_line.pyfile:/yggdrasil/command_line.py:function:yggtime_comm/yggtime_comm | def yggtime_comm():
"""Plot timing statistics comparing the different communication mechanisms."""
from yggdrasil import timing
timing.plot_scalings(compare='commtype')
|
ckipnlp | ckipnlp//container/base.pyclass:BaseTuple/from_list | @classmethod
def from_list(cls, data):
"""Construct an instance from python built-in containers.
Parameters
----------
data : list
"""
return cls(*data)
|
wx | wx//lib/ogl/oglmisc.pyfile:/lib/ogl/oglmisc.py:function:GraphicsStraightenLine/GraphicsStraightenLine | def GraphicsStraightenLine(point1, point2):
"""
Straighten a line in graphics
:param `point1`: a point list???
:param `point2`: a point list???
"""
dx = point2[0] - point1[0]
dy = point2[1] - point1[1]
if dx == 0:
return
elif abs(float(dy) / dx) > 1:
point2[0] = point1[0]
else:
point2[1] = point1[1]
|
modestpy-0.0.9 | modestpy-0.0.9//modestpy/utilities/figures.pyfile:/modestpy/utilities/figures.py:function:get_figure/get_figure | def get_figure(ax):
"""
Retrieves figure from axes. Axes can be either an instance
of Matplotlib.Axes or a 1D/2D array of Matplotlib.Axes.
:param ax: Axes or vector/array of Axes
:return: Matplotlib.Figure
"""
fig = None
try:
fig = ax.get_figure()
except AttributeError:
try:
fig = ax[0].get_figure()
except AttributeError:
fig = ax[0][0].get_figure()
return fig
|
fonduer-0.8.2 | fonduer-0.8.2//src/fonduer/utils/data_model_utils/visual.pyfile:/src/fonduer/utils/data_model_utils/visual.py:function:get_vert_ngrams_left/get_vert_ngrams_left | def get_vert_ngrams_left(c):
"""Not implemented."""
return
|
fake-bpy-module-2.79-20200428 | fake-bpy-module-2.79-20200428//bpy/ops/mesh.pyfile:/bpy/ops/mesh.py:function:rip_move/rip_move | def rip_move(MESH_OT_rip=None, TRANSFORM_OT_translate=None):
"""Rip polygons and move the result
:param MESH_OT_rip: Rip, Disconnect vertex or edges from connected geometry
:param TRANSFORM_OT_translate: Translate, Translate (move) selected items
"""
pass
|
collective.teamwork-0.9 | collective.teamwork-0.9//collective/teamwork/user/interfaces.pyclass:IWorkspaceGroup/__contains__ | def __contains__(username):
"""
Given user login name, is it contained in group?
"""
|
fake-blender-api-2.79-0.3.1 | fake-blender-api-2.79-0.3.1//bpy/ops/sequencer.pyfile:/bpy/ops/sequencer.py:function:cut_multicam/cut_multicam | def cut_multicam(camera: int=1):
"""Cut multi-cam strip and select camera
:param camera: Camera
:type camera: int
"""
pass
|
bvhtoolbox | bvhtoolbox//convert/csv2bvh.pyfile:/convert/csv2bvh.py:function:_get_joint_depth/_get_joint_depth | def _get_joint_depth(nodes, joint):
""" How deep in the tree are we?
:param nodes: Dictionary with skeleton hierarchy.
:type nodes: dict
:param joint: Name of the joint in question.
:type joint: str
:return: The depth of the joint in the hierarchy.
:rtype: int
"""
depth = 0
parent = nodes[joint]['parent']
while parent:
depth += 1
parent = nodes[parent]['parent']
return depth
|
fake-bpy-module-2.80-20200428 | fake-bpy-module-2.80-20200428//bpy/ops/gpencil.pyfile:/bpy/ops/gpencil.py:function:copy/copy | def copy():
"""Copy selected Grease Pencil points and strokes
"""
pass
|
aiida-core-1.2.1 | aiida-core-1.2.1//aiida/manage/configuration/migrations/migrations.pyfile:/aiida/manage/configuration/migrations/migrations.py:function:_2_simplify_default_profiles/_2_simplify_default_profiles | def _2_simplify_default_profiles(config):
"""
The concept of a different 'process' for a profile has been removed and as such the
default profiles key in the configuration no longer needs a value per process ('verdi', 'daemon').
We remove the dictionary 'default_profiles' and replace it with a simple value 'default_profile'.
"""
from aiida.manage.configuration import PROFILE
default_profiles = config.pop('default_profiles', None)
if default_profiles and 'daemon' in default_profiles:
config['default_profile'] = default_profiles['daemon']
elif default_profiles and 'verdi' in default_profiles:
config['default_profile'] = default_profiles['verdi']
elif PROFILE is not None:
config['default_profile'] = PROFILE.name
return config
|
parler | parler//forms.pyfile:/forms.py:function:_get_model_form_field/_get_model_form_field | def _get_model_form_field(model, name, formfield_callback=None, **kwargs):
"""
Utility to create the formfield from a model field.
When a field is not editable, a ``None`` will be returned.
"""
field = model._meta.get_field(name)
if not field.editable:
return None
if formfield_callback is None:
formfield = field.formfield(**kwargs)
elif not callable(formfield_callback):
raise TypeError('formfield_callback must be a function or callable')
else:
formfield = formfield_callback(field, **kwargs)
return formfield
|
dropbox | dropbox//team_log.pyclass:EventType/showcase_archived | @classmethod
def showcase_archived(cls, val):
"""
Create an instance of this class set to the ``showcase_archived`` tag
with value ``val``.
:param ShowcaseArchivedType val:
:rtype: EventType
"""
return cls('showcase_archived', val)
|
colin | colin//core/target.pyfile:/core/target.py:function:is_compatible/is_compatible | def is_compatible(target_type, check_instance):
"""
Check the target compatibility with the check instance.
:param target_type: Target subclass, if None, returns True
:param check_instance: instance of some Check class
:return: True if the target is None or compatible with the check instance
"""
if not target_type:
return True
return isinstance(check_instance, target_type.get_compatible_check_class())
|
atom-0.5.0 | atom-0.5.0//atom/atom.pyfile:/atom/atom.py:function:__newobj__/__newobj__ | def __newobj__(cls, *args):
""" A compatibility pickler function.
This function is not part of the public Atom api.
"""
return cls.__new__(cls, *args)
|
OFS | OFS//interfaces.pyclass:IManageable/manage_afterAdd | def manage_afterAdd(item, container):
"""Gets called after being added to a container"""
|
genepattern-python-20.5 | genepattern-python-20.5//gp/modules.pyclass:GPTaskSpec/manifest_escape | @staticmethod
def manifest_escape(string):
"""
Escape colon and equals characters for inclusion in manifest file
:param string:
:return: string
"""
return string.replace(':', '\\:').replace('=', '\\=')
|
allmydata | allmydata//interfaces.pyclass:ICheckResults/get_encoding_expected | def get_encoding_expected():
"""Return 'N', the number of total shares generated."""
|
django-meetup-1.0.7 | django-meetup-1.0.7//meetup/sync_utils.pyfile:/meetup/sync_utils.py:function:fro_meetup_geo/fro_meetup_geo | def fro_meetup_geo(geo):
""" From Meetup Data to geo location"""
if geo is None or not geo:
return
return float(geo)
|
fsleyes-props-1.6.7 | fsleyes-props-1.6.7//fsleyes_props/widgets.pyfile:/fsleyes_props/widgets.py:function:_Int/_Int | def _Int(parent, hasProps, propObj, propVal, **kwargs):
"""Creates and returns a widget allowing the user to edit the given
:class:`.Int` property value. See the :func:`.widgets_number._Number`
function for more details.
See the :func:`_String` documentation for details on the parameters.
"""
from fsleyes_props.widgets_number import _Number
return _Number(parent, hasProps, propObj, propVal, **kwargs)
|
reclaimer-2.9.0 | reclaimer-2.9.0//reclaimer/hek/defs/objs/sbsp.pyclass:SbspTag/point_in_front_of_plane | @staticmethod
def point_in_front_of_plane(plane, x, y, z):
"""
Takes a plane ex:
```py
collision_bsp = self.data.tagdata.collision_bsp.STEPTREE[0]
collision_bsp.planes.STEPTREE[i]
```
And dots the plane and coordinates and compares against d to
see if the xyz are in front of it.
"""
return x * plane.i + y * plane.j + z * plane.k >= plane.d
|
silva.core.interfaces-3.0.4 | silva.core.interfaces-3.0.4//src/silva/core/interfaces/content.pyclass:IImage/get_crop_box | def get_crop_box(crop=None):
"""Return a tuple describing the current crop box used to
create the web image. The describe the coordinate of the top
left and the bottom right corner.
"""
|
blessed-1.17.5 | blessed-1.17.5//blessed/color.pyfile:/blessed/color.py:function:xyz_to_lab/xyz_to_lab | def xyz_to_lab(x_val, y_val, z_val):
"""
Convert XYZ color to CIE-Lab color.
:arg float x_val: XYZ value of X.
:arg float y_val: XYZ value of Y.
:arg float z_val: XYZ value of Z.
:returns: Tuple (L, a, b) representing CIE-Lab color
:rtype: tuple
D65/2° standard illuminant
"""
xyz = []
for val, ref in ((x_val, 95.047), (y_val, 100.0), (z_val, 108.883)):
val /= ref
if val > 0.008856:
val = pow(val, 1 / 3.0)
else:
val = 7.787 * val + 16 / 116.0
xyz.append(val)
x_val, y_val, z_val = xyz
cie_l = 116 * y_val - 16
cie_a = 500 * (x_val - y_val)
cie_b = 200 * (y_val - z_val)
return cie_l, cie_a, cie_b
|
zope.browser-2.3 | zope.browser-2.3//src/zope/browser/interfaces.pyclass:IAdding/hasCustomAddView | def hasCustomAddView():
"""This should be called only if there is ``singleMenuItem`` else return 0"""
|
CodeEditor | CodeEditor//auxilary.pyfile:/auxilary.py:function:BGR2RGB/BGR2RGB | def BGR2RGB(bgrInt):
"""Convert an integer in BGR format to an ``(r, g, b)`` tuple.
``bgr_int`` is an integer representation of an RGB color, where the R, G,
and B values are in the range (0, 255), and the three channels are comined
into ``bgr_int`` by a bitwise ``red | (green << 8) | (blue << 16)``. This
leaves the red channel in the least-significant bits, making a direct
translation to a QColor difficult (the QColor constructor accepts an
integer form, but it assumes the *blue* channel is in the least-significant
bits).
Examples:
>>> BGR2RGB(4227327)
(255, 128, 64)
"""
red, green, blue = bgrInt & 255, bgrInt >> 8 & 255, bgrInt >> 16 & 255
return red, green, blue
|
Tailbone-0.8.92 | Tailbone-0.8.92//tailbone/views/shifts/lib.pyclass:TimeSheetView/_defaults | @classmethod
def _defaults(cls, config):
"""
Provide default configuration for a time sheet view.
"""
title = cls.get_title()
url_prefix = cls.get_url_prefix()
config.add_tailbone_permission_group(cls.key, title)
config.add_tailbone_permission(cls.key, '{}.viewall'.format(cls.key),
'View full {}'.format(title))
config.add_route(cls.key, '{}/'.format(url_prefix))
config.add_view(cls, attr='full', route_name=cls.key, renderer=
'/shifts/{}.mako'.format(cls.key), permission='{}.viewall'.format(
cls.key))
if cls.expose_employee_views:
config.add_tailbone_permission(cls.key, '{}.view'.format(cls.key),
'View single employee {}'.format(title))
config.add_route('{}.employee'.format(cls.key), '{}/employee/'.
format(url_prefix))
config.add_view(cls, attr='employee', route_name='{}.employee'.
format(cls.key), renderer='/shifts/{}.mako'.format(cls.key),
permission='{}.view'.format(cls.key))
other_key = 'timesheet' if cls.key == 'schedule' else 'schedule'
config.add_route('{}.goto.{}'.format(cls.key, other_key), '{}/goto-{}'.
format(url_prefix, other_key))
config.add_view(cls, attr='crossview', route_name='{}.goto.{}'.format(
cls.key, other_key), permission='{}.view'.format(other_key))
|
cot-2.2.1 | cot-2.2.1//versioneer.pyfile:/versioneer.py:function:render_git_describe/render_git_describe | def render_git_describe(pieces):
"""TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
if pieces['distance']:
rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
else:
rendered = pieces['short']
if pieces['dirty']:
rendered += '-dirty'
return rendered
|
donphan-2.3.0 | donphan-2.3.0//donphan/sqltype.pyclass:SQLType/BigInt | @classmethod
def BigInt(cls):
"""Postgres BigInt Type"""
return cls(int, 'BIGINT')
|
pyramid-1.10.4 | pyramid-1.10.4//src/pyramid/interfaces.pyclass:ICSRFStoragePolicy/check_csrf_token | def check_csrf_token(request, token):
""" Determine if the supplied ``token`` is valid. Most implementations
should simply compare the ``token`` to the current value of
``get_csrf_token`` but it is possible to verify the token using
any mechanism necessary using this method.
Returns ``True`` if the ``token`` is valid, otherwise ``False``.
"""
|
Pytzer-0.4.3 | Pytzer-0.4.3//pytzer/parameters.pyfile:/pytzer/parameters.py:function:psi_Ca_Na_CO3_HMW84/psi_Ca_Na_CO3_HMW84 | def psi_Ca_Na_CO3_HMW84(T, P):
"""c-c'-a: calcium sodium carbonate [HMW84]."""
psi = 0.0
valid = T == 298.15
return psi, valid
|
scratchai | scratchai//utils.pyfile:/utils.py:function:setatrib/setatrib | def setatrib(obj, attr: str, val):
"""
Overiding the default getattr
Arguments
---------
obj : object
The object from which to get the attribute.
attr : str
The attribute in string format.
"""
attrs = attr.split('[')
for ii in range(len(attrs)):
if attrs[ii][-1] == ']':
attr = attrs[ii][:-1]
else:
attr = attrs[ii]
if ii == len(attrs) - 1:
setattr(obj, attr, val)
else:
obj = getattr(obj, attr)
|
kaidoku-0.5.6 | kaidoku-0.5.6//kaidoku/misc.pyfile:/kaidoku/misc.py:function:box/box | def box():
"""Define the effective cells."""
box = []
for i in range(9):
for j in range(9):
b = [0] * 81
for i2 in range(9):
b[i2 * 9 + j] = 1
for j2 in range(9):
b[i * 9 + j2] = 1
begin = i // 3 * 27 + j // 3 * 3
for i2 in [0, 1, 2]:
for j2 in [0, 1, 2]:
b[begin + i2 * 9 + j2] = 1
b[i * 9 + j] = 0
bb = []
for i2 in range(81):
if b[i2] == 1:
bb = bb + [i2]
box = box + [bb]
return box
|
gwdetchar-1.0.2 | gwdetchar-1.0.2//gwdetchar/omega/core.pyfile:/gwdetchar/omega/core.py:function:whiten/whiten | def whiten(series, fftlength, overlap=None, method='median', window='hann',
detrend='linear'):
"""Whiten a `TimeSeries` against its own ASD
Parameters
----------
series : `~gwpy.timeseries.TimeSeries`
the `TimeSeries` data to whiten
fftlength : `float`
FFT integration length (in seconds) for ASD estimation
overlap : `float`, optional
seconds of overlap between FFTs, defaults to half the FFT length
method : `str`, optional
FFT-averaging method, default: ``'median'``,
window : `str`, `numpy.ndarray`, optional
window function to apply to timeseries prior to FFT,
default: ``'hann'``
see :func:`scipy.signal.get_window` for details on acceptable
formats
detrend : `str`, optional
type of detrending to do before FFT, default: ``'linear'``
Returns
-------
wseries : `~gwpy.timeseries.TimeSeries`
a whitened version of the input data with zero mean and unit variance
See Also
--------
gwpy.timeseries.TimeSeries.whiten
"""
if overlap is None:
overlap = fftlength / 2
return series.whiten(fftlength=fftlength, overlap=overlap, window=
window, detrend=detrend, method=method).detrend(detrend)
|
satnogs-db-0.35 | satnogs-db-0.35//versioneer.pyfile:/versioneer.py:function:render_pep440_old/render_pep440_old | def render_pep440_old(pieces):
"""TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0]
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
if pieces['distance'] or pieces['dirty']:
rendered += '.post%d' % pieces['distance']
if pieces['dirty']:
rendered += '.dev0'
else:
rendered = '0.post%d' % pieces['distance']
if pieces['dirty']:
rendered += '.dev0'
return rendered
|
asv-0.4.1 | asv-0.4.1//asv/util.pyfile:/asv/util.py:function:iter_chunks/iter_chunks | def iter_chunks(s, n):
"""
Iterator that returns elements from s in chunks of size n.
"""
chunk = []
for x in s:
chunk.append(x)
if len(chunk) == n:
yield chunk
chunk = []
if len(chunk):
yield chunk
|
facedancer | facedancer//core.pyclass:FacedancerApp/appropriate_for_environment | @classmethod
def appropriate_for_environment(cls, backend_name=None):
"""
Returns true if the current class is likely to be the appropriate
class to connect to a facedancer given the board_name and other
environmental factors.
board: The name of the backend, as typically retreived from the BACKEND
environment variable, or None to try figuring things out based
on other environmental factors.
"""
return False
|
taskforce-0.5.0 | taskforce-0.5.0//taskforce/utils.pyfile:/taskforce/utils.py:function:ses/ses | def ses(count, plural='s', singular=''):
"""
ses is pronounced "esses".
Return a string suffix that indicates a singular sense if
the count is 1, and a plural sense otherwise.
So, for example:
log.info("%d item%s found", items, utils.ses(items))
would log:
"1 item found" if items was 1
and:
"0 items found" if items was 0
And:
log.info("%d famil%s found", 1, ses(1, singular='y', plural='ies'))
or:
log.info("%d famil%s found", 1, ses(1, 'ies', 'y'))
would log:
"1 family found" if items was 1
and:
"10 families found" if items was 10
Note that the default covers pluralization for most English words and the positional
override is ordered to handle most easily handfle other cases.
This function officially has the highest comment:code ratio in our codebase.
"""
return singular if count == 1 else plural
|
argos | argos//utils/cls.pyfile:/utils/cls.py:function:is_a_mapping/is_a_mapping | def is_a_mapping(var, allow_none=False):
""" Returns True if var is a dictionary # TODO: ordered dict
"""
return isinstance(var, dict) or var is None and allow_none
|
guillotina-5.3.38 | guillotina-5.3.38//guillotina/schema/interfaces.pyclass:IVocabularyTokenized/getTermByToken | def getTermByToken(token):
"""Return an ITokenizedTerm for the passed-in token.
If `token` is not represented in the vocabulary, `LookupError`
is raised.
"""
|
astro-gala-1.1 | astro-gala-1.1//gala/dynamics/analyticactionangle.pyfile:/gala/dynamics/analyticactionangle.py:function:harmonic_oscillator_to_xv/harmonic_oscillator_to_xv | def harmonic_oscillator_to_xv(actions, angles, potential):
"""
Transform the input action-angle coordinates to cartesian
position and velocity for the Harmonic Oscillator potential.
.. note::
This function is included as a method of the
:class:`~gala.potential.HarmonicOscillatorPotential`
and it is recommended to call
:meth:`~gala.potential.HarmonicOscillatorPotential.phase_space()` instead.
Parameters
----------
actions : array_like
angles : array_like
potential : Potential
"""
raise NotImplementedError(
'Implementation not supported until working with angle-action variables has a better API.'
)
|
freezer | freezer//engine/rsyncv2/rsyncv2.pyclass:Rsyncv2Engine/_process_restore_data | @staticmethod
def _process_restore_data(data, decompressor, decryptor):
"""Decrypts and decompresses provided data according to args"""
if decryptor:
data = decryptor.decrypt(data)
data = decompressor.decompress(data)
return data
|
tentaclio | tentaclio//fs/api.pyfile:/fs/api.py:function:_relativize/_relativize | def _relativize(base: str, current: str) ->str:
"""Remove the base url from the current url."""
if current.startswith(base):
return current.replace(base, '', 1)
return current
|
bloxroute-gateway-1.62.13 | bloxroute-gateway-1.62.13//bxgateway/src/bxgateway/utils/eth/rlp_utils.pyfile:/bxgateway/src/bxgateway/utils/eth/rlp_utils.py:function:safe_ord/safe_ord | def safe_ord(c):
"""
Returns an integer representing the Unicode code point of the character or int if int argument is passed
:param c: character or integer
:return: integer representing the Unicode code point of the character or int if int argument is passed
"""
if isinstance(c, int):
return c
else:
return ord(c)
|
bpy | bpy//ops/ui.pyfile:/ops/ui.py:function:eyedropper_color/eyedropper_color | def eyedropper_color(use_accumulate: bool=True):
"""Sample a color from the Blender window to store in a property
:param use_accumulate: Accumulate
:type use_accumulate: bool
"""
pass
|
singer | singer//utils.pyfile:/utils.py:function:should_sync_field/should_sync_field | def should_sync_field(inclusion, selected, default=False):
"""
Returns True if a field should be synced.
inclusion: automatic|available|unsupported
selected: True|False|None
default: (default: False) True|False
"automatic" inclusion always returns True:
>>> should_sync_field("automatic", None, False)
True
>>> should_sync_field("automatic", True, False)
True
>>> should_sync_field("automatic", False, False)
True
>>> should_sync_field("automatic", None, True)
True
>>> should_sync_field("automatic", True, True)
True
>>> should_sync_field("automatic", False, True)
True
"unsupported" inclusion always returns False
>>> should_sync_field("unsupported", None, False)
False
>>> should_sync_field("unsupported", True, False)
False
>>> should_sync_field("unsupported", False, False)
False
>>> should_sync_field("unsupported", None, True)
False
>>> should_sync_field("unsupported", True, True)
False
>>> should_sync_field("unsupported", False, True)
False
"available" inclusion uses the selected value when set
>>> should_sync_field("available", True, False)
True
>>> should_sync_field("available", False, False)
False
>>> should_sync_field("available", True, True)
True
>>> should_sync_field("available", False, True)
False
"available" inclusion uses the default value when selected is None
>>> should_sync_field("available", None, False)
False
>>> should_sync_field("available", None, True)
True
"""
if inclusion == 'automatic':
return True
if inclusion == 'unsupported':
return False
if selected is not None:
return selected
return default
|
snappysonic-0.0.4 | snappysonic-0.0.4//snappysonic/algorithms/algorithms.pyfile:/snappysonic/algorithms/algorithms.py:function:check_us_buffer/check_us_buffer | def check_us_buffer(usbuffer):
"""
Checks that all ultrasound buffer contains all required key values.
:param usbuffer: the buffer to check
:raises: KeyError
:raises: ValueError
"""
if 'name' not in usbuffer:
raise KeyError('Buffer configuration must contain a name.')
if 'start frame' not in usbuffer:
raise KeyError('Buffer configuration must contain a start frame.')
if 'end frame' not in usbuffer:
raise KeyError('Buffer configuration must contain an end frame.')
if 'x0' not in usbuffer:
raise KeyError('Buffer configuration must contain x0')
if 'x1' not in usbuffer:
raise KeyError('Buffer configuration must contain x1')
if 'y0' not in usbuffer:
raise KeyError('Buffer configuration must contain y0')
if 'y1' not in usbuffer:
raise KeyError('Buffer configuration must contain y1')
if 'scan direction' not in usbuffer:
raise KeyError('Buffer configuration must contain a scan direction.')
direction = usbuffer.get('scan direction')
if direction not in ('x', 'y'):
raise ValueError('scan direction must be either x or y')
|
FFC-2017.1.0 | FFC-2017.1.0//ffc/tensor/monomialtransformation.pyfile:/ffc/tensor/monomialtransformation.py:function:_next_internal_index/_next_internal_index | def _next_internal_index():
"""Return next available internal index."""
global _current_internal_index
_current_internal_index += 1
return _current_internal_index - 1
|
paytm-pg-1.0.6 | paytm-pg-1.0.6//paytmpg/pg/utils/stringUtil.pyfile:/paytmpg/pg/utils/stringUtil.py:function:make_string/make_string | def make_string(arg):
"""Used to overload Dunder method __str__ of any class
This is used to convert <class 'class_name'> to string form and this is also a valid json
:param arg: arg ~ self, iterate over it and form key-value {attribute: value}
:return: string value of self(arg) of any class
"""
res = str()
is_first = True
for k, v in arg.__dict__.items():
if v is not None and v is not '':
if not is_first:
res += ','
if v.__str__()[0] == '{' or v.__str__()[0] == '[':
res += '"{}":{}'.format(k, v)
else:
res += '"{}":"{}"'.format(k, v)
is_first = False
if is_first:
return None
return '{' + res + '}'
|
drf_spectacular | drf_spectacular//plumbing.pyfile:/plumbing.py:function:alpha_operation_sorter/alpha_operation_sorter | def alpha_operation_sorter(endpoint):
""" sort endpoints first alphanumerically by path, then by method order """
path, path_regex, method, callback = endpoint
method_priority = {'GET': 0, 'POST': 1, 'PUT': 2, 'PATCH': 3, 'DELETE': 4
}.get(method, 5)
return path, method_priority
|
pypykatz-0.3.9 | pypykatz-0.3.9//pypykatz/crypto/unified/pkcs7.pyfile:/pypykatz/crypto/unified/pkcs7.py:function:pad/pad | def pad(bytestring, k=16):
"""
Pad an input bytestring according to PKCS#7
"""
l = len(bytestring)
val = k - l % k
return bytestring + bytearray([val] * val)
|
promus-0.1.2 | promus-0.1.2//promus/hooks/post_commit.pyfile:/promus/hooks/post_commit.py:function:run/run | def run(_):
"""Function to execute when the post-commit hook is called. """
pass
|
trimesh-3.6.35 | trimesh-3.6.35//trimesh/util.pyfile:/trimesh/util.py:function:decode_keys/decode_keys | def decode_keys(store, encoding='utf-8'):
"""
If a dictionary has keys that are bytes decode them to a str.
Parameters
------------
store : dict
Dictionary with data
Returns
---------
result : dict
Values are untouched but keys that were bytes
are converted to ASCII strings.
Example
-----------
In [1]: d
Out[1]: {1020: 'nah', b'hi': 'stuff'}
In [2]: trimesh.util.decode_keys(d)
Out[2]: {1020: 'nah', 'hi': 'stuff'}
"""
keys = store.keys()
for key in keys:
if hasattr(key, 'decode'):
decoded = key.decode(encoding)
if key != decoded:
store[key.decode(encoding)] = store[key]
store.pop(key)
return store
|