uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9856c8135f78dee89d3a5a3f | train | function | def transform(vector3, matrix4x4):
""" Apply a transformation matrix on a 3D vector.
:param vector3: array with 3 elements
:param matrix4x4: 4x4 matrix
"""
if numpy:
return numpy.dot(matrix4x4, numpy.append(vector3, 1.))
else:
m0,m1,m2,m3 = matrix4x4; x,y,z = vector3
ret... | def transform(vector3, matrix4x4):
| """ Apply a transformation matrix on a 3D vector.
:param vector3: array with 3 elements
:param matrix4x4: 4x4 matrix
"""
if numpy:
return numpy.dot(matrix4x4, numpy.append(vector3, 1.))
else:
m0,m1,m2,m3 = matrix4x4; x,y,z = vector3
return [
m0[0]*x + m0[1]*y... | _dirs:
if 'assimp' in dir_candidate.lower():
additional_dirs.append(dir_candidate)
#print(additional_dirs)
def vec2tuple(x):
""" Converts a VECTOR3D to a Tuple """
return (x.x, x.y, x.z)
def transform(vector3, matrix4x4):
| 64 | 64 | 211 | 10 | 54 | IKholopov/TierGine | external/Assimp/port/PyAssimp/pyassimp/helper.py | Python | transform | transform | 63 | 78 | 63 | 63 | 3dcb4ba5c36ca6047d501d0dcd029277163c06b4 | bigcode/the-stack | train |
6b422ff96d9804367ed3d213 | train | function | def vec2tuple(x):
""" Converts a VECTOR3D to a Tuple """
return (x.x, x.y, x.z)
| def vec2tuple(x):
| """ Converts a VECTOR3D to a Tuple """
return (x.x, x.y, x.z)
| ')
elif os.name=='nt':
ext_whitelist.append('.dll')
path_dirs = os.environ['PATH'].split(';')
for dir_candidate in path_dirs:
if 'assimp' in dir_candidate.lower():
additional_dirs.append(dir_candidate)
#print(additional_dirs)
def vec2tuple(x):
| 64 | 64 | 29 | 6 | 58 | IKholopov/TierGine | external/Assimp/port/PyAssimp/pyassimp/helper.py | Python | vec2tuple | vec2tuple | 59 | 61 | 59 | 59 | e37befad7c8dc93d262500056784cbf9b1c32766 | bigcode/the-stack | train |
3e3701bc96813e4eec1887e8 | train | function | def get_bounding_box_for_node(node, bb_min, bb_max, transformation):
if numpy:
transformation = numpy.dot(transformation, node.transformation)
else:
t0,t1,t2,t3 = transformation
T0,T1,T2,T3 = node.transformation
transformation = [ [
t0[0]*T0[0] + t0[1]*T1[0] + t0... | def get_bounding_box_for_node(node, bb_min, bb_max, transformation):
| if numpy:
transformation = numpy.dot(transformation, node.transformation)
else:
t0,t1,t2,t3 = transformation
T0,T1,T2,T3 = node.transformation
transformation = [ [
t0[0]*T0[0] + t0[1]*T1[0] + t0[2]*T2[0] + t0[3]*T3[0],
t0[0]*T0[1] + t0[1]*T1[1] + t... | 0]*m1[2]*m3[1] + m0[1]*m1[0]*m3[2] - m0[0]*m1[1]*m3[2]) /det,
( m0[1]*m1[2]*m2[0] - m0[2]*m1[1]*m2[0] + m0[2]*m1[0]*m2[1] - m0[0]*m1[2]*m2[1] - m0[1]*m1[0]*m2[2] + m0[0]*m1[1]*m2[2]) /det]]
def get_bounding_box(scene):
bb_min = [1e10, 1e10, 1e10] # x,y,z
bb_max = [-1e10, -1e10, -1e10] # x,y,z
i... | 256 | 256 | 946 | 17 | 239 | IKholopov/TierGine | external/Assimp/port/PyAssimp/pyassimp/helper.py | Python | get_bounding_box_for_node | get_bounding_box_for_node | 119 | 162 | 119 | 120 | 838ce01b005c01d9bee3013aeef2c7c1518dd258 | bigcode/the-stack | train |
ee1b3cf6591fbbeacdefd110 | train | function | def hasattr_silent(object, name):
"""
Calls hasttr() with the given parameters and preserves the legacy (pre-Python 3.2)
functionality of silently catching exceptions.
Returns the result of hasatter() or False if an exception was raised.
"""
try:
return hasattr(object, name... | def hasattr_silent(object, name):
| """
Calls hasttr() with the given parameters and preserves the legacy (pre-Python 3.2)
functionality of silently catching exceptions.
Returns the result of hasatter() or False if an exception was raised.
"""
try:
return hasattr(object, name)
except:
return False... | 1000 dll/so files containing 'assimp'
# in their name, do we have all of them in our address
# space now until gc kicks in?
# XXX: take version postfix of the .so on linux?
return res[1:]
def hasattr_silent(object, name):
| 64 | 64 | 74 | 8 | 56 | IKholopov/TierGine | external/Assimp/port/PyAssimp/pyassimp/helper.py | Python | hasattr_silent | hasattr_silent | 262 | 273 | 262 | 262 | 448957e963de4d617374c7ad90571db97a87b881 | bigcode/the-stack | train |
619409a7949768c29299421b | train | function | def _inv(matrix4x4):
m0,m1,m2,m3 = matrix4x4
det = m0[3]*m1[2]*m2[1]*m3[0] - m0[2]*m1[3]*m2[1]*m3[0] - \
m0[3]*m1[1]*m2[2]*m3[0] + m0[1]*m1[3]*m2[2]*m3[0] + \
m0[2]*m1[1]*m2[3]*m3[0] - m0[1]*m1[2]*m2[3]*m3[0] - \
m0[3]*m1[2]*m2[0]*m3[1] + m0[2]*m1[3]*m2[0]*m3[1] + \
... | def _inv(matrix4x4):
| m0,m1,m2,m3 = matrix4x4
det = m0[3]*m1[2]*m2[1]*m3[0] - m0[2]*m1[3]*m2[1]*m3[0] - \
m0[3]*m1[1]*m2[2]*m3[0] + m0[1]*m1[3]*m2[2]*m3[0] + \
m0[2]*m1[1]*m2[3]*m3[0] - m0[1]*m1[2]*m2[3]*m3[0] - \
m0[3]*m1[2]*m2[0]*m3[1] + m0[2]*m1[3]*m2[0]*m3[1] + \
m0[3]*m1[0]*m2[... | (dir_candidate)
#print(additional_dirs)
def vec2tuple(x):
""" Converts a VECTOR3D to a Tuple """
return (x.x, x.y, x.z)
def transform(vector3, matrix4x4):
""" Apply a transformation matrix on a 3D vector.
:param vector3: array with 3 elements
:param matrix4x4: 4x4 matrix
"""
if numpy:
... | 256 | 256 | 2,155 | 8 | 248 | IKholopov/TierGine | external/Assimp/port/PyAssimp/pyassimp/helper.py | Python | _inv | _inv | 80 | 111 | 80 | 80 | f4d06b1380ad57c9b4cd5ce0e1a1a504dae3fe50 | bigcode/the-stack | train |
c32c3fbe924709234eff6934 | train | function | def try_load_functions(library_path, dll):
'''
Try to bind to aiImportFile and aiReleaseImport
Arguments
---------
library_path: path to current lib
dll: ctypes handle to library
Returns
---------
If unsuccessful:
None
If successful:
Tuple containing (l... | def try_load_functions(library_path, dll):
| '''
Try to bind to aiImportFile and aiReleaseImport
Arguments
---------
library_path: path to current lib
dll: ctypes handle to library
Returns
---------
If unsuccessful:
None
If successful:
Tuple containing (library_path,
load... | ])
bb_max[2] = max(bb_max[2], v[2])
for child in node.children:
bb_min, bb_max = get_bounding_box_for_node(child, bb_min, bb_max, transformation)
return bb_min, bb_max
def try_load_functions(library_path, dll):
| 66 | 66 | 220 | 10 | 55 | IKholopov/TierGine | external/Assimp/port/PyAssimp/pyassimp/helper.py | Python | try_load_functions | try_load_functions | 164 | 199 | 164 | 164 | c687d88c89e06d04812730b7754d18d4ddae0de1 | bigcode/the-stack | train |
c6bc0c295d3295299bed6028 | train | function | def get_bounding_box(scene):
bb_min = [1e10, 1e10, 1e10] # x,y,z
bb_max = [-1e10, -1e10, -1e10] # x,y,z
inv = numpy.linalg.inv if numpy else _inv
return get_bounding_box_for_node(scene.rootnode, bb_min, bb_max, inv(scene.rootnode.transformation))
| def get_bounding_box(scene):
| bb_min = [1e10, 1e10, 1e10] # x,y,z
bb_max = [-1e10, -1e10, -1e10] # x,y,z
inv = numpy.linalg.inv if numpy else _inv
return get_bounding_box_for_node(scene.rootnode, bb_min, bb_max, inv(scene.rootnode.transformation))
| ]*m2[1] - m0[0]*m1[2]*m2[1] - m0[1]*m1[0]*m2[2] + m0[0]*m1[1]*m2[2]) /det]]
def get_bounding_box(scene):
| 64 | 64 | 92 | 7 | 57 | IKholopov/TierGine | external/Assimp/port/PyAssimp/pyassimp/helper.py | Python | get_bounding_box | get_bounding_box | 113 | 117 | 113 | 113 | d581f19043c035b27f99ffa6ae763d48faee0639 | bigcode/the-stack | train |
99515e8ce49e313da142bf43 | train | function | @borg.on(admin_cmd(pattern=r"call"))
async def _(event):
if event.fwd_from:
return
animation_interval = 3
animation_ttl = range(0, 18)
# input_str = event.pattern_match.group(1)
# if input_str == "call":
await event.edit("Calling")
animation_chars = [
"**Connecting To... | @borg.on(admin_cmd(pattern=r"call"))
async def _(event):
| if event.fwd_from:
return
animation_interval = 3
animation_ttl = range(0, 18)
# input_str = event.pattern_match.group(1)
# if input_str == "call":
await event.edit("Calling")
animation_chars = [
"**Connecting To Telegram Headquarters...**",
"**Call Connected.**... | """call
Available Commands:
.call
"""
import asyncio
from telethon import events
from userbot import ALIVE_NAME
from userbot.utils import admin_cmd
DEFAULTUSER = str(ALIVE_NAME) if ALIVE_NAME else "@pureindialover"
@borg.on(admin_cmd(pattern=r"call"))
async def _(event):
| 68 | 129 | 430 | 15 | 53 | abhijha099/IndianBot | userbot/plugins/call.py | Python | _ | _ | 15 | 57 | 15 | 17 | 55206c5cd95d944e72578a0e08d9b03013668e67 | bigcode/the-stack | train |
e6357661c1650df50a65097f | train | function | def do_aa_descriptor(conf, cert=None, enc_cert=None):
aad = md.AttributeAuthorityDescriptor()
aad.protocol_support_enumeration = samlp.NAMESPACE
endps = conf.getattr("endpoints", "aa")
if endps:
for (endpoint, instlist) in do_endpoints(endps,
EN... | def do_aa_descriptor(conf, cert=None, enc_cert=None):
| aad = md.AttributeAuthorityDescriptor()
aad.protocol_support_enumeration = samlp.NAMESPACE
endps = conf.getattr("endpoints", "aa")
if endps:
for (endpoint, instlist) in do_endpoints(endps,
ENDPOINTS["aa"]).items():
setattr(aad, endpo... | psso, key, DEFAULT[key])
else:
setattr(idpsso, key, ("%s" % val).lower())
except KeyError:
setattr(idpsso, key, DEFAULTS[key])
return idpsso
def do_aa_descriptor(conf, cert=None, enc_cert=None):
| 64 | 64 | 203 | 14 | 49 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_aa_descriptor | do_aa_descriptor | 627 | 654 | 627 | 627 | 69302bb424b83eaaa385423f10fa9127a6788572 | bigcode/the-stack | train |
9c83b269a6cf2d9eb8ad4e8e | train | function | def entities_descriptor(eds, valid_for, name, ident, sign, secc, sign_alg=None,
digest_alg=None):
entities = md.EntitiesDescriptor(entity_descriptor=eds)
if valid_for:
entities.valid_until = in_a_while(hours=valid_for)
if name:
entities.name = name
if ident:
... | def entities_descriptor(eds, valid_for, name, ident, sign, secc, sign_alg=None,
digest_alg=None):
| entities = md.EntitiesDescriptor(entity_descriptor=eds)
if valid_for:
entities.valid_until = in_a_while(hours=valid_for)
if name:
entities.name = name
if ident:
entities.id = ident
if sign:
if not ident:
ident = sid()
if not secc.key_file:
... | _cert)
if "aq" in serves:
confd.context = "aq"
entd.authn_authority_descriptor = do_aq_descriptor(confd, mycert,
enc_cert)
return entd
def entities_descriptor(eds, valid_for, name, ident, sign, secc, sign_alg=None,
... | 73 | 73 | 244 | 27 | 45 | hospiq/pysaml2 | src/saml2/metadata.py | Python | entities_descriptor | entities_descriptor | 773 | 804 | 773 | 774 | 94fe4f2355be9e49d6071947e12e84af774c6b19 | bigcode/the-stack | train |
344a200cec6e2738b0ac41ff | train | function | def metadata_tostring_fix(desc, nspair, xmlstring=""):
if not xmlstring:
xmlstring = desc.to_string(nspair)
if six.PY2:
if "\"xs:string\"" in xmlstring and XMLNSXS not in xmlstring:
xmlstring = xmlstring.replace(MDNS, MDNS + XMLNSXS)
else:
if b"\"xs:string\"" in xmlstrin... | def metadata_tostring_fix(desc, nspair, xmlstring=""):
| if not xmlstring:
xmlstring = desc.to_string(nspair)
if six.PY2:
if "\"xs:string\"" in xmlstring and XMLNSXS not in xmlstring:
xmlstring = xmlstring.replace(MDNS, MDNS + XMLNSXS)
else:
if b"\"xs:string\"" in xmlstring and bXMLNSXS not in xmlstring:
xmlstring ... | 0:metadata"'
XMLNSXS = " xmlns:xs=\"http://www.w3.org/2001/XMLSchema\""
bXMLNSXS = b" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\""
def metadata_tostring_fix(desc, nspair, xmlstring=""):
| 64 | 64 | 123 | 15 | 48 | hospiq/pysaml2 | src/saml2/metadata.py | Python | metadata_tostring_fix | metadata_tostring_fix | 65 | 76 | 65 | 65 | 23966494bec164366323639996bba04cd8692d2c | bigcode/the-stack | train |
6e3807988ca2500c099d511e | train | function | def do_requested_attribute(attributes, acs, is_required="false",
name_format=NAME_FORMAT_URI):
lista = []
for attr in attributes:
attr = from_local_name(acs, attr, name_format)
args = {}
if isinstance(attr, six.string_types):
args["name"] = attr
... | def do_requested_attribute(attributes, acs, is_required="false",
name_format=NAME_FORMAT_URI):
| lista = []
for attr in attributes:
attr = from_local_name(acs, attr, name_format)
args = {}
if isinstance(attr, six.string_types):
args["name"] = attr
else:
for key in attr.keyswv():
args[key] = getattr(attr, key)
args["is_required"... | key_info=ds.KeyInfo(
x509_data=ds.X509Data(
x509_certificate=ds.X509Certificate(text=cert)
)
)
)
return kd_list
def do_requested_attribute(attributes, acs, is_required="false",
name_format=NAME_FORMAT_URI)... | 64 | 64 | 123 | 22 | 41 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_requested_attribute | do_requested_attribute | 239 | 253 | 239 | 240 | 4188a100990e6af6e8f59f8edbbd39773e8851a2 | bigcode/the-stack | train |
8c2f773c1f709af4218f0006 | train | function | def _do_nameid_format(cls, conf, typ):
namef = conf.getattr("name_id_format", typ)
if namef:
if isinstance(namef, six.string_types):
ids = [md.NameIDFormat(namef)]
else:
ids = [md.NameIDFormat(text=form) for form in namef]
setattr(cls, "name_id_format", ids)
| def _do_nameid_format(cls, conf, typ):
| namef = conf.getattr("name_id_format", typ)
if namef:
if isinstance(namef, six.string_types):
ids = [md.NameIDFormat(namef)]
else:
ids = [md.NameIDFormat(text=form) for form in namef]
setattr(cls, "name_id_format", ids)
| except ImportError:
return None
else:
res = []
for _cname, ava in item.items():
cls = getattr(_mod, _cname)
res.append(rec_factory(cls, **ava))
return res
def _do_nameid_format(cls, conf, typ):
| 64 | 64 | 83 | 12 | 51 | hospiq/pysaml2 | src/saml2/metadata.py | Python | _do_nameid_format | _do_nameid_format | 410 | 417 | 410 | 410 | f52db9738c7caaaa6a050cfc60dcbc84f7e7b784 | bigcode/the-stack | train |
b59e5e1e56af0f56bd59369f | train | function | def do_endpoints(conf, endpoints):
service = {}
for endpoint, (eclass, indexed) in endpoints.items():
try:
servs = []
i = 1
for args in conf[endpoint]:
if isinstance(args,
six.string_types): # Assume it's the location
... | def do_endpoints(conf, endpoints):
| service = {}
for endpoint, (eclass, indexed) in endpoints.items():
try:
servs = []
i = 1
for args in conf[endpoint]:
if isinstance(args,
six.string_types): # Assume it's the location
args = {"location... | typ):
namef = conf.getattr("name_id_format", typ)
if namef:
if isinstance(namef, six.string_types):
ids = [md.NameIDFormat(namef)]
else:
ids = [md.NameIDFormat(text=form) for form in namef]
setattr(cls, "name_id_format", ids)
def do_endpoints(conf, endpoints):
| 81 | 81 | 270 | 8 | 73 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_endpoints | do_endpoints | 420 | 455 | 420 | 420 | df7c57cb6d1cbc86e84df83b2a1aac322b10c041 | bigcode/the-stack | train |
3f6167028ff7c3eb7e7c5dc9 | train | function | def do_organization_info(ava):
"""
Description of an organization in the configuration is
a dictionary of keys and values, where the values might be tuples::
"organization": {
"name": ("AB Exempel", "se"),
"display_name": ("AB Exempel", "se"),
"url": "http://www.... | def do_organization_info(ava):
| """
Description of an organization in the configuration is
a dictionary of keys and values, where the values might be tuples::
"organization": {
"name": ("AB Exempel", "se"),
"display_name": ("AB Exempel", "se"),
"url": "http://www.example.org"
}
"""... | (val, klass):
"""If no language is defined 'en' is the default"""
try:
(text, lang) = val
return klass(text=text, lang=lang)
except ValueError:
return klass(text=val, lang="en")
def do_organization_info(ava):
| 64 | 64 | 215 | 8 | 56 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_organization_info | do_organization_info | 125 | 152 | 125 | 125 | 9e094715027da9de2c33af6d8c913de7f156ff18 | bigcode/the-stack | train |
958c1c860d4f13dbd7b7b167 | train | function | def do_idpsso_descriptor(conf, cert=None, enc_cert=None):
idpsso = md.IDPSSODescriptor()
idpsso.protocol_support_enumeration = samlp.NAMESPACE
endps = conf.getattr("endpoints", "idp")
if endps:
for (endpoint, instlist) in do_endpoints(endps,
ENDP... | def do_idpsso_descriptor(conf, cert=None, enc_cert=None):
| idpsso = md.IDPSSODescriptor()
idpsso.protocol_support_enumeration = samlp.NAMESPACE
endps = conf.getattr("endpoints", "idp")
if endps:
for (endpoint, instlist) in do_endpoints(endps,
ENDPOINTS["idp"]).items():
setattr(idpsso, endpoin... | if val is None:
setattr(spsso, key, DEFAULT[key]) # default ?!
else:
strval = "{0:>s}".format(str(val))
setattr(spsso, key, strval.lower())
except KeyError:
setattr(spsso, key, DEFAULTS[key])
do_attribute_consuming_service(conf, spss... | 115 | 115 | 384 | 15 | 99 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_idpsso_descriptor | do_idpsso_descriptor | 580 | 624 | 580 | 580 | 1f5518d75e522224a3b1197e60c7c83d18cc8d8d | bigcode/the-stack | train |
20c3ea4e2951eebcac488856 | train | function | def do_aq_descriptor(conf, cert=None, enc_cert=None):
aqs = md.AuthnAuthorityDescriptor()
aqs.protocol_support_enumeration = samlp.NAMESPACE
endps = conf.getattr("endpoints", "aq")
if endps:
for (endpoint, instlist) in do_endpoints(endps,
ENDPOI... | def do_aq_descriptor(conf, cert=None, enc_cert=None):
| aqs = md.AuthnAuthorityDescriptor()
aqs.protocol_support_enumeration = samlp.NAMESPACE
endps = conf.getattr("endpoints", "aq")
if endps:
for (endpoint, instlist) in do_endpoints(endps,
ENDPOINTS["aq"]).items():
setattr(aqs, endpoint,... | aad.attribute.append(Attribute(text=attribute))
attribute_profiles = conf.getattr("attribute_profile", "aa")
if attribute_profiles:
for attribute_profile in attribute_profiles:
aad.attribute.append(AttributeProfile(text=attribute_profile))
return aad
def do_aq_descriptor(conf, cert=No... | 64 | 64 | 139 | 14 | 49 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_aq_descriptor | do_aq_descriptor | 657 | 674 | 657 | 657 | be9623a8a73b5c93e1ebe6e10fee409bcf085787 | bigcode/the-stack | train |
9f66dbe523bba41423de8756 | train | function | def entity_descriptor(confd):
mycert = None
enc_cert = None
if confd.cert_file is not None:
mycert = []
mycert.append("".join(open(confd.cert_file).readlines()[1:-1]))
if confd.additional_cert_files is not None:
for _cert_file in confd.additional_cert_files:
... | def entity_descriptor(confd):
| mycert = None
enc_cert = None
if confd.cert_file is not None:
mycert = []
mycert.append("".join(open(confd.cert_file).readlines()[1:-1]))
if confd.additional_cert_files is not None:
for _cert_file in confd.additional_cert_files:
mycert.append("".join(open(... | )
_do_nameid_format(aqs, conf, "aq")
if cert or enc_cert:
aqs.key_descriptor = do_key_descriptor(cert, enc_cert,
use=conf.metadata_key_usage)
return aqs
def do_pdp_descriptor(conf, cert=None, enc_cert=None):
""" Create a Policy Decision Point d... | 202 | 202 | 676 | 6 | 195 | hospiq/pysaml2 | src/saml2/metadata.py | Python | entity_descriptor | entity_descriptor | 699 | 770 | 699 | 699 | b0ed7c76da321fcef7b259f17f95ce1039bc8e3c | bigcode/the-stack | train |
da3d0ca2fead73db96920bd3 | train | function | def do_attribute_consuming_service(conf, spsso):
service_description = service_name = None
requested_attributes = []
acs = conf.attribute_converters
req = conf.getattr("required_attributes", "sp")
req_attr_name_format = conf.getattr("requested_attribute_name_format", "sp")
if req_attr_name_form... | def do_attribute_consuming_service(conf, spsso):
| service_description = service_name = None
requested_attributes = []
acs = conf.attribute_converters
req = conf.getattr("required_attributes", "sp")
req_attr_name_format = conf.getattr("requested_attribute_name_format", "sp")
if req_attr_name_format is None:
req_attr_name_format = conf.r... | raise
else:
args["index"] = str(args["index"])
servs.append(factory(eclass, **args))
service[endpoint] = servs
except KeyError:
pass
return service
DEFAULT = {
"want_assertions_... | 111 | 111 | 371 | 12 | 99 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_attribute_consuming_service | do_attribute_consuming_service | 466 | 521 | 466 | 466 | 8e909e6e2ca4808c69c2ac583b95a353f613b62c | bigcode/the-stack | train |
e24e5514fb8e09cd391d79c0 | train | function | def do_pdp_descriptor(conf, cert=None, enc_cert=None):
""" Create a Policy Decision Point descriptor """
pdp = md.PDPDescriptor()
pdp.protocol_support_enumeration = samlp.NAMESPACE
endps = conf.getattr("endpoints", "pdp")
if endps:
for (endpoint, instlist) in do_endpoints(endps,
... | def do_pdp_descriptor(conf, cert=None, enc_cert=None):
| """ Create a Policy Decision Point descriptor """
pdp = md.PDPDescriptor()
pdp.protocol_support_enumeration = samlp.NAMESPACE
endps = conf.getattr("endpoints", "pdp")
if endps:
for (endpoint, instlist) in do_endpoints(endps,
ENDPOINTS["pdp"... | list)
_do_nameid_format(aqs, conf, "aq")
if cert or enc_cert:
aqs.key_descriptor = do_key_descriptor(cert, enc_cert,
use=conf.metadata_key_usage)
return aqs
def do_pdp_descriptor(conf, cert=None, enc_cert=None):
| 64 | 64 | 147 | 14 | 49 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_pdp_descriptor | do_pdp_descriptor | 677 | 696 | 677 | 677 | c1f719d93db51d54e6bc99e5f3784975036b5e97 | bigcode/the-stack | train |
3219709633df2cd416b4b61a | train | function | def sign_entity_descriptor(edesc, ident, secc, sign_alg=None, digest_alg=None):
"""
:param edesc: EntityDescriptor instance
:param ident: EntityDescriptor identifier
:param secc: Security context
:return: Tuple with EntityDescriptor instance and Signed XML document
"""
if not ident:
... | def sign_entity_descriptor(edesc, ident, secc, sign_alg=None, digest_alg=None):
| """
:param edesc: EntityDescriptor instance
:param ident: EntityDescriptor identifier
:param secc: Security context
:return: Tuple with EntityDescriptor instance and Signed XML document
"""
if not ident:
ident = sid()
edesc.signature = pre_signature_part(ident, secc.my_cert, 1... | .sign_statement("%s" % entities, class_name(entities))
entities = md.entities_descriptor_from_string(xmldoc)
else:
xmldoc = None
return entities, xmldoc
def sign_entity_descriptor(edesc, ident, secc, sign_alg=None, digest_alg=None):
| 64 | 64 | 158 | 20 | 43 | hospiq/pysaml2 | src/saml2/metadata.py | Python | sign_entity_descriptor | sign_entity_descriptor | 807 | 823 | 807 | 807 | 14219023a31132a6a4c0835d1d0bfb8a53e6c4f9 | bigcode/the-stack | train |
97911b3ef34e5cd4ef946b5c | train | function | def do_contact_person_info(lava):
""" Creates a ContactPerson instance from configuration information"""
cps = []
if lava is None:
return cps
contact_person = md.ContactPerson
for ava in lava:
cper = md.ContactPerson()
for (key, classpec) in contact_person.c_children.values... | def do_contact_person_info(lava):
| """ Creates a ContactPerson instance from configuration information"""
cps = []
if lava is None:
return cps
contact_person = md.ContactPerson
for ava in lava:
cper = md.ContactPerson()
for (key, classpec) in contact_person.c_children.values():
try:
... | , [_localized_name(ava[ckey], klass)])
elif isinstance(ava[ckey], list):
setattr(org, dkey,
[_localized_name(n, klass) for n in ava[ckey]])
else:
setattr(org, dkey, [_localized_name(ava[ckey], klass)])
return org
def do_contact_person_info(lava):
| 79 | 79 | 265 | 8 | 70 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_contact_person_info | do_contact_person_info | 155 | 195 | 155 | 155 | 63fd912e1577c10947cc5081ce8b9858b4daec96 | bigcode/the-stack | train |
09c8de716424e86955bc8730 | train | function | def do_spsso_descriptor(conf, cert=None, enc_cert=None):
spsso = md.SPSSODescriptor()
spsso.protocol_support_enumeration = samlp.NAMESPACE
exts = conf.getattr("extensions", "sp")
if exts:
if spsso.extensions is None:
spsso.extensions = md.Extensions()
for key, val in exts.i... | def do_spsso_descriptor(conf, cert=None, enc_cert=None):
| spsso = md.SPSSODescriptor()
spsso.protocol_support_enumeration = samlp.NAMESPACE
exts = conf.getattr("extensions", "sp")
if exts:
if spsso.extensions is None:
spsso.extensions = md.Extensions()
for key, val in exts.items():
_ext = do_extensions(key, val)
... | .name
lang = "en"
service_name = [md.ServiceName(text=text, lang=lang)]
except KeyError:
pass
# Must be both requested attributes and service name
if requested_attributes:
if not service_name:
service_name = [md.ServiceName(text="", lang="en")]
... | 138 | 138 | 461 | 15 | 123 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_spsso_descriptor | do_spsso_descriptor | 524 | 577 | 524 | 524 | befb2c19782d3b945cac12499b8d0cf8d82ee974 | bigcode/the-stack | train |
9d572d527427e6064330c79d | train | function | def do_idpdisc(discovery_response):
return idpdisc.DiscoveryResponse(index="0", location=discovery_response,
binding=idpdisc.NAMESPACE)
| def do_idpdisc(discovery_response):
| return idpdisc.DiscoveryResponse(index="0", location=discovery_response,
binding=idpdisc.NAMESPACE)
| "])
try:
keyw.lang = val["lang"]
except KeyError:
pass
inst.append(keyw)
else:
raise SAMLError("Configuration Error: ui_info keywords")
except KeyError:
pass
return uii
def do_idpdisc(discovery_response):
| 64 | 64 | 35 | 9 | 54 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_idpdisc | do_idpdisc | 344 | 346 | 344 | 344 | 7b3c42992ba625e303ac9f500836789306482f14 | bigcode/the-stack | train |
6ee71eea2fd0ac2145e712d2 | train | function | def create_metadata_string(configfile, config=None, valid=None, cert=None,
keyfile=None, mid=None, name=None, sign=None):
valid_for = 0
nspair = {"xs": "http://www.w3.org/2001/XMLSchema"}
# paths = [".", "/opt/local/bin"]
if valid:
valid_for = int(valid) # Hours
... | def create_metadata_string(configfile, config=None, valid=None, cert=None,
keyfile=None, mid=None, name=None, sign=None):
| valid_for = 0
nspair = {"xs": "http://www.w3.org/2001/XMLSchema"}
# paths = [".", "/opt/local/bin"]
if valid:
valid_for = int(valid) # Hours
eds = []
if config is None:
if configfile.endswith(".py"):
configfile = configfile[:-3]
config = Config().load_file(... | NS + XMLNSXS)
else:
if b"\"xs:string\"" in xmlstring and bXMLNSXS not in xmlstring:
xmlstring = xmlstring.replace(bMDNS, bMDNS + bXMLNSXS)
return xmlstring
def create_metadata_string(configfile, config=None, valid=None, cert=None,
keyfile=None, mid=None, name=None... | 85 | 85 | 284 | 30 | 54 | hospiq/pysaml2 | src/saml2/metadata.py | Python | create_metadata_string | create_metadata_string | 79 | 113 | 79 | 80 | cc55fe7c6c32de5ef06a44a701792a77438b0305 | bigcode/the-stack | train |
d7cf1a3fb60cfc163b96f7dd | train | function | def _localized_name(val, klass):
"""If no language is defined 'en' is the default"""
try:
(text, lang) = val
return klass(text=text, lang=lang)
except ValueError:
return klass(text=val, lang="en")
| def _localized_name(val, klass):
| """If no language is defined 'en' is the default"""
try:
(text, lang) = val
return klass(text=text, lang=lang)
except ValueError:
return klass(text=val, lang="en")
| ]
if sign:
eid, xmldoc = sign_entity_descriptor(eid, mid, secc)
else:
xmldoc = None
valid_instance(eid)
return metadata_tostring_fix(eid, nspair, xmldoc)
def _localized_name(val, klass):
| 64 | 64 | 60 | 8 | 56 | hospiq/pysaml2 | src/saml2/metadata.py | Python | _localized_name | _localized_name | 116 | 122 | 116 | 116 | b52c90d32b555e88078e08ddb3429fa3ef836535 | bigcode/the-stack | train |
305bd1ada592ba63f6d076d5 | train | function | def do_extensions(mname, item):
try:
_mod = __import__("saml2.extension.%s" % mname, globals(), locals(),
mname)
except ImportError:
return None
else:
res = []
for _cname, ava in item.items():
cls = getattr(_mod, _cname)
res.... | def do_extensions(mname, item):
| try:
_mod = __import__("saml2.extension.%s" % mname, globals(), locals(),
mname)
except ImportError:
return None
else:
res = []
for _cname, ava in item.items():
cls = getattr(_mod, _cname)
res.append(rec_factory(cls, **ava))
... | BINDING_HTTP_REDIRECT,
"single_logout_service": BINDING_HTTP_POST,
"attribute_service": BINDING_SOAP,
"artifact_resolution_service": BINDING_SOAP,
"authn_query_service": BINDING_SOAP
}
def do_extensions(mname, item):
| 64 | 64 | 89 | 8 | 56 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_extensions | do_extensions | 395 | 407 | 395 | 395 | 84ab50127096974daa49e533a7168e54b9166360 | bigcode/the-stack | train |
e3641e20afe7f55e4d4af7a3 | train | function | def do_key_descriptor(cert=None, enc_cert=None, use="both"):
kd_list = []
if use in ["signing", "both"] and cert is not None:
if not isinstance(cert, list):
cert = [cert]
for _cert in cert:
kd_list.append(
md.KeyDescriptor(
key_info=ds.... | def do_key_descriptor(cert=None, enc_cert=None, use="both"):
| kd_list = []
if use in ["signing", "both"] and cert is not None:
if not isinstance(cert, list):
cert = [cert]
for _cert in cert:
kd_list.append(
md.KeyDescriptor(
key_info=ds.KeyInfo(
x509_data=ds.X509Data(
... | valid value
setattr(cper, prop, ava[prop])
except KeyError:
pass
# ContactType must have a value
typ = getattr(cper, "contact_type")
if not typ:
setattr(cper, "contact_type", "technical")
cps.append(cper)
return cps
def do_k... | 83 | 83 | 277 | 15 | 67 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_key_descriptor | do_key_descriptor | 198 | 236 | 198 | 198 | 8dcf64decf0caedcc84a2cd76ac0585908a8fb82 | bigcode/the-stack | train |
e9528969921f07ac8bf64fc5 | train | function | def do_uiinfo(_uiinfo):
uii = mdui.UIInfo()
for attr in ['display_name', 'description', "information_url",
'privacy_statement_url']:
try:
val = _uiinfo[attr]
except KeyError:
continue
aclass = uii.child_class(attr)
inst = getattr(uii, att... | def do_uiinfo(_uiinfo):
| uii = mdui.UIInfo()
for attr in ['display_name', 'description', "information_url",
'privacy_statement_url']:
try:
val = _uiinfo[attr]
except KeyError:
continue
aclass = uii.child_class(attr)
inst = getattr(uii, attr)
if isinstance... | None:
return md.KeyDescriptor(
key_info=ds.KeyInfo(
x509_data=ds.X509Data(
x509_certificate=ds.X509Certificate(text=cert)
)
)
)
return kd_list
def do_requested_attribute(attributes, acs, is_required="false",
... | 181 | 181 | 605 | 8 | 172 | hospiq/pysaml2 | src/saml2/metadata.py | Python | do_uiinfo | do_uiinfo | 256 | 341 | 256 | 256 | 9f9157cd6b4248f5cb7c84ab6bbfec287ca2ae15 | bigcode/the-stack | train |
4bee15eb84e6612aeacbe10d | train | function | def binary_search(x, target, my_min=1, my_max=None):
if my_max is None:
my_max = len(x) - 1
while my_min <= my_max:
mid = (my_min + my_max)//2
midval = x[mid]
if midval < target:
my_min = my_mid + 1
elif midval > target:
my_max = mid - 1
else:
r... | def binary_search(x, target, my_min=1, my_max=None):
| if my_max is None:
my_max = len(x) - 1
while my_min <= my_max:
mid = (my_min + my_max)//2
midval = x[mid]
if midval < target:
my_min = my_mid + 1
elif midval > target:
my_max = mid - 1
else:
return mid
raise ValueError
| : Packt Publishing Ltd.
Author : Yuxing Yan
Date : 6/6/2017
email : yany@canisius.edu
paulyxy@hotmail.com
"""
def binary_search(x, target, my_min=1, my_max=None):
| 64 | 64 | 106 | 16 | 48 | John-ye666/Python-for-Finance-Second-Edition | Chapter10/c10_34_binary_search.py | Python | binary_search | binary_search | 12 | 24 | 12 | 12 | 0f9d891f601518c5d63a6871475d0a2f59151139 | bigcode/the-stack | train |
c6655445c32cec0b1dac3c09 | train | class | class Wallet(object):
def __init__(self, protocol='http', host='127.0.0.1', port=18083, path='/json_rpc'):
self.rpc = JSONRPC('{protocol}://{host}:{port}{path}'.format(protocol=protocol, host=host, port=port, path=path))
def make_uniform_destinations(self, address, transfer_amount, transfer_number_of_... | class Wallet(object):
| def __init__(self, protocol='http', host='127.0.0.1', port=18083, path='/json_rpc'):
self.rpc = JSONRPC('{protocol}://{host}:{port}{path}'.format(protocol=protocol, host=host, port=port, path=path))
def make_uniform_destinations(self, address, transfer_amount, transfer_number_of_destinations=1):
... | # used to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FIT... | 201 | 201 | 671 | 4 | 196 | enrocoin/enro | tests/functional_tests/test_framework/wallet.py | Python | Wallet | Wallet | 33 | 120 | 33 | 34 | adcd0c1842ff2e8b333678ee430517a81fa547c8 | bigcode/the-stack | train |
4473b35f7637a35f335101a2 | train | class | class BukberConfig(AppConfig):
name = 'bukber'
| class BukberConfig(AppConfig):
| name = 'bukber'
| from django.apps import AppConfig
class BukberConfig(AppConfig):
| 14 | 64 | 14 | 7 | 6 | ppabcd/django-bukber | bukber/apps.py | Python | BukberConfig | BukberConfig | 4 | 5 | 4 | 4 | 969747dd391b0f863b684c99684670a9e2c8205f | bigcode/the-stack | train |
d92ec23371df4953322c1379 | train | function | def main():
binary = False
if sys.argv[1:] == ["--binary"]:
binary = True
print_header()
interact(list(collect_servers()), binary=binary)
| def main():
| binary = False
if sys.argv[1:] == ["--binary"]:
binary = True
print_header()
interact(list(collect_servers()), binary=binary)
| `\n"
def interact(servers, banner=banner, binary=False):
mc = pylibmc.Client(servers, binary=binary)
local = {"pylibmc": pylibmc,
"mc": mc}
code.interact(banner=banner, local=local)
def main():
| 64 | 64 | 40 | 3 | 61 | cogzidel/healthchecks | hc-venv/lib/python3.6/site-packages/pylibmc/__main__.py | Python | main | main | 42 | 47 | 42 | 42 | cbaee3766df2c4c18cd7dafc0976daaa7e286cf1 | bigcode/the-stack | train |
2e851059deb907dced742896 | train | function | def print_header(outf=sys.stdout):
outf.write("pylibmc interactive shell\n\n")
outf.write("Input list of servers, terminating by a blank line.\n")
outf.write(random.choice(tips) + "\n")
| def print_header(outf=sys.stdout):
| outf.write("pylibmc interactive shell\n\n")
outf.write("Input list of servers, terminating by a blank line.\n")
outf.write(random.choice(tips) + "\n")
| 1? Just hit Enter immediately.",
"Hit Enter immediately and you'll connect to 127.0.0.1.",
"Did you know there's a --binary flag? Try it!",
"Want to use binary mode? Pass --binary as a sole argument."
]
def print_header(outf=sys.stdout):
| 64 | 64 | 50 | 8 | 56 | cogzidel/healthchecks | hc-venv/lib/python3.6/site-packages/pylibmc/__main__.py | Python | print_header | print_header | 15 | 18 | 15 | 15 | d70e1ae8c2b72c5c0eb9ba67dc96596c2358b18f | bigcode/the-stack | train |
cdbdb7fd16e92f37bb331cdc | train | function | def interact(servers, banner=banner, binary=False):
mc = pylibmc.Client(servers, binary=binary)
local = {"pylibmc": pylibmc,
"mc": mc}
code.interact(banner=banner, local=local)
| def interact(servers, banner=banner, binary=False):
| mc = pylibmc.Client(servers, binary=binary)
local = {"pylibmc": pylibmc,
"mc": mc}
code.interact(banner=banner, local=local)
| _input("Address [<stop>]: ")
except:
in_addr = input("Address [<stop>]: ")
else:
yield "127.0.0.1"
banner = "\nmc client available as `mc`\n"
def interact(servers, banner=banner, binary=False):
| 64 | 64 | 58 | 12 | 52 | cogzidel/healthchecks | hc-venv/lib/python3.6/site-packages/pylibmc/__main__.py | Python | interact | interact | 36 | 40 | 36 | 36 | 4d065309bf1c4b573dd468a77b9a134f5a7b699e | bigcode/the-stack | train |
8939709f0428c0e14ca0b85f | train | function | def collect_servers():
try:
in_addr = raw_input("Address [127.0.0.1]: ")
except:
in_addr = input("Address [127.0.0.1]: ")
if in_addr:
while in_addr:
yield in_addr
try:
in_addr = raw_input("Address [<stop>]: ")
except:
... | def collect_servers():
| try:
in_addr = raw_input("Address [127.0.0.1]: ")
except:
in_addr = input("Address [127.0.0.1]: ")
if in_addr:
while in_addr:
yield in_addr
try:
in_addr = raw_input("Address [<stop>]: ")
except:
in_addr = input("Addr... | ? Pass --binary as a sole argument."
]
def print_header(outf=sys.stdout):
outf.write("pylibmc interactive shell\n\n")
outf.write("Input list of servers, terminating by a blank line.\n")
outf.write(random.choice(tips) + "\n")
def collect_servers():
| 64 | 64 | 107 | 4 | 60 | cogzidel/healthchecks | hc-venv/lib/python3.6/site-packages/pylibmc/__main__.py | Python | collect_servers | collect_servers | 20 | 33 | 20 | 20 | 9f14c9de1abc9debdd5a3f478007fdf63a807213 | bigcode/the-stack | train |
e5152f79e3b37e8e0febcdef | train | function | def create_log_group_arn(logs_client, hosted_zone_test_name):
"""Return ARN of a newly created CloudWatch log group."""
log_group_name = f"/aws/route53/{hosted_zone_test_name}"
response = logs_client.create_log_group(logGroupName=log_group_name)
assert response["ResponseMetadata"]["HTTPStatusCode"] == 2... | def create_log_group_arn(logs_client, hosted_zone_test_name):
| """Return ARN of a newly created CloudWatch log group."""
log_group_name = f"/aws/route53/{hosted_zone_test_name}"
response = logs_client.create_log_group(logGroupName=log_group_name)
assert response["ResponseMetadata"]["HTTPStatusCode"] == 200
log_group_arn = None
response = logs_client.descri... | _random_hex(6)}",
)
assert response["ResponseMetadata"]["HTTPStatusCode"] == 201
assert "HostedZone" in response and response["HostedZone"]["Id"]
return response["HostedZone"]["Id"]
def create_log_group_arn(logs_client, hosted_zone_test_name):
| 63 | 64 | 136 | 15 | 48 | gtourkas/moto | tests/test_route53/test_route53_query_logging_config.py | Python | create_log_group_arn | create_log_group_arn | 27 | 39 | 27 | 27 | 504ded73de9b016d1cd70912460e55a392a468e4 | bigcode/the-stack | train |
21719c56c100288ba448b03c | train | function | @mock_logs
@mock_route53
def test_get_query_logging_config():
"""Test valid and invalid get_query_logging_config requests."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
# Create a query logging config that can then be retrieved.... | @mock_logs
@mock_route53
def test_get_query_logging_config():
| """Test valid and invalid get_query_logging_config requests."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
# Create a query logging config that can then be retrieved.
hosted_zone_test_name = f"route53_query_log_{get_random_h... | a non-existent query logging config, i.e., the
# one that was just deleted.
with pytest.raises(ClientError) as exc:
client.delete_query_logging_config(Id=query_id)
err = exc.value.response["Error"]
assert err["Code"] == "NoSuchQueryLoggingConfig"
assert "The query logging configuration does... | 95 | 96 | 321 | 16 | 79 | gtourkas/moto | tests/test_route53/test_route53_query_logging_config.py | Python | test_get_query_logging_config | test_get_query_logging_config | 167 | 196 | 167 | 169 | 2a5f9a88ce3bc3fa2a8ae970983bed1a274b36ae | bigcode/the-stack | train |
ef410e7168936a20b0b90f0e | train | function | @mock_logs
@mock_route53
def test_delete_query_logging_config():
"""Test valid and invalid delete_query_logging_config requests."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
# Create a query logging config that can then be dele... | @mock_logs
@mock_route53
def test_delete_query_logging_config():
| """Test valid and invalid delete_query_logging_config requests."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
# Create a query logging config that can then be deleted.
hosted_zone_test_name = f"route53_query_log_{get_random_... | ZoneId"] == hosted_zone_id.split("/")[-1]
assert config["CloudWatchLogsLogGroupArn"] == log_group_arn
assert config["Id"]
location = response["Location"]
assert (
location
== f"https://route53.amazonaws.com/2013-04-01/queryloggingconfig/{config['Id']}"
)
@mock_logs
@mock_route53
def... | 91 | 91 | 306 | 16 | 75 | gtourkas/moto | tests/test_route53/test_route53_query_logging_config.py | Python | test_delete_query_logging_config | test_delete_query_logging_config | 136 | 164 | 136 | 138 | 4f5373206434c44def0cfacdd044965da23cc69d | bigcode/the-stack | train |
38482abfb9594b08e011c8b9 | train | function | @mock_logs
@mock_route53
def test_list_query_logging_configs_bad_args():
"""Test bad arguments to list_query_logging_configs()."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
# Check exception: NoSuchHostedZone
with pytest.r... | @mock_logs
@mock_route53
def test_list_query_logging_configs_bad_args():
| """Test bad arguments to list_query_logging_configs()."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
# Check exception: NoSuchHostedZone
with pytest.raises(ClientError) as exc:
client.list_query_logging_configs(Host... | "] == log_group_arn
assert config["Id"]
# Test the retrieval of a non-existent query logging config.
with pytest.raises(ClientError) as exc:
client.get_query_logging_config(Id="1234567890")
err = exc.value.response["Error"]
assert err["Code"] == "NoSuchQueryLoggingConfig"
assert "The qu... | 106 | 107 | 358 | 18 | 88 | gtourkas/moto | tests/test_route53/test_route53_query_logging_config.py | Python | test_list_query_logging_configs_bad_args | test_list_query_logging_configs_bad_args | 199 | 231 | 199 | 201 | 7934479ecfa5b122ded9753e63c4992b4bfcb5c9 | bigcode/the-stack | train |
cf4b81597011a4a36502415d | train | function | def create_hosted_zone_id(route53_client, hosted_zone_test_name):
"""Return ID of a newly created Route53 public hosted zone"""
response = route53_client.create_hosted_zone(
Name=hosted_zone_test_name,
CallerReference=f"test_caller_ref_{get_random_hex(6)}",
)
assert response["ResponseMet... | def create_hosted_zone_id(route53_client, hosted_zone_test_name):
| """Return ID of a newly created Route53 public hosted zone"""
response = route53_client.create_hosted_zone(
Name=hosted_zone_test_name,
CallerReference=f"test_caller_ref_{get_random_hex(6)}",
)
assert response["ResponseMetadata"]["HTTPStatusCode"] == 201
assert "HostedZone" in respon... | mock_logs
from moto import mock_route53
from moto.core import ACCOUNT_ID
from moto.core.utils import get_random_hex
# The log group must be in the us-east-1 region.
TEST_REGION = "us-east-1"
def create_hosted_zone_id(route53_client, hosted_zone_test_name):
| 64 | 64 | 108 | 15 | 49 | gtourkas/moto | tests/test_route53/test_route53_query_logging_config.py | Python | create_hosted_zone_id | create_hosted_zone_id | 16 | 24 | 16 | 16 | 1999fe3e3b5f748774159c69304af14897d2d29f | bigcode/the-stack | train |
e32c80a633d6b532e29be135 | train | function | @mock_logs
@mock_route53
def test_create_query_logging_config_bad_args():
"""Test bad arguments to create_query_logging_config()."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
hosted_zone_test_name = f"route53_query_log_{get_ran... | @mock_logs
@mock_route53
def test_create_query_logging_config_bad_args():
| """Test bad arguments to create_query_logging_config()."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
hosted_zone_test_name = f"route53_query_log_{get_random_hex(6)}.test"
hosted_zone_id = create_hosted_zone_id(client, hoste... | (6)}",
)
assert response["ResponseMetadata"]["HTTPStatusCode"] == 201
assert "HostedZone" in response and response["HostedZone"]["Id"]
return response["HostedZone"]["Id"]
def create_log_group_arn(logs_client, hosted_zone_test_name):
"""Return ARN of a newly created CloudWatch log group."""
log... | 201 | 201 | 673 | 18 | 182 | gtourkas/moto | tests/test_route53/test_route53_query_logging_config.py | Python | test_create_query_logging_config_bad_args | test_create_query_logging_config_bad_args | 42 | 107 | 42 | 44 | 89aac611bfd5131b0e50c373cf6cb5edd89857a6 | bigcode/the-stack | train |
a9c2dbc94ef627054ed3bddf | train | function | @mock_logs
@mock_route53
def test_list_query_logging_configs_good_args():
"""Test valid arguments to list_query_logging_configs()."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
# Test when there are no query logging configs.
... | @mock_logs
@mock_route53
def test_list_query_logging_configs_good_args():
| """Test valid arguments to list_query_logging_configs()."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
# Test when there are no query logging configs.
response = client.list_query_logging_configs()
query_logging_configs ... | arn,
)
# Retrieve a query logging config, then request more with an invalid token.
client.list_query_logging_configs(MaxResults="1")
with pytest.raises(ClientError) as exc:
client.list_query_logging_configs(NextToken="foo")
err = exc.value.response["Error"]
assert err["Code"] == "In... | 129 | 129 | 432 | 18 | 111 | gtourkas/moto | tests/test_route53/test_route53_query_logging_config.py | Python | test_list_query_logging_configs_good_args | test_list_query_logging_configs_good_args | 234 | 277 | 234 | 236 | d44b61cfde65e9e961855b4eb80a7fb4601dad82 | bigcode/the-stack | train |
345a95e9011d6f410832a39a | train | function | @mock_logs
@mock_route53
def test_create_query_logging_config_good_args():
"""Test a valid create_logging_config() request."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
hosted_zone_test_name = f"route53_query_log_{get_random_he... | @mock_logs
@mock_route53
def test_create_query_logging_config_good_args():
| """Test a valid create_logging_config() request."""
client = boto3.client("route53", region_name=TEST_REGION)
logs_client = boto3.client("logs", region_name=TEST_REGION)
hosted_zone_test_name = f"route53_query_log_{get_random_hex(6)}.test"
hosted_zone_id = create_hosted_zone_id(client, hosted_zone_... | log_group_arn,
)
err = exc.value.response["Error"]
assert err["Code"] == "QueryLoggingConfigAlreadyExists"
assert (
"A query logging configuration already exists for this hosted zone"
in err["Message"]
)
@mock_logs
@mock_route53
def test_create_query_logging_config_good_args():
| 72 | 72 | 242 | 18 | 54 | gtourkas/moto | tests/test_route53/test_route53_query_logging_config.py | Python | test_create_query_logging_config_good_args | test_create_query_logging_config_good_args | 110 | 133 | 110 | 112 | b6822b297c2309641c92196212e164a372034975 | bigcode/the-stack | train |
f7fd2a85bb7190d5051f0b96 | train | class | class pyAlgoBollinger(strategy.BacktestingStrategy):
def __init__(self, feed, instrument, bBandsPeriod):
strategy.BacktestingStrategy.__init__(self, feed)
self.setDebugMode(False)
self.__instrument = instrument
self.__feed = feed
self.__position = None
self.__bbands ... | class pyAlgoBollinger(strategy.BacktestingStrategy):
| def __init__(self, feed, instrument, bBandsPeriod):
strategy.BacktestingStrategy.__init__(self, feed)
self.setDebugMode(False)
self.__instrument = instrument
self.__feed = feed
self.__position = None
self.__bbands = bollinger.BollingerBands(feed[instrument].getCloseD... | #!/usr/bin/python2
# -*- coding: utf-8 -*-
# home
#
#
# vim:fileencoding=utf-8:sw=4:et -*- coding: utf-8 -*-
#
# 测试 pyalgotrade 回测
#
import _index
from energy.libs.MongoStock import Feed
from energy.libs.eAlgoLib import eAlgoLib as eal
from pyalgotrade import strategy
from pyalgotrade import bar
from pyalgotrade.tec... | 127 | 165 | 552 | 11 | 115 | vyouzhis/energy | epyalgo/pyAlgoBollinger.py | Python | pyAlgoBollinger | pyAlgoBollinger | 21 | 81 | 21 | 21 | 0cf06de45010aed7308ccd337b318ed7cac6e959 | bigcode/the-stack | train |
5d8f8292f11123e92ded2eb1 | train | function | def main(i, code):
#code = "000592"
dbfeed = Feed(code, bar.Frequency.DAY, 1024)
dbfeed.loadBars()
myStrategy = pyAlgoBollinger(dbfeed, code, bBandsPeriod=i)
ms = eal()
ms.setDebug(True)
ms.protfolio(myStrategy)
| def main(i, code):
#code = "000592"
| dbfeed = Feed(code, bar.Frequency.DAY, 1024)
dbfeed.loadBars()
myStrategy = pyAlgoBollinger(dbfeed, code, bBandsPeriod=i)
ms = eal()
ms.setDebug(True)
ms.protfolio(myStrategy)
| Broker().getCash(False) / bar.getClose())
self.__position = self.enterLong(self.__instrument, sharesToBuy, False)
elif shares > 0 and bar.getClose() > upper:
self.__position.exitMarket()
def main(i, code):
#code = "000592"
| 64 | 64 | 75 | 14 | 50 | vyouzhis/energy | epyalgo/pyAlgoBollinger.py | Python | main | main | 84 | 92 | 84 | 85 | 2b659132c9d354ed377f8699fc11e4e59ee22da3 | bigcode/the-stack | train |
634707e7e36a1aaaa77774d0 | train | function | @pytest.fixture(name="model")
def make_model():
return af.ModelMapper(mock_class=MockClassx2)
| @pytest.fixture(name="model")
def make_model():
| return af.ModelMapper(mock_class=MockClassx2)
| autofit.mock.mock import MockClassx2
from autofit.non_linear.samples import Sample, StoredSamples
from autofit.text import samples_text
text_path = path.join("{}".format(path.dirname(path.realpath(__file__))), "files", "samples")
@pytest.fixture(name="model")
def make_model():
| 63 | 64 | 23 | 10 | 53 | jonathanfrawley/PyAutoFit | test_autofit/text/test_samples_text.py | Python | make_model | make_model | 13 | 15 | 13 | 14 | 6d2dc26bd11a388fefa5e3627d067679faf23a81 | bigcode/the-stack | train |
3e1a9345b7233f5143c8ba1d | train | function | @pytest.fixture(name="samples")
def make_samples(model):
parameters = [[1.0, 2.0], [1.2, 2.2]]
log_likelihood_list = [1.0, 0.0]
return StoredSamples(
model=model,
samples=Sample.from_lists(
parameter_lists=parameters,
log_likelihood_list=log_likelihood_lis... | @pytest.fixture(name="samples")
def make_samples(model):
| parameters = [[1.0, 2.0], [1.2, 2.2]]
log_likelihood_list = [1.0, 0.0]
return StoredSamples(
model=model,
samples=Sample.from_lists(
parameter_lists=parameters,
log_likelihood_list=log_likelihood_list,
log_prior_list=[0.0, 0.0],
wei... | it.text import samples_text
text_path = path.join("{}".format(path.dirname(path.realpath(__file__))), "files", "samples")
@pytest.fixture(name="model")
def make_model():
return af.ModelMapper(mock_class=MockClassx2)
@pytest.fixture(name="samples")
def make_samples(model):
| 64 | 64 | 115 | 11 | 53 | jonathanfrawley/PyAutoFit | test_autofit/text/test_samples_text.py | Python | make_samples | make_samples | 18 | 33 | 18 | 19 | ab1002ed98beac205ab4490b5cc19d9eab79ce09 | bigcode/the-stack | train |
6bd2eef7d17854388e1f71f5 | train | function | def test__summary(samples):
results_at_sigma = samples_text.summary(samples=samples, sigma=3.0)
assert "one 1.00 (1.00, 1.20)" in results_at_sigma
assert "two 2.00 (2.00, 2.20)" in results_at_sigma
| def test__summary(samples):
| results_at_sigma = samples_text.summary(samples=samples, sigma=3.0)
assert "one 1.00 (1.00, 1.20)" in results_at_sigma
assert "two 2.00 (2.00, 2.20)" in results_at_sigma
| =model,
samples=Sample.from_lists(
parameter_lists=parameters,
log_likelihood_list=log_likelihood_list,
log_prior_list=[0.0, 0.0],
weight_list=log_likelihood_list,
model=model
)
)
def test__summary(samples):
| 63 | 64 | 72 | 6 | 57 | jonathanfrawley/PyAutoFit | test_autofit/text/test_samples_text.py | Python | test__summary | test__summary | 36 | 40 | 36 | 36 | 6391294eb559ab5e2f0bd9a033ce06e35fee774f | bigcode/the-stack | train |
9fd7057c215c36e9ee575fb7 | train | function | def test__latex(samples):
latex_results_at_sigma = samples_text.latex(samples=samples, sigma=3.0)
assert r"one_label_{\mathrm{o}} = 1.00^{+0.20}_{-0.00} & " in latex_results_at_sigma
assert r"two_label_{\mathrm{t}} = 2.00^{+0.20}_{-0.00}" in latex_results_at_sigma
| def test__latex(samples):
| latex_results_at_sigma = samples_text.latex(samples=samples, sigma=3.0)
assert r"one_label_{\mathrm{o}} = 1.00^{+0.20}_{-0.00} & " in latex_results_at_sigma
assert r"two_label_{\mathrm{t}} = 2.00^{+0.20}_{-0.00}" in latex_results_at_sigma
| (samples=samples, sigma=3.0)
assert "one 1.00 (1.00, 1.20)" in results_at_sigma
assert "two 2.00 (2.00, 2.20)" in results_at_sigma
def test__latex(samples):
| 64 | 64 | 93 | 6 | 57 | jonathanfrawley/PyAutoFit | test_autofit/text/test_samples_text.py | Python | test__latex | test__latex | 43 | 47 | 43 | 43 | 4e4265bfd5f144ef12b1782872cf0a8c50c60cc6 | bigcode/the-stack | train |
d6a00fa233b8052b2e5a3a56 | train | class | class RandomResizedCrop(object):
"""Crop the given PIL Image to random size and aspect ratio.
A crop of random size (default: of 0.08 to 1.0) of the original size and a random
aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
is finally resized to given size.
Thi... | class RandomResizedCrop(object):
| """Crop the given PIL Image to random size and aspect ratio.
A crop of random size (default: of 0.08 to 1.0) of the original size and a random
aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
is finally resized to given size.
This is popularly used to train the ... | .5):
self.shift_value = shift_value
self.ratio = ratio
def __call__(self, img, labelmap=None, maskmap=None, kpts=None, bboxes=None, labels=None, polygons=None):
assert isinstance(img, np.ndarray)
assert labelmap is None or isinstance(labelmap, np.ndarray)
assert maskmap is N... | 199 | 199 | 665 | 7 | 191 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomResizedCrop | RandomResizedCrop | 358 | 425 | 358 | 358 | 122b089751446e560b887629979895c7eed637b0 | bigcode/the-stack | train |
48d7374dee397a9eea493afb | train | class | class RandomContrast(object):
def __init__(self, lower=0.5, upper=1.5, ratio=0.5):
self.lower = lower
self.upper = upper
self.ratio = ratio
assert self.upper >= self.lower, "contrast upper must be >= lower."
assert self.lower >= 0, "contrast lower must be non-negative."
... | class RandomContrast(object):
| def __init__(self, lower=0.5, upper=1.5, ratio=0.5):
self.lower = lower
self.upper = upper
self.ratio = ratio
assert self.upper >= self.lower, "contrast upper must be >= lower."
assert self.lower >= 0, "contrast lower must be non-negative."
def __call__(self, img, labelm... | map, kpts, bboxes, labels, polygons
swap = self.perms[random.randint(0, len(self.perms) - 1)]
img = img[:, :, swap].astype(np.uint8)
return img, labelmap, maskmap, kpts, bboxes, labels, polygons
class RandomContrast(object):
| 70 | 70 | 236 | 5 | 64 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomContrast | RandomContrast | 317 | 335 | 317 | 317 | 350779fcfcba8ca71426e0a2e2097919e182f68d | bigcode/the-stack | train |
1e9050a8c7abb76c9f0d705d | train | class | class RandomBorder(object):
""" Padding the Image to proper size.
Args:
stride: the stride of the network.
pad_value: the value that pad to the image border.
img: Image object as input.
Returns::
img: Image object.
"""
d... | class RandomBorder(object):
| """ Padding the Image to proper size.
Args:
stride: the stride of the network.
pad_value: the value that pad to the image border.
img: Image object as input.
Returns::
img: Image object.
"""
def __init__(self, pad=None, ... | = cv2.copyMakeBorder(labelmap, up_pad, pad_height - up_pad, left_pad, pad_width - left_pad,
cv2.BORDER_CONSTANT, value=255)
if maskmap is not None:
maskmap = cv2.copyMakeBorder(maskmap, up_pad, pad_height - up_pad, left_pad, pad_width - left_pad,
... | 256 | 256 | 1,494 | 5 | 250 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomBorder | RandomBorder | 88 | 194 | 88 | 88 | d399ebd50c4d2bc006e6c26d7ceaa7e84de17bf3 | bigcode/the-stack | train |
605c76fa36f966bb1996c99a | train | class | class RandomDetCrop(object):
"""Crop
Arguments:
img (Image): the image being input during training
boxes (Tensor): the original bounding boxes in pt form
labels (Tensor): the class labels for each bbox
mode (float tuple): the min and max jaccard overlaps
Return:
(img,... | class RandomDetCrop(object):
| """Crop
Arguments:
img (Image): the image being input during training
boxes (Tensor): the original bounding boxes in pt form
labels (Tensor): the class labels for each bbox
mode (float tuple): the min and max jaccard overlaps
Return:
(img, boxes, classes)
... | + height,
abs(min(offset_left, 0)):abs(min(offset_left, 0)) + width] = maskmap
maskmap = expand_maskmap[max(offset_up, 0):max(offset_up, 0) + self.size[1],
max(offset_left, 0):max(offset_left, 0) + self.size[0]]
if labelmap is not Non... | 256 | 256 | 1,370 | 6 | 249 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomDetCrop | RandomDetCrop | 889 | 1,007 | 889 | 889 | 61ab7b0775eb30395168b95dfa1498cc4d00ae0b | bigcode/the-stack | train |
e08a0498a915d9b68729c6e6 | train | class | class RandomRotate(object):
"""Rotate the input numpy.ndarray and points to the given degree.
Args:
degree (number): Desired rotate degree.
"""
def __init__(self, max_degree, ratio=0.5, mean=(104, 117, 123)):
assert isinstance(max_degree, int)
self.max_degree = max_degree
... | class RandomRotate(object):
| """Rotate the input numpy.ndarray and points to the given degree.
Args:
degree (number): Desired rotate degree.
"""
def __init__(self, max_degree, ratio=0.5, mean=(104, 117, 123)):
assert isinstance(max_degree, int)
self.max_degree = max_degree
self.ratio = ratio
... | :
bboxes[:, 0::2] *= w_scale_ratio
bboxes[:, 1::2] *= h_scale_ratio
if polygons is not None:
for object_id in range(len(polygons)):
for polygon_id in range(len(polygons[object_id])):
polygons[object_id][polygon_id][0::2] *= w_scale_ratio
... | 256 | 256 | 1,209 | 5 | 250 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomRotate | RandomRotate | 534 | 632 | 534 | 534 | 01775858ef7fd0ea40f0f6670cd4706115fd8689 | bigcode/the-stack | train |
e380365ac860b7cb14752c03 | train | class | class CV2AugCompose(object):
"""Composes several transforms together.
Args:
transforms (list of ``Transform`` objects): list of transforms to compose.
Example:
>>> CV2AugCompose([
>>> RandomCrop(),
>>> ])
"""
def __init__(self, configer, split='train'):
... | class CV2AugCompose(object):
| """Composes several transforms together.
Args:
transforms (list of ``Transform`` objects): list of transforms to compose.
Example:
>>> CV2AugCompose([
>>> RandomCrop(),
>>> ])
"""
def __init__(self, configer, split='train'):
self.configer = configer
... | maskmap, kpts, bboxes, labels, polygons
CV2_AUGMENTATIONS_DICT = {
'random_saturation': RandomSaturation,
'random_hue': RandomHue,
'random_perm': RandomPerm,
'random_contrast': RandomContrast,
'random_brightness': RandomBrightness,
'random_pad': RandomPad,
'random_border': RandomBorder,
... | 163 | 163 | 545 | 7 | 156 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | CV2AugCompose | CV2AugCompose | 1,092 | 1,149 | 1,092 | 1,092 | 9109c52be5de9c1122a6e48050287f96809d3d1f | bigcode/the-stack | train |
1fa8383e60a6ef219e44714d | train | class | class RandomCrop(object):
"""Crop the given numpy.ndarray and at a random location.
Args:
size (int or tuple): Desired output size of the crop.(w, h)
"""
def __init__(self, crop_size, ratio=0.5, method='random', grid=None, allow_outside_center=True):
self.ratio = ratio
self.me... | class RandomCrop(object):
| """Crop the given numpy.ndarray and at a random location.
Args:
size (int or tuple): Desired output size of the crop.(w, h)
"""
def __init__(self, crop_size, ratio=0.5, method='random', grid=None, allow_outside_center=True):
self.ratio = ratio
self.method = method
self... | = [bboxes[i][0], bboxes[i][1], bboxes[i][2], bboxes[i][1],
bboxes[i][0], bboxes[i][3], bboxes[i][2], bboxes[i][3]]
for node in range(4):
x = bbox_temp[node * 2]
y = bbox_temp[node * 2 + 1]
p = np.array([x, y, 1])
... | 256 | 256 | 1,283 | 5 | 250 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomCrop | RandomCrop | 635 | 743 | 635 | 635 | a8615c7f71209f03e57b4a03f813a29d4cade3d4 | bigcode/the-stack | train |
3d478149330f4e845aa1fe88 | train | class | class RandomBrightness(object):
def __init__(self, shift_value=30, ratio=0.5):
self.shift_value = shift_value
self.ratio = ratio
def __call__(self, img, labelmap=None, maskmap=None, kpts=None, bboxes=None, labels=None, polygons=None):
assert isinstance(img, np.ndarray)
assert la... | class RandomBrightness(object):
| def __init__(self, shift_value=30, ratio=0.5):
self.shift_value = shift_value
self.ratio = ratio
def __call__(self, img, labelmap=None, maskmap=None, kpts=None, bboxes=None, labels=None, polygons=None):
assert isinstance(img, np.ndarray)
assert labelmap is None or isinstance(lab... |
img = img.astype(np.float32)
img *= random.uniform(self.lower, self.upper)
img = np.clip(img, 0, 255).astype(np.uint8)
return img, labelmap, maskmap, kpts, bboxes, labels, polygons
class RandomBrightness(object):
| 64 | 64 | 212 | 5 | 58 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomBrightness | RandomBrightness | 338 | 355 | 338 | 338 | f17d067ad9d8a3a74a46e99720052e432f9c778b | bigcode/the-stack | train |
5897e68be2f34e32378e0e6e | train | class | class RandomPad(object):
"""Random Pad a ``np.ndarray``
Args:
inputs: All elements that need to be processed.
up_scale_range: (list): the padding scale range of the image.
mean: (list): the mean pixel value.
ratio: the ratio of random pad.
Returns:
Outputs: All elem... | class RandomPad(object):
| """Random Pad a ``np.ndarray``
Args:
inputs: All elements that need to be processed.
up_scale_range: (list): the padding scale range of the image.
mean: (list): the mean pixel value.
ratio: the ratio of random pad.
Returns:
Outputs: All elements that have been proce... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Donny You (youansheng@gmail.com)
# Image Augmentations implemented by OpenCV. Including RandomPad, RandomRotate, RandomResize etc.
import collections
import random
import math
import cv2
import numpy as np
class RandomPad(object):
| 70 | 243 | 812 | 5 | 64 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomPad | RandomPad | 14 | 85 | 14 | 14 | a23ec8f01ab566cc1624b4b4e33fbcfba2942695 | bigcode/the-stack | train |
483d1ffac4afc95ebcf6e015 | train | class | class RandomHue(object):
def __init__(self, delta=18, ratio=0.5):
assert 0 <= delta <= 360
self.delta = delta
self.ratio = ratio
def __call__(self, img, labelmap=None, maskmap=None, kpts=None, bboxes=None, labels=None, polygons=None):
assert isinstance(img, np.ndarray)
a... | class RandomHue(object):
| def __init__(self, delta=18, ratio=0.5):
assert 0 <= delta <= 360
self.delta = delta
self.ratio = ratio
def __call__(self, img, labelmap=None, maskmap=None, kpts=None, bboxes=None, labels=None, polygons=None):
assert isinstance(img, np.ndarray)
assert labelmap is None or... | cv2.COLOR_BGR2HSV)
img[:, :, 1] *= random.uniform(self.lower, self.upper)
img = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)
img = np.clip(img, 0, 255).astype(np.uint8)
return img, labelmap, maskmap, kpts, bboxes, labels, polygons
class RandomHue(object):
| 84 | 84 | 282 | 5 | 78 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomHue | RandomHue | 273 | 294 | 273 | 273 | 30d9818268cc2148e82f78842665b958cfdbb2eb | bigcode/the-stack | train |
a88bf70ba34150a1197cf42c | train | class | class RandomFocusCrop(object):
"""Crop the given numpy.ndarray and at a random location.
Args:
size (int or tuple): Desired output size of the crop.(w, h)
"""
def __init__(self, crop_size, ratio=0.5, center_jitter=None, mean=(104, 117, 123), allow_outside_center=True):
self.ratio = rat... | class RandomFocusCrop(object):
| """Crop the given numpy.ndarray and at a random location.
Args:
size (int or tuple): Desired output size of the crop.(w, h)
"""
def __init__(self, crop_size, ratio=0.5, center_jitter=None, mean=(104, 117, 123), allow_outside_center=True):
self.ratio = ratio
self.center_jitter =... | = np.clip(polygons[object_id][polygon_id][0::2],
0, target_size[0] - 1)
polygons[object_id][polygon_id][1::2] = np.clip(polygons[object_id][polygon_id][1::2],
... | 256 | 256 | 1,761 | 6 | 249 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomFocusCrop | RandomFocusCrop | 746 | 886 | 746 | 746 | 4fd59acf344b41201b99edd63414f277cca4de82 | bigcode/the-stack | train |
87ca813183a6fd5c66852404 | train | class | class RandomHFlip(object):
def __init__(self, swap_pair=None, ratio=0.5):
self.swap_pair = swap_pair
self.ratio = ratio
def __call__(self, img, labelmap=None, maskmap=None, kpts=None, bboxes=None, labels=None, polygons=None):
assert isinstance(img, (np.ndarray, list))
assert lab... | class RandomHFlip(object):
| def __init__(self, swap_pair=None, ratio=0.5):
self.swap_pair = swap_pair
self.ratio = ratio
def __call__(self, img, labelmap=None, maskmap=None, kpts=None, bboxes=None, labels=None, polygons=None):
assert isinstance(img, (np.ndarray, list))
assert labelmap is None or isinstance... | , target_size[1]) + abs(offset_up),
max(width, target_size[0]) + abs(offset_left)), dtype=labelmap.dtype)
expand_labelmap[:, :] = 255
expand_labelmap[abs(min(offset_up, 0)):abs(min(offset_up, 0)) + height,
abs(min(offset_left, 0)):abs(min(offse... | 163 | 163 | 544 | 6 | 156 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomHFlip | RandomHFlip | 197 | 246 | 197 | 197 | 38ad4aa5616dd245ddfe5ae1c18febebf4261e8e | bigcode/the-stack | train |
9a8d45d964dfc4b94874e9ae | train | class | class Resize(object):
"""Resize the given numpy.ndarray to random size and aspect ratio.
Args:
scale_min: the min scale to resize.
scale_max: the max scale to resize.
"""
def __init__(self, target_size=None, min_side_length=None, max_side_length=None):
self.target_size = target_s... | class Resize(object):
| """Resize the given numpy.ndarray to random size and aspect ratio.
Args:
scale_min: the min scale to resize.
scale_max: the max scale to resize.
"""
def __init__(self, target_size=None, min_side_length=None, max_side_length=None):
self.target_size = target_size
self.min_s... | gt boxes
current_boxes = bboxes[mask, :].copy()
# cut the crop from the image
current_img = img[rect[1]:rect[3], rect[0]:rect[2], :]
# take only matching gt labels
current_labels = labels[mask]
# should we use the box left ... | 202 | 202 | 675 | 4 | 197 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | Resize | Resize | 1,010 | 1,070 | 1,010 | 1,010 | e9384079957e9fcca7dfcf8b58f596e0dbd8297f | bigcode/the-stack | train |
08e68a8cd27b3ee289b7b561 | train | class | class RandomSaturation(object):
def __init__(self, lower=0.5, upper=1.5, ratio=0.5):
self.lower = lower
self.upper = upper
self.ratio = ratio
assert self.upper >= self.lower, "saturation upper must be >= lower."
assert self.lower >= 0, "saturation lower must be non-negative."... | class RandomSaturation(object):
| def __init__(self, lower=0.5, upper=1.5, ratio=0.5):
self.lower = lower
self.upper = upper
self.ratio = ratio
assert self.upper >= self.lower, "saturation upper must be >= lower."
assert self.lower >= 0, "saturation lower must be non-negative."
def __call__(self, img, la... | temp_point = np.copy(kpts[:, pair[0] - 1])
kpts[:, pair[0] - 1] = kpts[:, pair[1] - 1]
kpts[:, pair[1] - 1] = temp_point
return img, labelmap, maskmap, kpts, bboxes, labels, polygons
class RandomSaturation(object):
| 83 | 83 | 278 | 6 | 76 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomSaturation | RandomSaturation | 249 | 270 | 249 | 249 | 8899e7ad909cd62591bb5451dcc9535910917145 | bigcode/the-stack | train |
e8ba0a998ed8f7ef5743cfed | train | class | class RandomPerm(object):
def __init__(self, ratio=0.5):
self.ratio = ratio
self.perms = ((0, 1, 2), (0, 2, 1),
(1, 0, 2), (1, 2, 0),
(2, 0, 1), (2, 1, 0))
def __call__(self, img, labelmap=None, maskmap=None, kpts=None, bboxes=None, labels=None, polyg... | class RandomPerm(object):
| def __init__(self, ratio=0.5):
self.ratio = ratio
self.perms = ((0, 1, 2), (0, 2, 1),
(1, 0, 2), (1, 2, 0),
(2, 0, 1), (2, 1, 0))
def __call__(self, img, labelmap=None, maskmap=None, kpts=None, bboxes=None, labels=None, polygons=None):
assert ... | ] < 0] += 360
img = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)
img = np.clip(img, 0, 255).astype(np.uint8)
return img, labelmap, maskmap, kpts, bboxes, labels, polygons
class RandomPerm(object):
| 70 | 70 | 236 | 5 | 64 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomPerm | RandomPerm | 297 | 314 | 297 | 297 | d410881e9848f68ce94ef123ab6ab2a74f807911 | bigcode/the-stack | train |
c95f1af676958f0ffd892947 | train | class | class RandomResize(object):
"""Resize the given numpy.ndarray to random size and aspect ratio.
Args:
scale_min: the min scale to resize.
scale_max: the max scale to resize.
"""
def __init__(self, scale_range=(0.75, 1.25), aspect_range=(0.9, 1.1), target_size=None,
resiz... | class RandomResize(object):
| """Resize the given numpy.ndarray to random size and aspect ratio.
Args:
scale_min: the min scale to resize.
scale_max: the max scale to resize.
"""
def __init__(self, scale_range=(0.75, 1.25), aspect_range=(0.9, 1.1), target_size=None,
resize_bound=None, method='random... | <= width and h <= height:
i = random.randint(0, height - h)
j = random.randint(0, width - w)
return i, j, h, w
# Fallback
w = min(height, width)
i = (height - w) // 2
j = (width - w) // 2
return i, j, w, w
def __call__(self, ... | 256 | 256 | 1,066 | 5 | 250 | luyanger1799/torchcv | datasets/tools/cv2_aug_transforms.py | Python | RandomResize | RandomResize | 428 | 531 | 428 | 428 | b14bdfb14aeac689dbf9f56670b2f713f5f432ff | bigcode/the-stack | train |
bf81c42bccc154c5237923fe | train | class | class Main(BasePage):
def go_to_Address_book(self): # 进入通讯录
# self.driver.find_element(MobileBy.XPATH, '//*[@text="通讯录"]').click()
self.find(MobileBy.XPATH, '//*[@text="通讯录"]')
return Address_book(self.driver)
| class Main(BasePage):
| def go_to_Address_book(self): # 进入通讯录
# self.driver.find_element(MobileBy.XPATH, '//*[@text="通讯录"]').click()
self.find(MobileBy.XPATH, '//*[@text="通讯录"]')
return Address_book(self.driver)
| from appium.webdriver.common.mobileby import MobileBy
from app_APPium_test.src.Address_book import Address_book
from app_APPium_test.src.BasePage import BasePage
class Main(BasePage):
| 40 | 64 | 63 | 5 | 34 | XuXuClassMate/My_Test_PyProject | app_APPium_test/src/Mian.py | Python | Main | Main | 6 | 10 | 6 | 6 | 380849763c681e738c9ba7e2bee0bf6eeaf6827f | bigcode/the-stack | train |
5cc02ab55951c7ca834f3c5b | train | class | class DASHNamespace(Serializable):
def __init__(self, prefix, uri):
super().__init__()
self.prefix = prefix
self.uri = uri
@classmethod
def parse_from_json_object(cls, json_object):
prefix = json_object.get('prefix')
uri = json_object.get('uri')
namespace = ... | class DASHNamespace(Serializable):
| def __init__(self, prefix, uri):
super().__init__()
self.prefix = prefix
self.uri = uri
@classmethod
def parse_from_json_object(cls, json_object):
prefix = json_object.get('prefix')
uri = json_object.get('uri')
namespace = DASHNamespace(prefix=prefix, uri=uri... | from bitmovin.utils import Serializable
class DASHNamespace(Serializable):
| 14 | 64 | 84 | 6 | 7 | camberbridge/bitmovin-python | bitmovin/resources/models/manifests/dash/dash_name_space.py | Python | DASHNamespace | DASHNamespace | 4 | 16 | 4 | 5 | 12e832a484ea08ef948edbe5f28107f7360a75bb | bigcode/the-stack | train |
63df5a8e60061be6f4b30bdc | train | class | class QActivityItem:
def __init__(self, user, activity, last_push):
self.user = user
self.activity = activity
self.last_push = last_push
def widgets(self):
if isinstance(self.activity, int):
activity = QNumericItem(hex(self.activity))
activity.setData(Qt.... | class QActivityItem:
| def __init__(self, user, activity, last_push):
self.user = user
self.activity = activity
self.last_push = last_push
def widgets(self):
if isinstance(self.activity, int):
activity = QNumericItem(hex(self.activity))
activity.setData(Qt.UserRole, self.activi... | Widget, QTableWidgetItem, QAbstractItemView, QHeaderView, QMenu
from PyQt5.QtCore import Qt
from ..utils import QNumericItem, friendly_datetime
from ...controller import BinSyncController
from .... import State
from ....data import Function
class QActivityItem:
| 64 | 64 | 190 | 5 | 58 | zachsez/binsync | binsync/common/ui/tables/activity_table.py | Python | QActivityItem | QActivityItem | 20 | 50 | 20 | 20 | 7f09c6c0aa798c75afa5dfc81d09f6ecb51ab89c | bigcode/the-stack | train |
51799f6a9a2bc3f494b802bf | train | class | class QActivityTable(QTableWidget):
"""
The activity table shown in the Control Panel. This table is responsible for showing users information
that is relevant to other users activity. The main user wants to know what others are doing, and how
often they are doing it. This table should also allow users ... | class QActivityTable(QTableWidget):
| """
The activity table shown in the Control Panel. This table is responsible for showing users information
that is relevant to other users activity. The main user wants to know what others are doing, and how
often they are doing it. This table should also allow users to sync from a user if they see them... | , QTableWidgetItem, QAbstractItemView, QHeaderView, QMenu
from PyQt5.QtCore import Qt
from ..utils import QNumericItem, friendly_datetime
from ...controller import BinSyncController
from .... import State
from ....data import Function
class QActivityItem:
def __init__(self, user, activity, last_push):
... | 256 | 256 | 879 | 8 | 247 | zachsez/binsync | binsync/common/ui/tables/activity_table.py | Python | QActivityTable | QActivityTable | 53 | 166 | 53 | 53 | d60f150ae618812fa440eb3c67cdb162abd2704d | bigcode/the-stack | train |
f95582db8914fee1cd842208 | train | class | class Topology(object):
"""Monitor a topology of one or more servers."""
def __init__(self, topology_settings):
self._settings = topology_settings
topology_description = TopologyDescription(
topology_settings.get_topology_type(),
topology_settings.get_server_descriptions(... | class Topology(object):
| """Monitor a topology of one or more servers."""
def __init__(self, topology_settings):
self._settings = topology_settings
topology_description = TopologyDescription(
topology_settings.get_topology_type(),
topology_settings.get_server_descriptions(),
topology_... | Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distribute... | 256 | 256 | 2,879 | 5 | 251 | musicrighter/P2-Iteration-0 | env/lib/python3.4/site-packages/pymongo/topology.py | Python | Topology | Topology | 36 | 424 | 36 | 36 | 71427d74a6a9360092d7d32f345b94adea29aa25 | bigcode/the-stack | train |
faaa6f81de13ed0c58411869 | train | class | class Font(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "scattergeo.hoverlabel"
_path_str = "scattergeo.hoverlabel.font"
_valid_props = {"color", "colorsrc", "family", "familysrc", "size", "sizesrc"}
# color
# -----
@property
def color(self... | class Font(_BaseTraceHierarchyType):
# class properties
# --------------------
| _parent_path_str = "scattergeo.hoverlabel"
_path_str = "scattergeo.hoverlabel.font"
_valid_props = {"color", "colorsrc", "family", "familysrc", "size", "sizesrc"}
# color
# -----
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
... | from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Font(_BaseTraceHierarchyType):
# class properties
# --------------------
| 42 | 256 | 2,591 | 17 | 24 | mastermind88/plotly.py | packages/python/plotly/plotly/graph_objs/scattergeo/hoverlabel/_font.py | Python | Font | Font | 5 | 330 | 5 | 8 | ef791adea6679beb016e9d5f17833d430b8c1545 | bigcode/the-stack | train |
0af795cd9db4d6260194a571 | train | class | class JavaScriptLibrary(object):
"""JavaScript库地址集合"""
def __init__(self, cache_path: str):
self.cache_path = cache_path
def get(self, name: str) -> str:
"""获取JavaScript库"""
if name.lower() in JS_LIBRARY:
# 读取目标JavaScript库的Url
library_url = JS_LIBRARY[name.l... | class JavaScriptLibrary(object):
| """JavaScript库地址集合"""
def __init__(self, cache_path: str):
self.cache_path = cache_path
def get(self, name: str) -> str:
"""获取JavaScript库"""
if name.lower() in JS_LIBRARY:
# 读取目标JavaScript库的Url
library_url = JS_LIBRARY[name.lower()]
# 在缓存文件夹中创建J... | import json
import os
from json import JSONDecodeError
import requests
from requests.exceptions import RequestException
# JavaScript库下载地址集合
JS_LIBRARY = {
"jquery": "https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"
}
class JavaScriptLibrary(object):
| 66 | 117 | 393 | 6 | 60 | ChangxingJiang/Selenium4R | Selenium4R/common/JavaScriptLibrary.py | Python | JavaScriptLibrary | JavaScriptLibrary | 14 | 61 | 14 | 14 | ed7cb1272d779faae74744a98f1c2d69b7913bd0 | bigcode/the-stack | train |
daf7c4c460d2fa1bf2a2f6c6 | train | function | def Bracket(token: tokens.Bracket, state):
if token.context == 'attribute':
return '[' if token.open else ']'
if token.context == 'expression':
return '{' if token.open else '}'
return '(' if token.open else '}'
| def Bracket(token: tokens.Bracket, state):
| if token.context == 'attribute':
return '[' if token.open else ']'
if token.context == 'expression':
return '{' if token.open else '}'
return '(' if token.open else '}'
| raise Exception('Unknown token %s' % token.type)
return visitor(token, state)
def Literal(token: tokens.Literal, state):
return token.value
def Quote(token: tokens.Quote, state):
return '\'' if token.single else '"'
def Bracket(token: tokens.Bracket, state):
| 64 | 64 | 55 | 11 | 52 | jingyuexing/py-emmet | emmet/abbreviation/stringify.py | Python | Bracket | Bracket | 31 | 36 | 31 | 31 | 9b6b69349715f29081f879742631b39b2239b067 | bigcode/the-stack | train |
0764009e3c51ebd88ee403d2 | train | function | def WhiteSpace(token, state):
return ' '
| def WhiteSpace(token, state):
| return ' '
| _ix - token.parent)
if parent_ix != last_ix:
value += repeater.count * state.repeaters[parent_ix].value
result = str(value)
prefix = '0' * max(0, token.size - len(result))
return prefix + result
def WhiteSpace(token, state):
| 64 | 64 | 11 | 7 | 56 | jingyuexing/py-emmet | emmet/abbreviation/stringify.py | Python | WhiteSpace | WhiteSpace | 94 | 95 | 94 | 94 | 4b15034a7f2a95ee281aaa2652945c2d5c13476a | bigcode/the-stack | train |
966f5b26039091cf0d19daae | train | function | def RepeaterPlaceholder(token: tokens.RepeaterPlaceholder, state):
# Find closest implicit repeater
repeater = None
repeater_list = state.repeaters[:]
repeater_list.reverse()
for r in repeater_list:
if r.implicit:
repeater = r
break
state.inserted = True
ret... | def RepeaterPlaceholder(token: tokens.RepeaterPlaceholder, state):
# Find closest implicit repeater
| repeater = None
repeater_list = state.repeaters[:]
repeater_list.reverse()
for r in repeater_list:
if r.implicit:
repeater = r
break
state.inserted = True
return state.get_text(repeater.value) if repeater else None
| if token.name else '${%s}'
return fmt % (token.index, token.name)
if token.name:
# It’s a variable
return state.get_variable(token.name)
return ''
def RepeaterPlaceholder(token: tokens.RepeaterPlaceholder, state):
# Find closest implicit repeater
| 63 | 64 | 88 | 21 | 42 | jingyuexing/py-emmet | emmet/abbreviation/stringify.py | Python | RepeaterPlaceholder | RepeaterPlaceholder | 57 | 69 | 57 | 58 | d59ff439581e130d45cd456d12a9dca0d122718b | bigcode/the-stack | train |
ed557cb0bd8c9a4218347776 | train | function | def stringify(token: tokens.Token, state):
visitor = globals().get(token.type)
if not visitor:
raise Exception('Unknown token %s' % token.type)
return visitor(token, state)
| def stringify(token: tokens.Token, state):
| visitor = globals().get(token.type)
if not visitor:
raise Exception('Unknown token %s' % token.type)
return visitor(token, state)
| from .tokenizer import tokens
operators = {
'child': '>',
'class': '.',
'climb': '^',
'id': '#',
'equal': '=',
'close': '/',
'sibling': '+'
}
def stringify(token: tokens.Token, state):
| 63 | 64 | 43 | 9 | 54 | jingyuexing/py-emmet | emmet/abbreviation/stringify.py | Python | stringify | stringify | 15 | 20 | 15 | 15 | b4df435ed45ef2e21fdaf0024de76bff0fb5445c | bigcode/the-stack | train |
e5280a4a56486459042261ef | train | function | def Field(token: tokens.Field, state):
if token.index is not None:
# It’s a field: by default, return TextMate-compatible field
fmt = '${%d:%s}' if token.name else '${%s}'
return fmt % (token.index, token.name)
if token.name:
# It’s a variable
return state.get_variable(t... | def Field(token: tokens.Field, state):
| if token.index is not None:
# It’s a field: by default, return TextMate-compatible field
fmt = '${%d:%s}' if token.name else '${%s}'
return fmt % (token.index, token.name)
if token.name:
# It’s a variable
return state.get_variable(token.name)
return ''
| '[' if token.open else ']'
if token.context == 'expression':
return '{' if token.open else '}'
return '(' if token.open else '}'
def Operator(token: tokens.Operator, state):
global operators
return operators.get(token.operator)
def Field(token: tokens.Field, state):
| 64 | 64 | 84 | 9 | 55 | jingyuexing/py-emmet | emmet/abbreviation/stringify.py | Python | Field | Field | 44 | 54 | 44 | 44 | b6e3aaf2d2f01e1dc02ef7e1cd8eae55dcd1c20d | bigcode/the-stack | train |
d0b51b3bd0a5e7984f3b286e | train | function | def RepeaterNumber(token: tokens.RepeaterNumber, state):
value = 1
last_ix = len(state.repeaters) - 1
if last_ix >= 0:
repeater = state.repeaters[-1]
if token.reverse:
value = token.base + repeater.count - repeater.value - 1
else:
value = token.base + repeate... | def RepeaterNumber(token: tokens.RepeaterNumber, state):
| value = 1
last_ix = len(state.repeaters) - 1
if last_ix >= 0:
repeater = state.repeaters[-1]
if token.reverse:
value = token.base + repeater.count - repeater.value - 1
else:
value = token.base + repeater.value
if token.parent:
parent_ix =... | repeater_list.reverse()
for r in repeater_list:
if r.implicit:
repeater = r
break
state.inserted = True
return state.get_text(repeater.value) if repeater else None
def RepeaterNumber(token: tokens.RepeaterNumber, state):
| 64 | 64 | 156 | 13 | 50 | jingyuexing/py-emmet | emmet/abbreviation/stringify.py | Python | RepeaterNumber | RepeaterNumber | 72 | 91 | 72 | 72 | 3691c12d9da50a40969303a237276a4f7fdb9a3f | bigcode/the-stack | train |
32b70bd2a75df0dc40c356df | train | function | def Quote(token: tokens.Quote, state):
return '\'' if token.single else '"'
| def Quote(token: tokens.Quote, state):
| return '\'' if token.single else '"'
| tokens.Token, state):
visitor = globals().get(token.type)
if not visitor:
raise Exception('Unknown token %s' % token.type)
return visitor(token, state)
def Literal(token: tokens.Literal, state):
return token.value
def Quote(token: tokens.Quote, state):
| 64 | 64 | 19 | 10 | 53 | jingyuexing/py-emmet | emmet/abbreviation/stringify.py | Python | Quote | Quote | 27 | 28 | 27 | 27 | 1bff978131a0f1b317d4ef98a61d5088d24bce36 | bigcode/the-stack | train |
a30679b1307370c72deb70df | train | function | def Operator(token: tokens.Operator, state):
global operators
return operators.get(token.operator)
| def Operator(token: tokens.Operator, state):
| global operators
return operators.get(token.operator)
| Bracket(token: tokens.Bracket, state):
if token.context == 'attribute':
return '[' if token.open else ']'
if token.context == 'expression':
return '{' if token.open else '}'
return '(' if token.open else '}'
def Operator(token: tokens.Operator, state):
| 63 | 64 | 20 | 9 | 54 | jingyuexing/py-emmet | emmet/abbreviation/stringify.py | Python | Operator | Operator | 39 | 41 | 39 | 39 | 787924cd0cf25cbf01bab9f3bfde95c0acb7182b | bigcode/the-stack | train |
f184a2e7fdfc7f54d793e09e | train | function | def Literal(token: tokens.Literal, state):
return token.value
| def Literal(token: tokens.Literal, state):
| return token.value
| close': '/',
'sibling': '+'
}
def stringify(token: tokens.Token, state):
visitor = globals().get(token.type)
if not visitor:
raise Exception('Unknown token %s' % token.type)
return visitor(token, state)
def Literal(token: tokens.Literal, state):
| 64 | 64 | 15 | 10 | 54 | jingyuexing/py-emmet | emmet/abbreviation/stringify.py | Python | Literal | Literal | 23 | 24 | 23 | 23 | 300c8d2c8b5ef1a44acb763682b787e17f25ad33 | bigcode/the-stack | train |
72ca127eb709646870bea311 | train | function | def create(kernel):
result = Building()
result.template = "object/building/general/shared_cave_07_flatland_s02.iff"
result.attribute_template_id = -1
result.stfName("building_name","cave")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | def create(kernel):
| result = Building()
result.template = "object/building/general/shared_cave_07_flatland_s02.iff"
result.attribute_template_id = -1
result.stfName("building_name","cave")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
| 46 | 64 | 68 | 4 | 42 | obi-two/GameServer | data/scripts/templates/object/building/general/shared_cave_07_flatland_s02.py | Python | create | create | 7 | 17 | 7 | 7 | d78b4ba4ccbca9151ec61d9b3d34c0c287582c38 | bigcode/the-stack | train |
be508537df3e1beac870cc45 | train | function | def perturb_rotations(rotations, angle_sigma):
for i in range(len(rotations)):
rotation = rotations[i]
rodrigues = cv2.Rodrigues(rotation)[0].ravel()
angle = np.linalg.norm(rodrigues)
angle_pertubed = angle + np.random.normal(0.0, angle_sigma)
rodrigues *= (float(angle_pertub... | def perturb_rotations(rotations, angle_sigma):
| for i in range(len(rotations)):
rotation = rotations[i]
rodrigues = cv2.Rodrigues(rotation)[0].ravel()
angle = np.linalg.norm(rodrigues)
angle_pertubed = angle + np.random.normal(0.0, angle_sigma)
rodrigues *= (float(angle_pertubed)/float(angle))
rotations[i] = cv2.Ro... |
exif['gps']['altitude'] = alt
exif['gps']['dop'] = gps_noise
exif['compass'] = {'angle': comp}
exifs[shot_name] = exif
return exifs
def perturb_rotations(rotations, angle_sigma):
| 64 | 64 | 110 | 10 | 53 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | perturb_rotations | perturb_rotations | 155 | 162 | 155 | 155 | d00d31a87092e17695bbb6b9fcf3443f5d54b0d0 | bigcode/the-stack | train |
c3d53f2f936b26163538660b | train | function | def weird_curve(length, point):
y = math.cos(point+0.1*point**2+2.3*point**4 +
0.8*point**7+0.1*point**9)
return length*np.transpose(np.array([point, y]))
| def weird_curve(length, point):
| y = math.cos(point+0.1*point**2+2.3*point**4 +
0.8*point**7+0.1*point**9)
return length*np.transpose(np.array([point, y]))
| np.insert(rotations, 1, values=np.array([0, 0, -1]), axis=1)
return positions, rotations
def line_generator(length, point):
x = point*length
return np.transpose(np.array([x, 0]))
def weird_curve(length, point):
| 63 | 64 | 60 | 7 | 56 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | weird_curve | weird_curve | 97 | 100 | 97 | 97 | 696af79efe7e847a4b70f70c3fb7335cd59d67f1 | bigcode/the-stack | train |
6a196b6293e9ae5b454a2d82 | train | function | def generate_track_data(reconstruction, maximum_depth, noise):
tracks_manager = pysfm.TracksManager()
feature_data_type = np.float32
desc_size = 128
non_zeroes = 5
track_descriptors = {}
for track_index in reconstruction.points:
descriptor = np.zeros(desc_size)
for i in range(no... | def generate_track_data(reconstruction, maximum_depth, noise):
| tracks_manager = pysfm.TracksManager()
feature_data_type = np.float32
desc_size = 128
non_zeroes = 5
track_descriptors = {}
for track_index in reconstruction.points:
descriptor = np.zeros(desc_size)
for i in range(non_zeroes):
index = np.random.randint(0, desc_size)
... | shift = len(reconstruction.points)
for i in range(points.shape[0]):
point = types.Point()
point.id = str(shift+i)
point.coordinates = points[i, :]
point.color = color
reconstruction.add_point(point)
def create_reconstruction(points, colors,
camera... | 149 | 149 | 497 | 12 | 136 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | generate_track_data | generate_track_data | 200 | 257 | 200 | 200 | 391608e284d02d62a876ceee4339a26535874b2a | bigcode/the-stack | train |
a42146126654af25794ff3bb | train | function | def _is_inside_camera(projection, camera):
if camera.width > camera.height:
return (-0.5 < projection[0] < 0.5) and \
(-float(camera.height)/float(2*camera.width) < projection[1]
< float(camera.height)/float(2*camera.width))
else:
return (-0.5 < projection[1] < 0.5) a... | def _is_inside_camera(projection, camera):
| if camera.width > camera.height:
return (-0.5 < projection[0] < 0.5) and \
(-float(camera.height)/float(2*camera.width) < projection[1]
< float(camera.height)/float(2*camera.width))
else:
return (-0.5 < projection[1] < 0.5) and \
(-float(camera.width)/floa... | shot, maximum_depth):
return shot.pose.transform(point.coordinates)[2] < maximum_depth
def _is_in_front(point, shot):
return np.dot((point.coordinates - shot.pose.get_origin()),
shot.pose.get_rotation_matrix()[2]) > 0
def _is_inside_camera(projection, camera):
| 64 | 64 | 121 | 10 | 53 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | _is_inside_camera | _is_inside_camera | 269 | 277 | 269 | 269 | eb0a97f1311ff610242d89b3103b74ccafea96fe | bigcode/the-stack | train |
924eab05c0aede040cf48539 | train | function | def add_shots_to_reconstruction(positions, rotations,
camera, reconstruction):
shift = len(reconstruction.shots)
for i, item in enumerate(zip(positions, rotations)):
shot = types.Shot()
shot.id = 'shot%04d' % (shift + i)
shot.camera = camera
shot.p... | def add_shots_to_reconstruction(positions, rotations,
camera, reconstruction):
| shift = len(reconstruction.shots)
for i, item in enumerate(zip(positions, rotations)):
shot = types.Shot()
shot.id = 'shot%04d' % (shift + i)
shot.camera = camera
shot.pose = types.Pose()
shot.pose.set_rotation_matrix(item[1])
shot.pose.set_origin(item[0])
... | + np.random.normal(0.0, angle_sigma)
rodrigues *= (float(angle_pertubed)/float(angle))
rotations[i] = cv2.Rodrigues(rodrigues)[0]
def add_shots_to_reconstruction(positions, rotations,
camera, reconstruction):
| 64 | 64 | 109 | 17 | 47 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | add_shots_to_reconstruction | add_shots_to_reconstruction | 165 | 176 | 165 | 166 | 7447967e62fd082a990d1e4dcdcf9f53303aa3ac | bigcode/the-stack | train |
444a5b742990345a12f3797f | train | function | def samples_generator_random_count(count):
return np.random.rand(count)
| def samples_generator_random_count(count):
| return np.random.rand(count)
|
from opensfm import reconstruction as rc
from opensfm import pysfm
def derivative(func, x):
eps = 1e-10
d = (func(x+eps)-func(x))/eps
d /= np.linalg.norm(d)
return d
def samples_generator_random_count(count):
| 64 | 64 | 14 | 7 | 56 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | samples_generator_random_count | samples_generator_random_count | 20 | 21 | 20 | 20 | a2a19267d346069a3179b5ddc62335d39c6f52a0 | bigcode/the-stack | train |
7ce92b48093d4263c61d7d89 | train | function | def _is_in_front(point, shot):
return np.dot((point.coordinates - shot.pose.get_origin()),
shot.pose.get_rotation_matrix()[2]) > 0
| def _is_in_front(point, shot):
| return np.dot((point.coordinates - shot.pose.get_origin()),
shot.pose.get_rotation_matrix()[2]) > 0
| = np.array(colors_inside)
descriptors[shot_index] = np.array(descriptors_inside)
return features, descriptors, colors, tracks_manager
def _check_depth(point, shot, maximum_depth):
return shot.pose.transform(point.coordinates)[2] < maximum_depth
def _is_in_front(point, shot):
| 64 | 64 | 35 | 9 | 54 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | _is_in_front | _is_in_front | 264 | 266 | 264 | 264 | 3b67906cb8f4cf3538c95be4b88debd69e8c9b69 | bigcode/the-stack | train |
9522d080a053e2becf9829eb | train | function | def generate_xy_planes(samples, shape, z_size, y_size):
xy1 = generate_samples_shifted(samples, shape, y_size)
xy2 = generate_samples_shifted(samples, shape, -y_size)
xy1 = np.insert(xy1, 2, values=np.random.rand(
xy1.shape[0])*z_size, axis=1)
xy2 = np.insert(xy2, 2, values=np.random.rand(
... | def generate_xy_planes(samples, shape, z_size, y_size):
| xy1 = generate_samples_shifted(samples, shape, y_size)
xy2 = generate_samples_shifted(samples, shape, -y_size)
xy1 = np.insert(xy1, 2, values=np.random.rand(
xy1.shape[0])*z_size, axis=1)
xy2 = np.insert(xy2, 2, values=np.random.rand(
xy2.shape[0])*z_size, axis=1)
return np.concatena... | .rand()-0.5)*thickness)
point += shift
plane_points += [point]
plane_points = np.array(plane_points)
return np.insert(plane_points, 2, values=0, axis=1)
def generate_xy_planes(samples, shape, z_size, y_size):
| 64 | 64 | 124 | 14 | 50 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | generate_xy_planes | generate_xy_planes | 68 | 75 | 68 | 68 | 110156a394055ee531eac2c84a829551f749d961 | bigcode/the-stack | train |
2335c33ff489114ea3edaafe | train | function | def generate_z_plane(samples, shape, thickness):
plane_points = []
for i in samples:
point = shape(i)
tangent = derivative(shape, i)
tangent = np.array([-tangent[1], tangent[0]])
shift = tangent*((np.random.rand()-0.5)*thickness)
point += shift
plane_points += [po... | def generate_z_plane(samples, shape, thickness):
| plane_points = []
for i in samples:
point = shape(i)
tangent = derivative(shape, i)
tangent = np.array([-tangent[1], tangent[0]])
shift = tangent*((np.random.rand()-0.5)*thickness)
point += shift
plane_points += [point]
plane_points = np.array(plane_points)
... | :
point = shape(i)
tangent = derivative(shape, i)
tangent = np.array([-tangent[1], tangent[0]])
point += tangent*(shift/2)
plane_points += [point]
return np.array(plane_points)
def generate_z_plane(samples, shape, thickness):
| 64 | 64 | 107 | 10 | 54 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | generate_z_plane | generate_z_plane | 55 | 65 | 55 | 55 | 904e8bde823f59b5cf4ffb1548ccf46b5b7adf84 | bigcode/the-stack | train |
7aa994a53841cd31bd05b811 | train | function | def line_generator(length, point):
x = point*length
return np.transpose(np.array([x, 0]))
| def line_generator(length, point):
| x = point*length
return np.transpose(np.array([x, 0]))
| , axis=1)
rotations = np.insert(rotations, 2, values=0, axis=2)
rotations = np.insert(rotations, 1, values=np.array([0, 0, -1]), axis=1)
return positions, rotations
def line_generator(length, point):
| 64 | 64 | 26 | 7 | 56 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | line_generator | line_generator | 92 | 94 | 92 | 92 | 79c30ad32f0b586b52c8a860c58c05743273813b | bigcode/the-stack | train |
945de698ac4f02aff2d27468 | train | function | def generate_exifs(reconstruction, gps_noise, speed_ms=10):
"""Generate fake exif metadata from the reconstruction."""
previous_pose = None
previous_time = 0
exifs = {}
reference = geo.TopocentricConverter(0, 0, 0)
for shot_name in sorted(reconstruction.shots.keys()):
shot = reconstructi... | def generate_exifs(reconstruction, gps_noise, speed_ms=10):
| """Generate fake exif metadata from the reconstruction."""
previous_pose = None
previous_time = 0
exifs = {}
reference = geo.TopocentricConverter(0, 0, 0)
for shot_name in sorted(reconstruction.shots.keys()):
shot = reconstruction.shots[shot_name]
exif = {}
exif['width'] ... | x = np.cos(point*2*np.pi)*x_size/2
return np.transpose(np.array([x, y]))
def perturb_points(points, sigmas):
eps = 1e-10
for point in points:
sigmas = np.array([max(s, eps) for s in sigmas])
point += np.random.normal(0.0, sigmas,
point.shape)
def generate... | 101 | 101 | 339 | 15 | 86 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | generate_exifs | generate_exifs | 117 | 152 | 117 | 117 | 8d1790fac89bb27b61390a14643cfcc0c2f95ef0 | bigcode/the-stack | train |
f1cbc2120f48ef5c921e1867 | train | function | def add_points_to_reconstruction(points, color, reconstruction):
shift = len(reconstruction.points)
for i in range(points.shape[0]):
point = types.Point()
point.id = str(shift+i)
point.coordinates = points[i, :]
point.color = color
reconstruction.add_point(point)
| def add_points_to_reconstruction(points, color, reconstruction):
| shift = len(reconstruction.points)
for i in range(points.shape[0]):
point = types.Point()
point.id = str(shift+i)
point.coordinates = points[i, :]
point.color = color
reconstruction.add_point(point)
| (shift + i)
shot.camera = camera
shot.pose = types.Pose()
shot.pose.set_rotation_matrix(item[1])
shot.pose.set_origin(item[0])
reconstruction.add_shot(shot)
reconstruction.add_camera(camera)
def add_points_to_reconstruction(points, color, reconstruction):
| 64 | 64 | 65 | 12 | 52 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | add_points_to_reconstruction | add_points_to_reconstruction | 179 | 186 | 179 | 179 | 7fd580555c4fedabe9c3438aff5989ba997482da | bigcode/the-stack | train |
71d54ae783c167585352c79a | train | function | def perturb_points(points, sigmas):
eps = 1e-10
for point in points:
sigmas = np.array([max(s, eps) for s in sigmas])
point += np.random.normal(0.0, sigmas,
point.shape)
| def perturb_points(points, sigmas):
| eps = 1e-10
for point in points:
sigmas = np.array([max(s, eps) for s in sigmas])
point += np.random.normal(0.0, sigmas,
point.shape)
|
def ellipse_generator(x_size, y_size, point):
y = np.sin(point*2*np.pi)*y_size/2
x = np.cos(point*2*np.pi)*x_size/2
return np.transpose(np.array([x, y]))
def perturb_points(points, sigmas):
| 63 | 64 | 59 | 8 | 55 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | perturb_points | perturb_points | 109 | 114 | 109 | 109 | 0490930056c0725db0b97d50abe72fed838aa089 | bigcode/the-stack | train |
5de3837ab57b8bbe61f78ef4 | train | function | def samples_generator_interval(start, length, interval, interval_noise):
samples = np.linspace(start/length, 1, num=int(length/interval))
samples += np.random.normal(0.0,
float(interval_noise)/float(length),
samples.shape)
return samples
| def samples_generator_interval(start, length, interval, interval_noise):
| samples = np.linspace(start/length, 1, num=int(length/interval))
samples += np.random.normal(0.0,
float(interval_noise)/float(length),
samples.shape)
return samples
| x):
eps = 1e-10
d = (func(x+eps)-func(x))/eps
d /= np.linalg.norm(d)
return d
def samples_generator_random_count(count):
return np.random.rand(count)
def samples_generator_interval(start, length, interval, interval_noise):
| 64 | 64 | 58 | 13 | 51 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | samples_generator_interval | samples_generator_interval | 24 | 29 | 24 | 24 | c7e3dc55616e8bc7016cacb365b1239926923565 | bigcode/the-stack | train |
1f1f8dab471920ecd5f83665 | train | function | def ellipse_generator(x_size, y_size, point):
y = np.sin(point*2*np.pi)*y_size/2
x = np.cos(point*2*np.pi)*x_size/2
return np.transpose(np.array([x, y]))
| def ellipse_generator(x_size, y_size, point):
| y = np.sin(point*2*np.pi)*y_size/2
x = np.cos(point*2*np.pi)*x_size/2
return np.transpose(np.array([x, y]))
| y = math.cos(point+0.1*point**2+2.3*point**4 +
0.8*point**7+0.1*point**9)
return length*np.transpose(np.array([point, y]))
def ellipse_generator(x_size, y_size, point):
| 63 | 64 | 54 | 11 | 52 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | ellipse_generator | ellipse_generator | 103 | 106 | 103 | 103 | cc73601becde66c256191c5a1564a5321f31af11 | bigcode/the-stack | train |
c033b8ac22586781fd842002 | train | function | def create_reconstruction(points, colors,
cameras, positions,
rotations):
reconstruction = types.Reconstruction()
for item in zip(points, colors):
add_points_to_reconstruction(item[0], item[1], reconstruction)
for item in zip(positions, rotations, ... | def create_reconstruction(points, colors,
cameras, positions,
rotations):
| reconstruction = types.Reconstruction()
for item in zip(points, colors):
add_points_to_reconstruction(item[0], item[1], reconstruction)
for item in zip(positions, rotations, cameras):
add_shots_to_reconstruction(item[0], item[1], item[2], reconstruction)
return reconstruction
| construction.points)
for i in range(points.shape[0]):
point = types.Point()
point.id = str(shift+i)
point.coordinates = points[i, :]
point.color = color
reconstruction.add_point(point)
def create_reconstruction(points, colors,
cameras, positions,
... | 64 | 64 | 85 | 16 | 48 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | create_reconstruction | create_reconstruction | 189 | 197 | 189 | 191 | dd91e3380d7b733977630571cf8a18957c88cc26 | bigcode/the-stack | train |
b690230194e0b9f7526cb5d8 | train | function | def derivative(func, x):
eps = 1e-10
d = (func(x+eps)-func(x))/eps
d /= np.linalg.norm(d)
return d
| def derivative(func, x):
| eps = 1e-10
d = (func(x+eps)-func(x))/eps
d /= np.linalg.norm(d)
return d
| import numpy as np
from collections import defaultdict
import math
import copy
import cv2
from opensfm import geo
from opensfm import types
from opensfm import reconstruction as rc
from opensfm import pysfm
def derivative(func, x):
| 53 | 64 | 41 | 6 | 46 | ragarciafran/OpenSfM | opensfm/synthetic_data/synthetic_generator.py | Python | derivative | derivative | 13 | 17 | 13 | 13 | 967327ee76d9e924559db36df92ff364ba63dcd0 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.