repo
stringlengths 1
29
| path
stringlengths 24
332
| code
stringlengths 39
579k
|
---|---|---|
completions
|
completions//templates.pyfile:/templates.py:function:_escape_colon/_escape_colon
|
def _escape_colon(name):
"""Escape colon in command/option name for zsh"""
return name.replace(':', '\\:')
|
mycroft
|
mycroft//tts/mimic2_tts.pyfile:/tts/mimic2_tts.py:function:break_chunks/break_chunks
|
def break_chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield ' '.join(l[i:i + n])
|
pskc
|
pskc//signature.pyfile:/signature.py:function:sign_x509/sign_x509
|
def sign_x509(xml, key, certificate, algorithm=None, digest_algorithm=None,
canonicalization_method=None):
"""Sign PSKC data using X.509 certificate and private key.
xml: an XML document
key: the private key in binary format
certificate: the X.509 certificate
"""
import signxml
algorithm = algorithm or 'rsa-sha256'
digest_algorithm = digest_algorithm or 'sha256'
canonicalization_method = (canonicalization_method or signxml.
XMLSignatureProcessor.default_c14n_algorithm)
return signxml.XMLSigner(method=signxml.methods.enveloped,
signature_algorithm=algorithm.rsplit('#', 1)[-1].lower(),
digest_algorithm=digest_algorithm.rsplit('#', 1)[-1].lower(),
c14n_algorithm=canonicalization_method).sign(xml, key=key, cert=
certificate)
|
OFS
|
OFS//interfaces.pyclass:IPropertyManager/getProperty
|
def getProperty(id, d=None):
"""Get the property 'id'.
Returns the optional second argument or None if no such property is
found.
"""
|
fake-blender-api-2.79-0.3.1
|
fake-blender-api-2.79-0.3.1//bpy/ops/uv.pyfile:/bpy/ops/uv.py:function:mark_seam/mark_seam
|
def mark_seam(clear: bool=False):
"""Mark selected UV edges as seams
:param clear: Clear Seams, Clear instead of marking seams
:type clear: bool
"""
pass
|
plone.folder-3.0.2
|
plone.folder-3.0.2//src/plone/folder/interfaces.pyclass:IOrdering/notifyRemoved
|
def notifyRemoved(obj_id):
""" Inform the ordering implementation that an item was removed """
|
cl-timer-1.1.4
|
cl-timer-1.1.4//cl_timer/timer.pyfile:/cl_timer/timer.py:function:convert_to_float/convert_to_float
|
def convert_to_float(lst, purpose):
"""
Returns list of all float-convertable values of `lst`,
along with length of new list
"""
float_times = []
len_times = 0
for t in lst:
if str(t)[:3] != 'DNF' and t != '' and str(t)[-1] != '+':
float_times.append(float(t))
len_times += 1
elif str(t)[-1] == '+':
if purpose == 'average':
float_times.append(float(t[:-1]))
len_times += 1
elif purpose == 'single':
float_times.append(t)
len_times += 1
return float_times, len_times
|
horae.reports-1.0a1
|
horae.reports-1.0a1//horae/reports/interfaces.pyclass:IReport/properties
|
def properties():
""" Returns a dict of name, value pairs to be used for searching
"""
|
databrowse
|
databrowse//plugins/db_plain_text_file/handlers.pyfile:/plugins/db_plain_text_file/handlers.py:function:dbh__text/dbh__text
|
def dbh__text(path, contenttype, extension, roottag, nsurl):
""" Generic Text Handler - Returns text_generic for all text files """
if contenttype.startswith('text') or contenttype.startswith(
'application/xml') or contenttype.startswith('text/xml'):
return 'db_plain_text_file'
else:
return False
|
fake-bpy-module-2.79-20200428
|
fake-bpy-module-2.79-20200428//bpy/ops/mask.pyfile:/bpy/ops/mask.py:function:add_feather_vertex_slide/add_feather_vertex_slide
|
def add_feather_vertex_slide(MASK_OT_add_feather_vertex=None,
MASK_OT_slide_point=None):
"""Add new vertex to feather and slide it
:param MASK_OT_add_feather_vertex: Add Feather Vertex, Add vertex to feather
:param MASK_OT_slide_point: Slide Point, Slide control points
"""
pass
|
relstorage
|
relstorage//blobhelper/interfaces.pyclass:IBlobHelper/storeBlob
|
def storeBlob(cursor, store_func, oid, serial, data, blobfilename, version, txn
):
"""Storage API: store a blob object."""
|
fecon236
|
fecon236//host/qdl.pyfile:/host/qdl.py:function:plotqdl/plotqdl
|
def plotqdl(data, title='tmp', maxi=87654321):
"""DEPRECATED: Plot data should be it given as dataframe or quandlcode."""
msg = 'plotqdl() DEPRECATED. Instead use get() and plot().'
raise DeprecationWarning(msg)
|
pytzer
|
pytzer//parameters.pyfile:/parameters.py:function:psi_K_Cl_H2PO4_MP98/psi_K_Cl_H2PO4_MP98
|
def psi_K_Cl_H2PO4_MP98(T, P):
"""c-a-a': potassium chloride dihydrogen-phosphate [MP98]."""
psi = -0.0105
valid = T == 298.15
return psi, valid
|
eulerian-magnification-0.22
|
eulerian-magnification-0.22//eulerian_magnification/base.pyfile:/eulerian_magnification/base.py:function:get_frame_dimensions/get_frame_dimensions
|
def get_frame_dimensions(frame):
"""Get the dimensions of a single frame"""
height, width = frame.shape[:2]
return width, height
|
bespin-0.8.1
|
bespin-0.8.1//bespin/processes.pyfile:/bespin/processes.py:function:read_non_blocking/read_non_blocking
|
def read_non_blocking(stream):
"""Read from a non-blocking stream"""
if stream:
while True:
nxt = ''
try:
nxt = stream.readline()
except IOError:
pass
if nxt:
yield nxt
else:
break
|
python_adb_utils-0.0.11
|
python_adb_utils-0.0.11//adb_utils/adb_utils.pyfile:/adb_utils/adb_utils.py:function:list_files_in_device/list_files_in_device
|
def list_files_in_device() ->None:
"""
Gets a list of files in a specific folder
:param device:
:param path:
:return: list of files
"""
pass
|
pocsuite3
|
pocsuite3//lib/core/revision.pyfile:/lib/core/revision.py:function:stdout_encode/stdout_encode
|
def stdout_encode(data):
"""
Cross-linked function
"""
if isinstance(data, bytes):
data = data.decode('utf-8')
else:
data = str(data)
return data
|
delphixpy
|
delphixpy//v1_4_0/common.pyfile:/v1_4_0/common.py:function:validate_format/validate_format
|
def validate_format(*_arg):
"""
This method can be overridden with format validation logic.
"""
return True
|
mailman
|
mailman//interfaces/listmanager.pyclass:IListManager/delete
|
def delete(mlist):
"""Remove the mailing list from the database.
:param mlist: The mailing list to delete.
:type mlist: `IMailingList`
"""
|
passlib
|
passlib//utils/compat/_ordered_dict.pyclass:OrderedDict/update
|
def update(*args, **kwds):
"""od.update(E, **F) -> None. Update od from dict/iterable E and F.
If E is a dict instance, does: for k in E: od[k] = E[k]
If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
Or if E is an iterable of items, does: for k, v in E: od[k] = v
In either case, this is followed by: for k, v in F.items(): od[k] = v
"""
if len(args) > 2:
raise TypeError(
'update() takes at most 2 positional arguments (%d given)' % (
len(args),))
elif not args:
raise TypeError('update() takes at least 1 argument (0 given)')
self = args[0]
other = ()
if len(args) == 2:
other = args[1]
if isinstance(other, dict):
for key in other:
self[key] = other[key]
elif hasattr(other, 'keys'):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
|
normalize
|
normalize//visitor.pyclass:VisitorPattern/collect
|
@classmethod
def collect(cls, mapped_coll_generator, coll_type, visitor):
"""Like :py:meth:`normalize.visitor.VisitorPattern.aggregate`, but
coerces the mapped values to the collection item type on the way
through.
"""
return coll_type.tuples_to_coll(mapped_coll_generator)
|
sch-askbot-1.0.1
|
sch-askbot-1.0.1//askbot/signals.pyfile:/askbot/signals.py:function:pop_signal_receivers/pop_signal_receivers
|
def pop_signal_receivers(signal):
"""disables a given signal by removing listener functions
and returns the list
"""
receivers = signal.receivers
signal.receivers = list()
return receivers
|
Swoop
|
Swoop//Swoop.pyclass:Schematic/_from_et
|
@classmethod
def _from_et(cls, root, parent):
"""
Create a :class:`Schematic` from a :code:`schematic` element.
:param root: The element tree tree to parse.
:param parent: :class:`EagleFilePart` that should hold the resulting :class:`EagleFilePart`
:rtype: :class:`Schematic`
"""
n = cls()
n._init_from_et(root, parent)
return n
|
fake-bpy-module-2.78-20200428
|
fake-bpy-module-2.78-20200428//freestyle/utils/ContextFunctions.pyfile:/freestyle/utils/ContextFunctions.py:function:read_map_pixel/read_map_pixel
|
def read_map_pixel(map_name: str, level: int, x: int, y: int) ->float:
"""Reads a pixel in a user-defined map.
:param map_name: The name of the map.
:type map_name: str
:param level: The level of the pyramid in which we wish to read the pixel.
:type level: int
:param x: The x coordinate of the pixel we wish to read. The origin is in the lower-left corner.
:type x: int
:param y: The y coordinate of the pixel we wish to read. The origin is in the lower-left corner.
:type y: int
:return: The floating-point value stored for that pixel.
"""
pass
|
panda3d-blend2bam-0.11
|
panda3d-blend2bam-0.11//blend2bam/blend2egg/yabee/yabee_libs/utils.pyfile:/blend2bam/blend2egg/yabee/yabee_libs/utils.py:function:eggSafeName/eggSafeName
|
def eggSafeName(s):
""" (Get from Chicken) Function that converts names into something
suitable for the egg file format - simply puts " around names that
contain spaces and prunes bad characters, replacing them with an
underscore.
"""
s = str(s).replace('"', '_')
if ' ' in s:
return '"' + s + '"'
else:
return s
|
fsspec-0.7.3
|
fsspec-0.7.3//versioneer.pyfile:/versioneer.py:function:plus_or_dot/plus_or_dot
|
def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if '+' in pieces.get('closest-tag', ''):
return '.'
return '+'
|
pyphi
|
pyphi//labels.pyfile:/labels.py:function:default_label/default_label
|
def default_label(index):
"""Default label for a node."""
return 'n{}'.format(index)
|
h5io-0.1.2
|
h5io-0.1.2//versioneer.pyfile:/versioneer.py:function:render_pep440_pre/render_pep440_pre
|
def render_pep440_pre(pieces):
"""TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
if pieces['distance']:
rendered += '.post.dev%d' % pieces['distance']
else:
rendered = '0.post.dev%d' % pieces['distance']
return rendered
|
fluidasserts-20.5.10030
|
fluidasserts-20.5.10030//fluidasserts/sca/npm.pyfile:/fluidasserts/sca/npm.py:function:_get_vuln_line/_get_vuln_line
|
def _get_vuln_line(reqs: list, pkg: str, ver: str) ->int:
"""Return the line of first occurrence of pkg and version in path or 0."""
line = list(map(lambda y: y[3], filter(lambda x: x[1] == pkg and x[2] ==
ver, reqs)))
return line[0] if line else 0
|
jsonpickle
|
jsonpickle//util.pyfile:/util.py:function:is_installed/is_installed
|
def is_installed(module):
"""Tests to see if ``module`` is available on the sys.path
>>> is_installed('sys')
True
>>> is_installed('hopefullythisisnotarealmodule')
False
"""
try:
__import__(module)
return True
except ImportError:
return False
|
beatle-0.2.4
|
beatle-0.2.4//beatle/app/bmpTools.pyfile:/beatle/app/bmpTools.py:function:GetBitmapMaxSize/GetBitmapMaxSize
|
def GetBitmapMaxSize(bitmapList):
"""
Gets the maximum width and height for a bitmap list
"""
width = 0
height = 0
for bmp in bitmapList:
width = max(width, bmp.GetWidth())
height = max(height, bmp.GetHeight())
return width, height
|
spyne-2.12.16
|
spyne-2.12.16//spyne/model/_base.pyclass:ModelBase/get_namespace_prefix
|
@classmethod
def get_namespace_prefix(cls, interface):
"""Returns the namespace prefix for the given interface. The
get_namespace_prefix of the interface class generates a prefix if none
is defined.
"""
ns = cls.get_namespace()
retval = interface.get_namespace_prefix(ns)
return retval
|
networkx
|
networkx//algorithms/assortativity/mixing.pyfile:/algorithms/assortativity/mixing.py:function:mixing_dict/mixing_dict
|
def mixing_dict(xy, normalized=False):
"""Returns a dictionary representation of mixing matrix.
Parameters
----------
xy : list or container of two-tuples
Pairs of (x,y) items.
attribute : string
Node attribute key
normalized : bool (default=False)
Return counts if False or probabilities if True.
Returns
-------
d: dictionary
Counts or Joint probability of occurrence of values in xy.
"""
d = {}
psum = 0.0
for x, y in xy:
if x not in d:
d[x] = {}
if y not in d:
d[y] = {}
v = d[x].get(y, 0)
d[x][y] = v + 1
psum += 1
if normalized:
for k, jdict in d.items():
for j in jdict:
jdict[j] /= psum
return d
|
elist-0.4.64
|
elist-0.4.64//elist/elist.pyfile:/elist/elist.py:function:interleave/interleave
|
def interleave(*arrays, **kwargs):
"""
arr1 = [1,2,3,4]
arr2 = ['a','b','c','d']
arr3 = ['@','#','%','*']
interleave(arr1,arr2,arr3)
"""
anum = arrays.__len__()
rslt = []
length = arrays[0].__len__()
for j in range(0, length):
for i in range(0, anum):
array = arrays[i]
rslt.append(array[j])
return rslt
|
uhb
|
uhb//psi.pyfile:/psi.py:function:Ncv/Ncv
|
def Ncv(c, H, D):
""" Vertical uplift factor for sand
"""
if c == 0:
return 0
return min(2 * H / D, 10)
|
taglightswitch-0.1.2
|
taglightswitch-0.1.2//taglightswitch/controltags.pyclass:ControlTags/explain_tags
|
@classmethod
def explain_tags(cls, body):
""" return usage string containing tag names, formats """
s = """
lightswitch:offhours=21:00-7:00
lightswitch:offhours=21:00-23:00
lightswitch:offmode=toggle
lightswitch:offmode=offonly
lightswitch:offdays=sat,sun
lightswitch:offdays=monday
"""
return s
|
fzutils
|
fzutils//spider/app_utils.pyfile:/spider/app_utils.py:function:u2_get_ui_obj/u2_get_ui_obj
|
def u2_get_ui_obj(d, resourceId=None, resourceIdMatches=None, text=None,
textContains=None, textMatches=None, textStartsWith=None, className=
None, classNameMatches=None, description=None, descriptionContains=None,
descriptionMatches=None, descriptionStartsWith=None, packageName=None,
packageNameMatches=None, checkable: bool=False, checked: bool=False,
clickable: bool=False, longClickable: bool=False, scrollable: bool=
False, enabled: bool=False, focusable: bool=False, focused: bool=False,
selected: bool=False, index: int=0, instance: int=0):
"""
u2获取指定UI元素对象(因为用u2编码时没有参数提示)
note: (参数默认值可从 from uiautomator2.session import Selector查看)
:return: UiObject (from uiautomator2.session import UiObject) eg: ele: UiObject = u2_get_ui_obj(d=d, resourceId='xxxx') 来调用后续方法
"""
kwargs = {}
if resourceId is not None:
kwargs.update({'resourceId': resourceId})
if resourceIdMatches is not None:
kwargs.update({'resourceIdMatches': resourceIdMatches})
if text is not None:
kwargs.update({'text': text})
if textContains is not None:
kwargs.update({'textContains': textContains})
if textMatches is not None:
kwargs.update({'textMatches': textMatches})
if textStartsWith is not None:
kwargs.update({'textStartsWith': textStartsWith})
if className is not None:
kwargs.update({'className': className})
if classNameMatches is not None:
kwargs.update({'classNameMatches': classNameMatches})
if description is not None:
kwargs.update({'description': description})
if descriptionContains is not None:
kwargs.update({'descriptionContains': descriptionContains})
if descriptionMatches is not None:
kwargs.update({'descriptionMatches': descriptionMatches})
if descriptionStartsWith is not None:
kwargs.update({'descriptionStartsWith': descriptionStartsWith})
if packageName is not None:
kwargs.update({'packageName': packageName})
if packageNameMatches is not None:
kwargs.update({'packageNameMatches': packageNameMatches})
if checkable:
kwargs.update({'checkable': checkable})
if checked:
kwargs.update({'checked': checked})
if clickable:
kwargs.update({'clickable': clickable})
if longClickable:
kwargs.update({'longClickable': longClickable})
if scrollable:
kwargs.update({'scrollable': scrollable})
if enabled:
kwargs.update({'enabled': enabled})
if focusable:
kwargs.update({'focusable': focusable})
if focused:
kwargs.update({'focused': focused})
if selected:
kwargs.update({'selected': selected})
if index != 0:
kwargs.update({'index': index})
if instance != 0:
kwargs.update({'instance': instance})
return d(**kwargs)
|
dropbox-10.1.2
|
dropbox-10.1.2//dropbox/team_log.pyclass:EventDetails/emm_create_exceptions_report_details
|
@classmethod
def emm_create_exceptions_report_details(cls, val):
"""
Create an instance of this class set to the
``emm_create_exceptions_report_details`` tag with value ``val``.
:param EmmCreateExceptionsReportDetails val:
:rtype: EventDetails
"""
return cls('emm_create_exceptions_report_details', val)
|
zenmake
|
zenmake//waf/waflib/Utils.pyfile:/waf/waflib/Utils.py:function:def_attrs/def_attrs
|
def def_attrs(cls, **kw):
"""
Sets default attributes on a class instance
:type cls: class
:param cls: the class to update the given attributes in.
:type kw: dict
:param kw: dictionary of attributes names and values.
"""
for k, v in kw.items():
if not hasattr(cls, k):
setattr(cls, k, v)
|
scrapydart
|
scrapydart//interfaces.pyclass:IEggStorage/get
|
def get(project, version=None):
"""Return a tuple (version, file) with the the egg for the specified
project and version. If version is None, the latest version is
returned. If no egg is found for the given project/version (None, None)
should be returned."""
|
clik-wtforms-0.90.1
|
clik-wtforms-0.90.1//src/clik_wtforms.pyfile:/src/clik_wtforms.py:function:stringify/stringify
|
def stringify(value):
"""
Return string ``value``, with quotes around if there is whitespace.
:param value: Value to stringify
:return: Stringified, possibly quoted, value
:rtype: :class:`str`
"""
rv = str(value)
if len(rv.split()) > 1:
return '"%s"' % rv
return rv
|
py4xs
|
py4xs//hdf.pyfile:/hdf.py:function:proc_line_profile/proc_line_profile
|
def proc_line_profile(queue, images, sn, nframes, detectors, qphi_range,
debug, starting_frame_no=0):
""" put the results in a dataset, with attributes describing where the results come from?
"""
pass
|
pyboto3-1.4.4
|
pyboto3-1.4.4//pyboto3/support.pyfile:/pyboto3/support.py:function:describe_communications/describe_communications
|
def describe_communications(caseId=None, beforeTime=None, afterTime=None,
nextToken=None, maxResults=None):
"""
Returns communications (and attachments) for one or more support cases. You can use the afterTime and beforeTime parameters to filter by date. You can use the caseId parameter to restrict the results to a particular case.
Case data is available for 12 months after creation. If a case was created more than 12 months ago, a request for data might cause an error.
You can use the maxResults and nextToken parameters to control the pagination of the result set. Set maxResults to the number of cases you want displayed on each page, and use nextToken to specify the resumption of pagination.
See also: AWS API Documentation
:example: response = client.describe_communications(
caseId='string',
beforeTime='string',
afterTime='string',
nextToken='string',
maxResults=123
)
:type caseId: string
:param caseId: [REQUIRED]
The AWS Support case ID requested or returned in the call. The case ID is an alphanumeric string formatted as shown in this example: case-12345678910-2013-c4c1d2bf33c5cf47
:type beforeTime: string
:param beforeTime: The end date for a filtered date search on support case communications. Case communications are available for 12 months after creation.
:type afterTime: string
:param afterTime: The start date for a filtered date search on support case communications. Case communications are available for 12 months after creation.
:type nextToken: string
:param nextToken: A resumption point for pagination.
:type maxResults: integer
:param maxResults: The maximum number of results to return before paginating.
:rtype: dict
:return: {
'communications': [
{
'caseId': 'string',
'body': 'string',
'submittedBy': 'string',
'timeCreated': 'string',
'attachmentSet': [
{
'attachmentId': 'string',
'fileName': 'string'
},
]
},
],
'nextToken': 'string'
}
"""
pass
|
DOE2-SIM-Parser-0.20
|
DOE2-SIM-Parser-0.20//versioneer.pyfile:/versioneer.py:function:scan_setup_py/scan_setup_py
|
def scan_setup_py():
"""Validate the contents of setup.py against Versioneer's expectations."""
found = set()
setters = False
errors = 0
with open('setup.py', 'r') as f:
for line in f.readlines():
if 'import versioneer' in line:
found.add('import')
if 'versioneer.get_cmdclass()' in line:
found.add('cmdclass')
if 'versioneer.get_version()' in line:
found.add('get_version')
if 'versioneer.VCS' in line:
setters = True
if 'versioneer.versionfile_source' in line:
setters = True
if len(found) != 3:
print('')
print('Your setup.py appears to be missing some important items')
print('(but I might be wrong). Please make sure it has something')
print('roughly like the following:')
print('')
print(' import versioneer')
print(' setup( version=versioneer.get_version(),')
print(' cmdclass=versioneer.get_cmdclass(), ...)')
print('')
errors += 1
if setters:
print("You should remove lines like 'versioneer.VCS = ' and")
print("'versioneer.versionfile_source = ' . This configuration")
print('now lives in setup.cfg, and should be removed from setup.py')
print('')
errors += 1
return errors
|
pycm
|
pycm//pycm_interpret.pyfile:/pycm_interpret.py:function:kappa_analysis_cicchetti/kappa_analysis_cicchetti
|
def kappa_analysis_cicchetti(kappa):
"""
Analysis kappa number with Cicchetti benchmark.
:param kappa: kappa number
:type kappa : float
:return: strength of agreement as str
"""
try:
if kappa < 0.4:
return 'Poor'
if kappa >= 0.4 and kappa < 0.59:
return 'Fair'
if kappa >= 0.59 and kappa < 0.74:
return 'Good'
if kappa >= 0.74 and kappa <= 1:
return 'Excellent'
return 'None'
except Exception:
return 'None'
|
asym_crypto_yaml-0.0.11
|
asym_crypto_yaml-0.0.11//asym_crypto_yaml/crypto.pyfile:/asym_crypto_yaml/crypto.py:function:chunk_input/chunk_input
|
def chunk_input(inp, number_of_characters_per_string):
"""
Breaks an input string inp into chunks of up to number_of_characters_per_string
"""
for i in range(0, len(inp), number_of_characters_per_string):
yield inp[i:i + number_of_characters_per_string]
|
nionswift_plugin
|
nionswift_plugin//TIFF_IO/tifffile.pyfile:/TIFF_IO/tifffile.py:function:enumarg/enumarg
|
def enumarg(enum, arg):
"""Return enum member from its name or value.
>>> enumarg(TIFF.PHOTOMETRIC, 2)
<PHOTOMETRIC.RGB: 2>
>>> enumarg(TIFF.PHOTOMETRIC, 'RGB')
<PHOTOMETRIC.RGB: 2>
"""
try:
return enum(arg)
except Exception:
try:
return enum[arg.upper()]
except Exception:
raise ValueError('invalid argument %s' % arg)
|
biobb_analysis-3.0.0
|
biobb_analysis-3.0.0//biobb_analysis/gromacs/common.pyfile:/biobb_analysis/gromacs/common.py:function:is_valid_index/is_valid_index
|
def is_valid_index(ext):
""" Checks if structure format is compatible with GROMACS """
formats = ['ndx']
return ext in formats
|
pyrates
|
pyrates//utility/annarchy_wrapper.pyfile:/utility/annarchy_wrapper.py:function:adapt_pop/adapt_pop
|
def adapt_pop(pop, params: dict, param_map: dict):
"""Changes the parametrization of a circuit.
Parameters
----------
pop
ANNarchy population instance.
params
Key-value pairs of the parameters that should be changed.
param_map
Map between the keys in params and the circuit variables.
Returns
-------
Population
Updated population instance.
"""
for key in params.keys():
val = params[key]
for op, var in param_map[key]['var']:
nodes = param_map[key]['nodes'] if 'nodes' in param_map[key] else [
]
for node in nodes:
if node in pop.name:
try:
pop.set({var: float(val)})
except TypeError:
pop.set({var: val})
except (KeyError, ValueError):
pass
return pop
|
nitransforms
|
nitransforms//io/itk.pyclass:ITKLinearTransform/from_filename
|
@classmethod
def from_filename(cls, filename):
"""Read the struct from a file given its path."""
if str(filename).endswith('.mat'):
with open(str(filename), 'rb') as fileobj:
return cls.from_binary(fileobj)
with open(str(filename)) as fileobj:
return cls.from_string(fileobj.read())
|
libs
|
libs//util.pyfile:/util.py:function:_deserialize_object/_deserialize_object
|
def _deserialize_object(value):
"""Return a original value.
:return: object.
"""
return value
|
oneupsdk
|
oneupsdk//integration/api.pyfile:/integration/api.py:function:configure_auth/configure_auth
|
def configure_auth(username=None, password=None):
"""
Override the configuration file sourced authentication information.
"""
_override_username = username
_override_password = password
|
fake-blender-api-2.79-0.3.1
|
fake-blender-api-2.79-0.3.1//bpy/ops/node.pyfile:/bpy/ops/node.py:function:duplicate_move_keep_inputs/duplicate_move_keep_inputs
|
def duplicate_move_keep_inputs(NODE_OT_duplicate=None,
NODE_OT_translate_attach=None):
"""Duplicate selected nodes keeping input links and move them
:param NODE_OT_duplicate: Duplicate Nodes, Duplicate selected nodes
:param NODE_OT_translate_attach: Move and Attach, Move nodes and attach to frame
"""
pass
|
mercurial-5.4
|
mercurial-5.4//mercurial/thirdparty/zope/interface/common/sequence.pyclass:IReadSequence/__gt__
|
def __gt__(other):
"""`x.__gt__(other)` <==> `x > other`"""
|
mxnet-1.6.0.data
|
mxnet-1.6.0.data//purelib/mxnet/ndarray/gen_op.pyfile:/purelib/mxnet/ndarray/gen_op.py:function:identity/identity
|
def identity(data=None, out=None, name=None, **kwargs):
"""Returns a copy of the input.
From:src/operator/tensor/elemwise_unary_op_basic.cc:246
Parameters
----------
data : NDArray
The input array.
out : NDArray, optional
The output NDArray to hold the result.
Returns
-------
out : NDArray or list of NDArrays
The output of this function.
"""
return 0,
|
sasmodels-1.0.2
|
sasmodels-1.0.2//sasmodels/convert.pyfile:/sasmodels/convert.py:function:_is_sld/_is_sld
|
def _is_sld(model_info, par):
"""
Return True if parameter is a magnetic magnitude or SLD parameter.
"""
if par.startswith('M0:'):
return True
if '_pd' in par or '.' in par:
return False
for p in model_info.parameters.call_parameters:
if p.id == par:
return p.type == 'sld'
for p in model_info.parameters.kernel_parameters:
if p.id == par:
return p.type == 'sld'
return False
|
PyVRML97-2.3.1
|
PyVRML97-2.3.1//vrml/protofunctions.pyfile:/vrml/protofunctions.py:function:root/root
|
def root(obj, value=None, *args, **named):
"""Get/set root-node reference for nodes/protos"""
from vrml import node
if value is not None:
return node.Node.rootSceneGraph.fset(obj, value, *args, **named)
else:
return node.Node.rootSceneGraph.fget(obj, *args, **named)
|
typped-0.1.3
|
typped-0.1.3//src/typped/pratt_parser.pyclass:TokenSubclassMeta/__radd__
|
def __radd__(cls, left_other):
"""The right version of `__add__` above."""
return left_other + cls.prod_rule_funs['Tok'](cls)
|
GetCCWarc
|
GetCCWarc//_version.pyfile:/_version.py:function:plus_or_dot/plus_or_dot
|
def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if '+' in pieces.get('closest-tag', ''):
return '.'
return '+'
|
ore.alchemist-0.6.0
|
ore.alchemist-0.6.0//src/ore/alchemist/interfaces.pyclass:ISchemaIntrospector/bindEngine
|
def bindEngine(engine, schema_name=None):
"""
bind the engine to the introspector, creates an internal bound metadata to the engine.
"""
|
tribology
|
tribology//p3can/numeric_methods.pyfile:/p3can/numeric_methods.py:function:secant_method/secant_method
|
def secant_method(x, fx):
"""Applies secant method to find root x of function f(x). If not enough
(x, f(x)) value pairs are known to apply secant method, a new x value is
guessed by slightly changing the initial x value"""
if fx[-1] != 0:
if len(x) > 1 and fx[-1] != 0 and abs(fx[-1]) != abs(fx[-2]):
x0 = x[-2]
x1 = x[-1]
fx0 = fx[-2]
fx1 = fx[-1]
m = (fx1 - fx0) / (x1 - x0)
return x1 + -fx1 / m
else:
return x[0] * 0.9 + 0.0001
else:
return x[-1]
|
RsCmwWlanSig-3.7.50.5
|
RsCmwWlanSig-3.7.50.5//RsCmwWlanSig/Internal/Utilities.pyfile:/RsCmwWlanSig/Internal/Utilities.py:function:get_plural_string/get_plural_string
|
def get_plural_string(word: str, amount: int) ->str:
"""Returns singular or plural of the word depending on the amount.
Example:
word = 'piece', amount = 0 -> '0 pieces'
word = 'piece', amount = 1 -> '1 piece'
word = 'piece', amount = 5 -> '5 pieces'"""
if amount == 1:
return f'1 {word}'
else:
return f'{amount} {word}s'
|
CifFile
|
CifFile//drel/drel_ast_yacc.pyfile:/drel/drel_ast_yacc.py:function:p_repeat_stmt/p_repeat_stmt
|
def p_repeat_stmt(p):
"""repeat_stmt : REPEAT suite"""
p[0] = ['REPEAT', p[2]]
|
electricpy-0.1.7
|
electricpy-0.1.7//electricpy/fault.pyfile:/electricpy/fault.py:function:highzmini/highzmini
|
def highzmini(N, Ie, Irly=None, Vset=None, Rrly=2000, Imov=0, CTR=1):
"""
Minimum Current for High Impedance Protection Calculator
Evaluates the minimum pickup current required to cause
high-impedance bus protection element pickup.
Parameters
----------
N: int
Number of Current Transformers included in scheme
Ie: float
The excitation current at the voltage setting
Irly: float, optional
The relay current at voltage setting
Vset: float, optional
The relay's voltage pickup setting in volts.
Rrly: float, optional
The relay's internal resistance in ohms, default=2000
Imov: float, optional
The overvoltage protection current at the
voltage setting. default=0.0
CTR: float, optional
Current Transformer Ratio, default=1
Returns
-------
Imin: float
Minimum current required to cause high-impedance
bus protection element pickup.
"""
if Irly == Vset == None:
raise ValueError('Relay Current Required.')
Ie = abs(Ie)
Imov = abs(Imov)
if Irly == None:
Vset = abs(Vset)
Irly = Vset / Rrly
else:
Irly = abs(Irly)
Imin = (N * Ie + Irly + Imov) * CTR
return Imin
|
sylib
|
sylib//atfparser/parser.pyfile:/atfparser/parser.py:function:p_prims2/p_prims2
|
def p_prims2(p):
"""prims : prims COMMA prim"""
p[1].append(p[3])
p[0] = p[1]
|
layabase
|
layabase//_database_sqlalchemy.pyclass:CRUDModel/get_last
|
@classmethod
def get_last(cls, **filters) ->dict:
"""
Return last revision of the model formatted as a dictionary.
"""
return cls.get(**filters)
|
fsds
|
fsds//default.pyfile:/default.py:function:Cohen_d/Cohen_d
|
def Cohen_d(group1, group2, correction=False):
"""Compute Cohen's d
d = (group1.mean()-group2.mean())/pool_variance.
pooled_variance= (n1 * var1 + n2 * var2) / (n1 + n2)
Args:
group1 (Series or NumPy array): group 1 for calculating d
group2 (Series or NumPy array): group 2 for calculating d
correction (bool): Apply equation correction if N<50. Default is False.
- Url with small ncorrection equation:
- https://www.statisticshowto.datasciencecentral.com/cohens-d/
Returns:
d (float): calculated d value
INTERPRETATION OF COHEN's D:
> Small effect = 0.2
> Medium Effect = 0.5
> Large Effect = 0.8
"""
import scipy.stats as stats
import scipy
import numpy as np
N = len(group1) + len(group2)
diff = group1.mean() - group2.mean()
n1, n2 = len(group1), len(group2)
var1 = group1.var()
var2 = group2.var()
pooled_var = (n1 * var1 + n2 * var2) / (n1 + n2)
d = diff / np.sqrt(pooled_var)
if (N < 50) & (correction == True):
d = d * ((N - 3) / (N - 2.25)) * np.sqrt((N - 2) / N)
return d
|
dropbox
|
dropbox//team_log.pyclass:EventType/shared_content_download
|
@classmethod
def shared_content_download(cls, val):
"""
Create an instance of this class set to the ``shared_content_download``
tag with value ``val``.
:param SharedContentDownloadType val:
:rtype: EventType
"""
return cls('shared_content_download', val)
|
cfgstack-0.1.post28
|
cfgstack-0.1.post28//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
|
openfisca_france
|
openfisca_france//model/prelevements_obligatoires/impot_revenu/reductions_impot.pyclass:doment/formula_2010_01_01
|
def formula_2010_01_01(foyer_fiscal, period, parameters):
"""
Investissements dans les DOM-TOM dans le cadre d'une entreprise.
"""
f7oz = foyer_fiscal('f7oz', period)
f7pz = foyer_fiscal('f7pz', period)
f7qz = foyer_fiscal('f7qz_2012', period)
f7rz = foyer_fiscal('f7rz_2010', period)
f7qe = foyer_fiscal('f7qe', period)
f7qf = foyer_fiscal('f7qf', period)
f7qg = foyer_fiscal('f7qg', period)
f7qh = foyer_fiscal('f7qh', period)
f7qi = foyer_fiscal('f7qi', period)
f7qj = foyer_fiscal('f7qj', period)
f7qo = foyer_fiscal('f7qo_2012', period)
f7qp = foyer_fiscal('f7qp_2012', period)
f7qq = foyer_fiscal('f7qq', period)
f7qr = foyer_fiscal('f7qr_2012', period)
f7qs = foyer_fiscal('f7qs', period)
f7mm = foyer_fiscal('f7mm', period)
f7ma = foyer_fiscal('f7ma', period)
f7lg = foyer_fiscal('f7lg', period)
f7ks = foyer_fiscal('f7ks', period)
f7ls = foyer_fiscal('f7ls', period)
return (f7ks + f7lg + f7ls + f7ma + f7mm + f7oz + f7pz + f7qe + f7qf +
f7qg + f7qh + f7qi + f7qj + f7qo + f7qp + f7qq + f7qr + f7qs + f7qz +
f7rz)
|
aggregation_builder-0.0.4
|
aggregation_builder-0.0.4//aggregation_builder/operators/date.pyfile:/aggregation_builder/operators/date.py:function:DAY_OF_YEAR/DAY_OF_YEAR
|
def DAY_OF_YEAR(expression):
"""
Returns the day of the year for a date as a number between 1 and 366.
See https://docs.mongodb.com/manual/reference/operator/aggregation/dayOfYear/
for more details
:param expression: expression or variable of a Date, a Timestamp, or an ObjectID
:return: Aggregation operator
"""
return {'$dayOfYear': expression}
|
learn2map-0.6.6
|
learn2map-0.6.6//learn2map/data_learning.pyfile:/learn2map/data_learning.py:function:rfbc_tune/rfbc_tune
|
def rfbc_tune(learn_rfbc, n_feature, min_thres=30):
"""
tuning parameters for the xgboost regression model
:param n_feature: number of features
:param learn_rfbc: GridLearn class object
:return: learn_rfbc: GridLearn class object
"""
learn_rfbc.setup_rfbc_model()
params = {'learn__max_depth': list(range(3, 40, 4)),
'learn__max_features': [int(0.2 * n_feature), int(0.4 * n_feature),
int(0.6 * n_feature), int(0.8 * n_feature)], 'learn__n_estimators':
list(range(50, 501, 100))}
learn_rfbc.clean_and_tune(params, k=5, min_thres=min_thres)
return learn_rfbc
|
pyNastran
|
pyNastran//converters/shabp/shabp.pyfile:/converters/shabp/shabp.py:function:parse_viscous/parse_viscous
|
def parse_viscous(lines, line, i):
"""
Parses the viscous table (method=4)
140 viscous_run (level 2)
11 1
000
5 5000 0.0000 1.0000 0.0000 1.0000 3.0000 3.0000
2 0 4 1 1 1 1 1 0 0 0 1 1 0 1
1.500000E2 3.000000E2 1.600000E1 3.000000E1 9.000000E1
5.000000E2 8.000000E-1 1.200000E1 0.000000E0 0.000000E0
21 1
...
"""
line = lines[i].rstrip()
ncomp = int(line[0:2])
unused_ifsave = line[2:3]
unused_title = line[6:66].strip()
i += 1
for unused_icompi in range(ncomp):
line = lines[i].rstrip()
unused_a, unused_b = line.split()
unused_icomp = int(line[:3])
unused_isk = line[3]
unused_nskin_friction_elements = line[4:7]
i += 6
line = lines[i].rstrip()
return i
|
reportforce-0.0.6
|
reportforce-0.0.6//reportforce/helpers/parsers.pyfile:/reportforce/helpers/parsers.py:function:get_report_total/get_report_total
|
def get_report_total(report):
"""Get a report grand total."""
return report['factMap']['T!T']['aggregates'][0]['value']
|
plotnine-0.6.0
|
plotnine-0.6.0//plotnine/doctools.pyfile:/plotnine/doctools.py:function:parameters_dict_to_str/parameters_dict_to_str
|
def parameters_dict_to_str(d):
"""
Convert a dict of param section to a string
Parameters
----------
d : dict
Parameters and their descriptions in a docstring
Returns
-------
param_section : str
Text in the parameter section
See Also
--------
:func:`parameters_str_to_dict`
"""
return '\n'.join(d.values())
|
nengo-dl-3.2.0
|
nengo-dl-3.2.0//nengo_dl/builder.pyclass:OpBuilder/mergeable
|
@staticmethod
def mergeable(x, y):
"""
Compute the mergeability of two operators of this builder's type.
Parameters
----------
x : `nengo.builder.Operator`
The operator being tested
y : `nengo.builder.Operator`
The operator being merged into (this is representative of a group
of operators that have already been merged)
Returns
-------
mergeable : bool
True if ``x`` and ``y`` can be merged into a single built op,
else ``False``.
"""
return False
|
hepdata_validator-0.2.1
|
hepdata_validator-0.2.1//hepdata_validator/data_file_validator.pyfile:/hepdata_validator/data_file_validator.py:function:convert_to_float/convert_to_float
|
def convert_to_float(error):
"""
Convert error from a string to a float if possible.
:param error: uncertainty from either 'symerror' or 'asymerror'
:return: error as a float if possible, otherwise the original string
"""
if isinstance(error, str):
error = error.replace('%', '')
try:
error = float(error)
except ValueError:
pass
return error
|
pyboto3-1.4.4
|
pyboto3-1.4.4//pyboto3/wafregional.pyfile:/pyboto3/wafregional.py:function:list_resources_for_web_acl/list_resources_for_web_acl
|
def list_resources_for_web_acl(WebACLId=None):
"""
Returns an array of resources associated with the specified web ACL.
See also: AWS API Documentation
:example: response = client.list_resources_for_web_acl(
WebACLId='string'
)
:type WebACLId: string
:param WebACLId: [REQUIRED]
The unique identifier (ID) of the web ACL for which to list the associated resources.
:rtype: dict
:return: {
'ResourceArns': [
'string',
]
}
"""
pass
|
farc
|
farc//Hsm.pyclass:Hsm/state
|
def state(func):
"""A decorator that identifies which methods are states.
The presence of the farc_state attr, not its value,
determines statehood.
The Spy debugging system uses the farc_state attribute
to determine which methods inside a class are actually states.
Other uses of the attribute may come in the future.
"""
setattr(func, 'farc_state', True)
return staticmethod(func)
|
reports
|
reports//utils.pyfile:/utils.py:function:parse_updates/parse_updates
|
def parse_updates(updates_string):
""" Parses updates string in a report and returns a sanitized version
"""
updates = []
ulist = updates_string.split()
while ulist:
updates.append('{0!s} {1!s} {2!s}\n'.format(ulist[0], ulist[1],
ulist[2]))
ulist.pop(0)
ulist.pop(0)
ulist.pop(0)
return updates
|
trusat
|
trusat//tle_util.pyfile:/tle_util.py:function:tle_fmt_int/tle_fmt_int
|
def tle_fmt_int(num, digits=5):
""" Return an integer right-aligned string with DIGITS of precision, all blank if num=0
Ignores sign.
"""
if num:
num = abs(num)
else:
return ' ' * digits
string_int = '{:>{DIGITS}d}'.format(num, DIGITS=digits)
return string_int
|
pya2l-0.0.1
|
pya2l-0.0.1//pya2l/parser/grammar/parser.pyclass:A2lParser/p_byte_order
|
@staticmethod
def p_byte_order(p):
"""byte_order : BYTE_ORDER byte_order_type"""
p[0] = p[2]
|
mosaik-2.5.3
|
mosaik-2.5.3//mosaik/scheduler.pyfile:/mosaik/scheduler.py:function:wait_for_dependencies/wait_for_dependencies
|
def wait_for_dependencies(world, sim):
"""
Return an event (:class:`simpy.events.AllOf`) that is triggered when
all dependencies can provide input data for *sim*.
Also notify any simulator that is already waiting to perform its next step.
*world* is a mosaik :class:`~mosaik.scenario.World`.
"""
events = []
t = sim.next_step
dfg = world.df_graph
for dep_sid in dfg.predecessors(sim.sid):
dep = world.sims[dep_sid]
if t in world._df_cache and dep_sid in world._df_cache[t]:
continue
evt = world.env.event()
events.append(evt)
world.df_graph[dep_sid][sim.sid]['wait_event'] = evt
if not dep.step_required.triggered:
dep.step_required.succeed()
for suc_sid in dfg.successors(sim.sid):
suc = world.sims[suc_sid]
if dfg[sim.sid][suc_sid]['async_requests'] and suc.next_step < t:
evt = world.env.event()
events.append(evt)
world.df_graph[sim.sid][suc_sid]['wait_async'] = evt
clg = world.shifted_graph
for dep_sid in clg.predecessors(sim.sid):
dep = world.sims[dep_sid]
if dep.next_step < t:
evt = world.env.event()
events.append(evt)
clg[dep_sid][sim.sid]['wait_shifted'] = evt
return world.env.all_of(events)
|
geo-squizzy-0.2.2
|
geo-squizzy-0.2.2//geosquizzy/optimum/neurons.pyfile:/geosquizzy/optimum/neurons.py:function:rationality/rationality
|
def rationality(x):
"""
:param x [x, y, z, k, g] history record
Neuron sense, rationality will focus on x[4] which is a
difference in omitted objects between current and last history record
"""
try:
return x[3] / x[4]
except ZeroDivisionError:
return 0
|
bx-python-0.8.8
|
bx-python-0.8.8//lib/bx_extras/pstat.pyfile:/lib/bx_extras/pstat.py:function:flat/flat
|
def flat(l):
"""
Returns the flattened version of a '2D' list. List-correlate to the a.flat()
method of NumPy arrays.
Usage: flat(l)
"""
newl = []
for i in range(len(l)):
for j in range(len(l[i])):
newl.append(l[i][j])
return newl
|
pyboto3-1.4.4
|
pyboto3-1.4.4//pyboto3/redshift.pyfile:/pyboto3/redshift.py:function:delete_cluster_parameter_group/delete_cluster_parameter_group
|
def delete_cluster_parameter_group(ParameterGroupName=None):
"""
Deletes a specified Amazon Redshift parameter group.
See also: AWS API Documentation
:example: response = client.delete_cluster_parameter_group(
ParameterGroupName='string'
)
:type ParameterGroupName: string
:param ParameterGroupName: [REQUIRED]
The name of the parameter group to be deleted.
Constraints:
Must be the name of an existing cluster parameter group.
Cannot delete a default cluster parameter group.
"""
pass
|
shoobx.immutable-2.0.2
|
shoobx.immutable-2.0.2//src/shoobx/immutable/interfaces.pyclass:IImmutable/__im_create__
|
def __im_create__(cls, mode: str=None, finalize=True, *create_args, **create_kw
):
"""Returns a context manager allowing the `cls` class to be instantiated
Within the context you can set any attribute on the object,
call any method to setup the initial state.
Exiting the context shall finalize the object.
* `mode`: gets set on the object as it's `__im_mode__`
* `finalize`: the object gets finalized at the very end
* `create_args`, `create_kw`: get passed to `cls.__im_after_create__`
right after `cls.__init__` is called, thus allowing to set e.g.
`creator` before the object is finalized
"""
|
dyban
|
dyban//priors.pyfile:/priors.py:function:calculateChangePointsSetPrior/calculateChangePointsSetPrior
|
def calculateChangePointsSetPrior(changepointsSet):
"""
Function that returns the prior probability of the changepoint set tau
Args:
changepointsSet : list<int>
a list that contains the proposed changepoint set
Returns:
res : float
the prior probability of the changepointset
"""
changepointsSetCopy = changepointsSet.copy()
changepointsSetCopy.insert(0, 1)
p = 0.125
if len(changepointsSetCopy) > 10:
res = 0
else:
tau_h = changepointsSetCopy[-1] - 1
tau_h_minus = changepointsSetCopy[-2]
el1 = (1 - p) ** (tau_h - tau_h_minus)
el2 = 1
for idx in range(len(changepointsSet) - 1):
curTau_h = changepointsSetCopy[idx + 1]
curTau_h_minus = changepointsSetCopy[idx]
currEl2 = p * (1 - p) ** (curTau_h - curTau_h_minus - 1)
el2 = el2 * currEl2
res = el1 * el2
return res
|
swat
|
swat//cas/table.pyclass:CASTable/from_records
|
@classmethod
def from_records(cls, connection, data, casout=None, **kwargs):
"""
Create a CASTable from records
Parameters
----------
connection : :class:`CAS`
The :class:`CAS` connection to read the data into.
data : :func:`numpy.ndarray`, list-of-tuples, dict, or :class:`pandas.DataFrame`
The data to upload.
casout : string or :class:`CASTable`, optional
The output table specification. This includes the following parameters.
name : string, optional
Name of the output CAS table.
caslib : string, optional
CASLib for the output CAS table.
label : string, optional
The label to apply to the output CAS table.
promote : boolean, optional
If True, the output CAS table will be visible in all sessions.
replace : boolean, optional
If True, the output CAS table will replace any existing CAS.
table with the same name.
**kwargs : keyword arguments
Keyword arguments sent to :meth:`pandas.DataFrame.from_records`.
See Also
--------
:meth:`pandas.DataFrame.from_records`
Returns
-------
:class:`CASTable`
"""
return cls._from_any('records', connection, data, casout=casout, **kwargs)
|
currency.converter-0.5.5
|
currency.converter-0.5.5//currency/converter/interfaces.pyclass:IPortalCurrency/portal_currency_code
|
def portal_currency_code():
"""Returns default currency code of portal."""
|
sokoenginepy-0.5.3
|
sokoenginepy-0.5.3//src/sokoenginepy/utilities/coordinate_helpers.pyfile:/src/sokoenginepy/utilities/coordinate_helpers.py:function:index_1d/index_1d
|
def index_1d(x, y, board_width):
"""Converts 2D coordinate to board position index."""
return y * board_width + x
|
golem-framework-0.9.0
|
golem-framework-0.9.0//golem/core/settings_manager.pyfile:/golem/core/settings_manager.py:function:get_remote_browsers/get_remote_browsers
|
def get_remote_browsers(settings):
"""Return the defined remote browsers in settings."""
remote_browsers = {}
if 'remote_browsers' in settings:
remote_browsers = settings['remote_browsers']
return remote_browsers
|
pvml
|
pvml//multiclass.pyfile:/multiclass.py:function:one_vs_rest_train/one_vs_rest_train
|
def one_vs_rest_train(X, Y, train_fun):
"""Train a multi-class classifier using the one vs. rest strategy.
Parameters
----------
X : ndarray, shape (m, n)
training features.
Y : ndarray, shape (m,)
training labels in the range 0, ..., (k - 1).
train_fun : function that, given X and a set of binary labels, trains
a binary classifier. The function must return a tuple, where the
last element is the list of loss values obtained during training,
and all the others are the parameters of the trained classifier.
Returns
-------
params : dict
collection of (class, parameters) representing the binary classifiers.
loss : ndarray, shape (steps,)
average loss value after each training iteration.
"""
k = Y.max() + 1
m, n = X.shape
loss = 0
classifiers = {}
for c in range(k):
Ybin = Y == c
result = train_fun(X, Ybin)
classifiers[c] = result[:-1]
loss = loss + result[-1]
return classifiers, loss / k
|
signac-1.4.0
|
signac-1.4.0//signac/contrib/import_export.pyfile:/signac/contrib/import_export.py:function:_convert_bool/_convert_bool
|
def _convert_bool(value):
"""Convert a boolean value encoded as string to corresponding bool."""
return {'true': True, '1': True, 'false': False, '0': False}.get(value.
lower(), bool(value))
|
astropy-4.0.1.post1
|
astropy-4.0.1.post1//astropy/utils/state.pyclass:ScienceState/get
|
@classmethod
def get(cls):
"""
Get the current science state value.
"""
return cls.validate(cls._value)
|
django-sitemetrics-1.1.0
|
django-sitemetrics-1.1.0//sitemetrics/providers.pyclass:MetricsProvider/get_template_name
|
@classmethod
def get_template_name(cls):
"""Returns js counter code template path."""
return 'sitemetrics/%s.html' % cls.alias
|
mxnet
|
mxnet//ndarray/gen_sparse.pyfile:/ndarray/gen_sparse.py:function:sin/sin
|
def sin(data=None, out=None, name=None, **kwargs):
"""Computes the element-wise sine of the input array.
The input should be in radians (:math:`2\\pi` rad equals 360 degrees).
.. math::
sin([0, \\pi/4, \\pi/2]) = [0, 0.707, 1]
The storage type of ``sin`` output depends upon the input storage type:
- sin(default) = default
- sin(row_sparse) = row_sparse
- sin(csr) = csr
Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L47
Parameters
----------
data : NDArray
The input array.
out : NDArray, optional
The output NDArray to hold the result.
Returns
-------
out : NDArray or list of NDArrays
The output of this function.
"""
return 0,
|
Blue-DiscordBot-3.2.0
|
Blue-DiscordBot-3.2.0//bluebot/core/drivers/red_mongo.pyclass:Mongo/_escape_dict_keys
|
@classmethod
def _escape_dict_keys(cls, data: dict) ->dict:
"""Recursively escape all keys in a dict."""
ret = {}
for key, value in data.items():
key = cls._escape_key(key)
if isinstance(value, dict):
value = cls._escape_dict_keys(value)
ret[key] = value
return ret
|
pcuf-0.1.9
|
pcuf-0.1.9//pcuf/containers.pyfile:/pcuf/containers.py:function:lookahead/lookahead
|
def lookahead(iterable):
"""Pass through all values from the given iterable, augmented by the
information if there are more values to come after the current one
(True), or if it is the last value (False).
"""
it = iter(iterable)
last = next(it)
for val in it:
yield last, True
last = val
yield last, False
|
formal
|
formal//model_mongodb.pyclass:Model/find_or_create
|
@classmethod
def find_or_create(cls, query, *args, **kwargs):
""" Retrieve an element from the database. If it doesn't exist, create
it. Calling this method is equivalent to calling find_one and then
creating an object. Note that this method is not atomic. """
result = cls.find_one(query, *args, **kwargs)
if result is None:
default = cls._schema.get('default', {})
default.update(query)
result = cls(default, *args, **kwargs)
return result
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.