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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b4c003e1422a08c06b2a0b9a | train | class | class DictionaryInfo:
# filename of dictionary
# On Windows, filename is stored in UTF-8 encoding
filename: str
# character set of the dictionary. e.g., "SHIFT-JIS", "UTF-8"
charset: str
# How many words are registered in this dictionary.
size: int
# dictionary type
# this value s... | class DictionaryInfo:
# filename of dictionary
# On Windows, filename is stored in UTF-8 encoding
| filename: str
# character set of the dictionary. e.g., "SHIFT-JIS", "UTF-8"
charset: str
# How many words are registered in this dictionary.
size: int
# dictionary type
# this value should be MECAB_USR_DIC, MECAB_SYS_DIC, or MECAB_UNK_DIC.
type: int
# left attributes size
lsi... | # The position is a strong token boundary.
MECAB_TOKEN_BOUNDARY = 1
# The position is not a token boundary.
MECAB_INSIDE_TOKEN = 2
class DictionaryInfo:
# filename of dictionary
# On Windows, filename is stored in UTF-8 encoding
| 64 | 64 | 174 | 24 | 39 | lainrose/pecab | mecab/data_structure.py | Python | DictionaryInfo | DictionaryInfo | 70 | 96 | 70 | 72 | eb2c7ea59de50a0d75712a6dce830ed7ba337ae5 | bigcode/the-stack | train |
98d0a6d7823c67c1b382d557 | train | class | class Path:
# pointer to the right node
# type of rnode is Node*
rnode: object
# pointer to the next right path
# python can't access itself. (type of rnext is Path*)
rnext: object
# pointer to the left node
# type of lnode is Node*
lnode: object
# pointer to the next left pat... | class Path:
# pointer to the right node
# type of rnode is Node*
| rnode: object
# pointer to the next right path
# python can't access itself. (type of rnext is Path*)
rnext: object
# pointer to the left node
# type of lnode is Node*
lnode: object
# pointer to the next left path
# python can't access itself. (type of lnext is Path*)
lnext: o... | : int
# version of this dictionary
version: int
# pointer to the next dictionary info.
# python can't access itself. (type of next is DictionaryInfo*)
next: object
class Path:
# pointer to the right node
# type of rnode is Node*
| 64 | 64 | 129 | 20 | 43 | lainrose/pecab | mecab/data_structure.py | Python | Path | Path | 99 | 120 | 99 | 101 | 008fdbc705f989e55444dbe4eb37b936e8d7972c | bigcode/the-stack | train |
54640634ab454072ee8e5ad8 | train | class | class RequestType:
# One best result is obtained (default mode)
MECAB_ONE_BEST = 1
# Set this flag if you want to obtain N best results.
MECAB_NBEST = 2
# Set this flag if you want to enable a partial parsing mode.
# When this flag is set, the input |sentence| needs to be written
# in part... | class RequestType:
# One best result is obtained (default mode)
| MECAB_ONE_BEST = 1
# Set this flag if you want to obtain N best results.
MECAB_NBEST = 2
# Set this flag if you want to enable a partial parsing mode.
# When this flag is set, the input |sentence| needs to be written
# in partial parsing format.
MECAB_PARTIAL = 4
# Set this flag if yo... |
class DictType:
# This is a system dictionary.
MECAB_SYS_DIC = 0
# This is a user dictionary.
MECAB_USR_DIC = 1
# This is a unknown word dictionary.
MECAB_UNK_DIC = 2
class RequestType:
# One best result is obtained (default mode)
| 77 | 77 | 259 | 15 | 61 | lainrose/pecab | mecab/data_structure.py | Python | RequestType | RequestType | 29 | 56 | 29 | 30 | be94ee6754fbe252ae30c43c6b349ecfd8ac6a30 | bigcode/the-stack | train |
bf4084f36508ce7ce90f066a | train | class | class DictType:
# This is a system dictionary.
MECAB_SYS_DIC = 0
# This is a user dictionary.
MECAB_USR_DIC = 1
# This is a unknown word dictionary.
MECAB_UNK_DIC = 2
| class DictType:
# This is a system dictionary.
| MECAB_SYS_DIC = 0
# This is a user dictionary.
MECAB_USR_DIC = 1
# This is a unknown word dictionary.
MECAB_UNK_DIC = 2
| AB_BOS_NODE = 2
# Virtual node representing a end of the sentence.
MECAB_EOS_NODE = 3
# Virtual node representing a end of the N-best enumeration.
MECAB_EON_NODE = 4
class DictType:
# This is a system dictionary.
| 64 | 64 | 61 | 12 | 51 | lainrose/pecab | mecab/data_structure.py | Python | DictType | DictType | 18 | 26 | 18 | 19 | 7e9b850b025bb743948f9627e84ac13273a5c2b8 | bigcode/the-stack | train |
f129354ed0548d70a70edfe7 | train | class | class Node:
# pointer to the previous node.
# python can't access itself. (type of prev is Node*)
prev: object
# pointer to the next node.
# python can't access itself. (type of next is Node*)
next: object
# pointer to the node which ends at the same position.
# python can't access its... | class Node:
# pointer to the previous node.
# python can't access itself. (type of prev is Node*)
| prev: object
# pointer to the next node.
# python can't access itself. (type of next is Node*)
next: object
# pointer to the node which ends at the same position.
# python can't access itself. (type of enext is Node*)
enext: object
# pointer to the node which starts at the same positi... | class Path:
# pointer to the right node
# type of rnode is Node*
rnode: object
# pointer to the next right path
# python can't access itself. (type of rnext is Path*)
rnext: object
# pointer to the left node
# type of lnode is Node*
lnode: object
# pointer to the next left pat... | 154 | 154 | 516 | 25 | 128 | lainrose/pecab | mecab/data_structure.py | Python | Node | Node | 123 | 200 | 123 | 125 | c048cac29ab49e52c608b51d755685697e207f61 | bigcode/the-stack | train |
f3f6d55fde7cbb1c3e82a98c | train | class | class BoundaryConstraintType:
# The token boundary is not specified.
MECAB_ANY_BOUNDARY = 0
# The position is a strong token boundary.
MECAB_TOKEN_BOUNDARY = 1
# The position is not a token boundary.
MECAB_INSIDE_TOKEN = 2
| class BoundaryConstraintType:
# The token boundary is not specified.
| MECAB_ANY_BOUNDARY = 0
# The position is a strong token boundary.
MECAB_TOKEN_BOUNDARY = 1
# The position is not a token boundary.
MECAB_INSIDE_TOKEN = 2
| the lattice.
MECAB_ALL_MORPHS = 32
# When this flag is set, tagger internally copies the body of passed
# sentence into internal buffer.
MECAB_ALLOCATE_SENTENCE = 64
class BoundaryConstraintType:
# The token boundary is not specified.
| 64 | 64 | 64 | 14 | 49 | lainrose/pecab | mecab/data_structure.py | Python | BoundaryConstraintType | BoundaryConstraintType | 59 | 67 | 59 | 60 | 5af5275c50d82ea0ccf3ab1047379fe5180014a0 | bigcode/the-stack | train |
d007e0e2527bcb6814eabaec | train | function | @app.route('/')
def index():
"""Index page of the application."""
return "Hello, World! (from a Docker container)"
| @app.route('/')
def index():
| """Index page of the application."""
return "Hello, World! (from a Docker container)"
| """A basic flask applications"""
import os
from flask import Flask
from flask import Response
from flask import json
app = Flask(__name__)
@app.route('/')
def index():
| 36 | 64 | 27 | 6 | 30 | edeediong/Flask-Pulumi-GitHub-Actions | simple/app.py | Python | index | index | 9 | 12 | 9 | 10 | 20f5ccf2e4cca0524ea92882089f8920ecaa15b6 | bigcode/the-stack | train |
16fca0b8965ae4f9a404ef4f | train | function | @app.route('/cities.json')
def cities():
"""A JSON formatted result."""
data = ["Amsterdam", "San Francisco", "Berlin", "New York"]
resp = Response(json.dumps(data), status=200, mimetype="application/json")
return resp
| @app.route('/cities.json')
def cities():
| """A JSON formatted result."""
data = ["Amsterdam", "San Francisco", "Berlin", "New York"]
resp = Response(json.dumps(data), status=200, mimetype="application/json")
return resp
| basic flask applications"""
import os
from flask import Flask
from flask import Response
from flask import json
app = Flask(__name__)
@app.route('/')
def index():
"""Index page of the application."""
return "Hello, World! (from a Docker container)"
@app.route('/cities.json')
def cities():
| 64 | 64 | 55 | 9 | 55 | edeediong/Flask-Pulumi-GitHub-Actions | simple/app.py | Python | cities | cities | 14 | 19 | 14 | 15 | 8b9eaaf761ce2f1e79c3c050cc343eb21d3bbbec | bigcode/the-stack | train |
a185bf934e249bafbfea2048 | train | function | def crypto_sign_ed25519_pk_to_curve25519(public_key_bytes: bytes) -> bytes:
"""
Converts a public Ed25519 key (encoded as bytes ``public_key_bytes``) to
a public Curve25519 key as bytes.
Raises a ValueError if ``public_key_bytes`` is not of length
``crypto_sign_PUBLICKEYBYTES``
:param public_k... | def crypto_sign_ed25519_pk_to_curve25519(public_key_bytes: bytes) -> bytes:
| """
Converts a public Ed25519 key (encoded as bytes ``public_key_bytes``) to
a public Curve25519 key as bytes.
Raises a ValueError if ``public_key_bytes`` is not of length
``crypto_sign_PUBLICKEYBYTES``
:param public_key_bytes: bytes
:rtype: bytes
"""
if len(public_key_bytes) != cr... | message_len, signed, len(signed), pk)
!= 0
):
raise exc.BadSignatureError("Signature was forged or corrupt")
return ffi.buffer(message, message_len[0])[:]
def crypto_sign_ed25519_pk_to_curve25519(public_key_bytes: bytes) -> bytes:
| 64 | 64 | 211 | 20 | 43 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign_ed25519_pk_to_curve25519 | crypto_sign_ed25519_pk_to_curve25519 | 111 | 133 | 111 | 111 | 22ac033b55deff2806deba136988a9f4c53f01f7 | bigcode/the-stack | train |
36e9bffb4ac2b330d5101c7c | train | class | class crypto_sign_ed25519ph_state:
"""
State object wrapping the sha-512 state used in ed25519ph computation
"""
__slots__ = ["state"]
def __init__(self) -> None:
self.state: bytes = ffi.new(
"unsigned char[]", crypto_sign_ed25519ph_STATEBYTES
)
rc = lib.crypto... | class crypto_sign_ed25519ph_state:
| """
State object wrapping the sha-512 state used in ed25519ph computation
"""
__slots__ = ["state"]
def __init__(self) -> None:
self.state: bytes = ffi.new(
"unsigned char[]", crypto_sign_ed25519ph_STATEBYTES
)
rc = lib.crypto_sign_ed25519ph_init(self.state)
... | :param secret_key_bytes: bytes
:rtype: bytes
"""
if len(secret_key_bytes) != crypto_sign_SECRETKEYBYTES:
raise exc.ValueError("Invalid secret key")
return secret_key_bytes[:crypto_sign_SEEDBYTES]
class crypto_sign_ed25519ph_state:
| 64 | 64 | 107 | 9 | 55 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign_ed25519ph_state | crypto_sign_ed25519ph_state | 195 | 209 | 195 | 195 | 48b4bb94fe0c9a6ac3236d201a1c7ebb9131513f | bigcode/the-stack | train |
2250a498d1d3d90be4806077 | train | function | def crypto_sign_ed25519ph_final_verify(
edph: crypto_sign_ed25519ph_state, signature: bytes, pk: bytes
) -> bool:
"""
Verify a prehashed signature using the public key pk
:param edph: the ed25519ph state for the data
being verified
:type edph: crypto_sign_ed25519ph_state
:param... | def crypto_sign_ed25519ph_final_verify(
edph: crypto_sign_ed25519ph_state, signature: bytes, pk: bytes
) -> bool:
| """
Verify a prehashed signature using the public key pk
:param edph: the ed25519ph state for the data
being verified
:type edph: crypto_sign_ed25519ph_state
:param signature: the signature being verified
:type signature: bytes
:param pk: the ed25519 public part of the sign... | raising=exc.TypeError,
)
signature = ffi.new("unsigned char[]", crypto_sign_BYTES)
rc = lib.crypto_sign_ed25519ph_final_create(
edph.state, signature, ffi.NULL, sk
)
ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
return ffi.buffer(signature, crypto_sign_BYTES)[:]... | 113 | 113 | 379 | 34 | 78 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign_ed25519ph_final_verify | crypto_sign_ed25519ph_final_verify | 279 | 327 | 279 | 281 | 164e2c64d8d159d0b4fa05b885e3f3009858e0a0 | bigcode/the-stack | train |
924e3e2fdf5b0d7937fe4a39 | train | function | def crypto_sign_seed_keypair(seed: bytes) -> Tuple[bytes, bytes]:
"""
Computes and returns the public key and secret key using the seed ``seed``.
:param seed: bytes
:rtype: (bytes(public_key), bytes(secret_key))
"""
if len(seed) != crypto_sign_SEEDBYTES:
raise exc.ValueError("Invalid se... | def crypto_sign_seed_keypair(seed: bytes) -> Tuple[bytes, bytes]:
| """
Computes and returns the public key and secret key using the seed ``seed``.
:param seed: bytes
:rtype: (bytes(public_key), bytes(secret_key))
"""
if len(seed) != crypto_sign_SEEDBYTES:
raise exc.ValueError("Invalid seed")
pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYT... | 0, "Unexpected library error", raising=exc.RuntimeError)
return (
ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
)
def crypto_sign_seed_keypair(seed: bytes) -> Tuple[bytes, bytes]:
| 64 | 64 | 179 | 17 | 47 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign_seed_keypair | crypto_sign_seed_keypair | 50 | 69 | 50 | 50 | 89fd6a1c32eb93492bc937abc735e98fdfe8d280 | bigcode/the-stack | train |
ac03eb6490846eb9b0771b8f | train | function | def crypto_sign_ed25519ph_update(
edph: crypto_sign_ed25519ph_state, pmsg: bytes
) -> None:
"""
Update the hash state wrapped in edph
:param edph: the ed25519ph state being updated
:type edph: crypto_sign_ed25519ph_state
:param pmsg: the partial message
:type pmsg: bytes
:rtype: None
... | def crypto_sign_ed25519ph_update(
edph: crypto_sign_ed25519ph_state, pmsg: bytes
) -> None:
| """
Update the hash state wrapped in edph
:param edph: the ed25519ph state being updated
:type edph: crypto_sign_ed25519ph_state
:param pmsg: the partial message
:type pmsg: bytes
:rtype: None
"""
ensure(
isinstance(edph, crypto_sign_ed25519ph_state),
"edph parameter... | )
rc = lib.crypto_sign_ed25519ph_init(self.state)
ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
def crypto_sign_ed25519ph_update(
edph: crypto_sign_ed25519ph_state, pmsg: bytes
) -> None:
| 64 | 64 | 207 | 30 | 34 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign_ed25519ph_update | crypto_sign_ed25519ph_update | 212 | 235 | 212 | 214 | cd08c4a7f7d07401a9f1009eaf91909cbbcfb5da | bigcode/the-stack | train |
69acc48e431362d1c4a693ba | train | function | def crypto_sign_ed25519_sk_to_curve25519(secret_key_bytes: bytes) -> bytes:
"""
Converts a secret Ed25519 key (encoded as bytes ``secret_key_bytes``) to
a secret Curve25519 key as bytes.
Raises a ValueError if ``secret_key_bytes``is not of length
``crypto_sign_SECRETKEYBYTES``
:param secret_ke... | def crypto_sign_ed25519_sk_to_curve25519(secret_key_bytes: bytes) -> bytes:
| """
Converts a secret Ed25519 key (encoded as bytes ``secret_key_bytes``) to
a secret Curve25519 key as bytes.
Raises a ValueError if ``secret_key_bytes``is not of length
``crypto_sign_SECRETKEYBYTES``
:param secret_key_bytes: bytes
:rtype: bytes
"""
if len(secret_key_bytes) != cry... | curve_public_key, public_key_bytes
)
ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
return ffi.buffer(curve_public_key, curve_public_key_len)[:]
def crypto_sign_ed25519_sk_to_curve25519(secret_key_bytes: bytes) -> bytes:
| 64 | 64 | 211 | 20 | 43 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign_ed25519_sk_to_curve25519 | crypto_sign_ed25519_sk_to_curve25519 | 136 | 158 | 136 | 136 | 3105c40bf041efd247170025dd4a68ccd6e6a7a9 | bigcode/the-stack | train |
856845f5642fbb43301abddb | train | function | def crypto_sign_ed25519ph_final_create(
edph: crypto_sign_ed25519ph_state, sk: bytes
) -> bytes:
"""
Create a signature for the data hashed in edph
using the secret key sk
:param edph: the ed25519ph state for the data
being signed
:type edph: crypto_sign_ed25519ph_state
:pa... | def crypto_sign_ed25519ph_final_create(
edph: crypto_sign_ed25519ph_state, sk: bytes
) -> bytes:
| """
Create a signature for the data hashed in edph
using the secret key sk
:param edph: the ed25519ph state for the data
being signed
:type edph: crypto_sign_ed25519ph_state
:param sk: the ed25519 secret part of the signing key
:type sk: bytes
:return: ed25519ph signatu... | , bytes),
"pmsg parameter must be a bytes object",
raising=exc.TypeError,
)
rc = lib.crypto_sign_ed25519ph_update(edph.state, pmsg, len(pmsg))
ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
def crypto_sign_ed25519ph_final_create(
edph: crypto_sign_ed25519ph_state, ... | 93 | 93 | 312 | 30 | 63 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign_ed25519ph_final_create | crypto_sign_ed25519ph_final_create | 238 | 276 | 238 | 240 | aa64ed9685777d687f707ca34f5b1bfc2e6d3052 | bigcode/the-stack | train |
59b8143b94a9e84f8f657236 | train | function | def crypto_sign(message: bytes, sk: bytes) -> bytes:
"""
Signs the message ``message`` using the secret key ``sk`` and returns the
signed message.
:param message: bytes
:param sk: bytes
:rtype: bytes
"""
signed = ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES)
signed_le... | def crypto_sign(message: bytes, sk: bytes) -> bytes:
| """
Signs the message ``message`` using the secret key ``sk`` and returns the
signed message.
:param message: bytes
:param sk: bytes
:rtype: bytes
"""
signed = ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES)
signed_len = ffi.new("unsigned long long *")
rc = lib.cry... | ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
return (
ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
)
def crypto_sign(message: bytes, sk: bytes) -> bytes:
| 64 | 64 | 141 | 14 | 50 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign | crypto_sign | 72 | 87 | 72 | 72 | 2d8e75c7ca10da040d55e94dc541d17afcd8b9f4 | bigcode/the-stack | train |
8c0462f6f39b58676d744317 | train | function | def crypto_sign_keypair() -> Tuple[bytes, bytes]:
"""
Returns a randomly generated public key and secret key.
:rtype: (bytes(public_key), bytes(secret_key))
"""
pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)
rc = lib.... | def crypto_sign_keypair() -> Tuple[bytes, bytes]:
| """
Returns a randomly generated public key and secret key.
:rtype: (bytes(public_key), bytes(secret_key))
"""
pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)
rc = lib.crypto_sign_keypair(pk, sk)
ensure(rc == 0, "U... | KEYBYTES: int = lib.crypto_sign_secretkeybytes()
crypto_sign_curve25519_BYTES: int = lib.crypto_box_secretkeybytes()
crypto_sign_ed25519ph_STATEBYTES: int = lib.crypto_sign_ed25519ph_statebytes()
def crypto_sign_keypair() -> Tuple[bytes, bytes]:
| 64 | 64 | 138 | 13 | 51 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign_keypair | crypto_sign_keypair | 32 | 47 | 32 | 32 | b45c999000ae140c85d3ffc02633b078d9326b71 | bigcode/the-stack | train |
0b9ef1740764effd49f5c462 | train | function | def crypto_sign_ed25519_sk_to_pk(secret_key_bytes: bytes) -> bytes:
"""
Extract the public Ed25519 key from a secret Ed25519 key (encoded
as bytes ``secret_key_bytes``).
Raises a ValueError if ``secret_key_bytes``is not of length
``crypto_sign_SECRETKEYBYTES``
:param secret_key_bytes: bytes
... | def crypto_sign_ed25519_sk_to_pk(secret_key_bytes: bytes) -> bytes:
| """
Extract the public Ed25519 key from a secret Ed25519 key (encoded
as bytes ``secret_key_bytes``).
Raises a ValueError if ``secret_key_bytes``is not of length
``crypto_sign_SECRETKEYBYTES``
:param secret_key_bytes: bytes
:rtype: bytes
"""
if len(secret_key_bytes) != crypto_sign_... | (
curve_secret_key, secret_key_bytes
)
ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
return ffi.buffer(curve_secret_key, curve_secret_key_len)[:]
def crypto_sign_ed25519_sk_to_pk(secret_key_bytes: bytes) -> bytes:
| 64 | 64 | 128 | 18 | 45 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign_ed25519_sk_to_pk | crypto_sign_ed25519_sk_to_pk | 161 | 175 | 161 | 161 | e3f9ec9b7328d58a999446c50c713552de2934bb | bigcode/the-stack | train |
ba3a1a9d9483fcb3930030a0 | train | function | def crypto_sign_open(signed: bytes, pk: bytes) -> bytes:
"""
Verifies the signature of the signed message ``signed`` using the public
key ``pk`` and returns the unsigned message.
:param signed: bytes
:param pk: bytes
:rtype: bytes
"""
message = ffi.new("unsigned char[]", len(signed))
... | def crypto_sign_open(signed: bytes, pk: bytes) -> bytes:
| """
Verifies the signature of the signed message ``signed`` using the public
key ``pk`` and returns the unsigned message.
:param signed: bytes
:param pk: bytes
:rtype: bytes
"""
message = ffi.new("unsigned char[]", len(signed))
message_len = ffi.new("unsigned long long *")
if (... | lib.crypto_sign(signed, signed_len, message, len(message), sk)
ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
return ffi.buffer(signed, signed_len[0])[:]
def crypto_sign_open(signed: bytes, pk: bytes) -> bytes:
| 64 | 64 | 147 | 16 | 47 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign_open | crypto_sign_open | 90 | 108 | 90 | 90 | 4c0ac715e3081eae86e3d5a70201cbeb0e9c998e | bigcode/the-stack | train |
82668a507f130e1701c153c0 | train | function | def crypto_sign_ed25519_sk_to_seed(secret_key_bytes: bytes) -> bytes:
"""
Extract the seed from a secret Ed25519 key (encoded
as bytes ``secret_key_bytes``).
Raises a ValueError if ``secret_key_bytes``is not of length
``crypto_sign_SECRETKEYBYTES``
:param secret_key_bytes: bytes
:rtype: by... | def crypto_sign_ed25519_sk_to_seed(secret_key_bytes: bytes) -> bytes:
| """
Extract the seed from a secret Ed25519 key (encoded
as bytes ``secret_key_bytes``).
Raises a ValueError if ``secret_key_bytes``is not of length
``crypto_sign_SECRETKEYBYTES``
:param secret_key_bytes: bytes
:rtype: bytes
"""
if len(secret_key_bytes) != crypto_sign_SECRETKEYBYTES... | :rtype: bytes
"""
if len(secret_key_bytes) != crypto_sign_SECRETKEYBYTES:
raise exc.ValueError("Invalid secret key")
return secret_key_bytes[crypto_sign_SEEDBYTES:]
def crypto_sign_ed25519_sk_to_seed(secret_key_bytes: bytes) -> bytes:
| 63 | 64 | 124 | 18 | 45 | isabella232/pynacl | src/nacl/bindings/crypto_sign.py | Python | crypto_sign_ed25519_sk_to_seed | crypto_sign_ed25519_sk_to_seed | 178 | 192 | 178 | 178 | c37dea682d9ffcc957b11c2c2aed63657643579b | bigcode/the-stack | train |
705f18298f6c6709a13c2067 | train | function | @borg.on(admin_cmd(pattern=r"decode$", outgoing=True))
async def parseqr(qr_e):
""" For .decode command, get QR Code/BarCode content from the replied photo. """
downloaded_file_name = await qr_e.client.download_media(
await qr_e.get_reply_message())
# klanraloosh @aaaDa @telethon
command_to_exec... | @borg.on(admin_cmd(pattern=r"decode$", outgoing=True))
async def parseqr(qr_e):
| """ For .decode command, get QR Code/BarCode content from the replied photo. """
downloaded_file_name = await qr_e.client.download_media(
await qr_e.get_reply_message())
# klanraloosh @aaaDa @telethon
command_to_exec = [
"curl", "-X", "POST", "-F", "f=@" + downloaded_file_name + "",
... | related to QR Codes. """
import os
import asyncio
import time
from datetime import datetime
import qrcode
import barcode
from barcode.writer import ImageWriter
from bs4 import BeautifulSoup
from userbot import CMD_HELP
from userbot.utils import admin_cmd
@borg.on(admin_cmd(pattern=r"decode$", outgoing=True))
async ... | 77 | 77 | 257 | 21 | 55 | vv65/ae.thon | userbot/plugins/Decode_berlin.py | Python | parseqr | parseqr | 18 | 46 | 18 | 19 | e1b29785206ed2313a266b9302add67bc3cd09b4 | bigcode/the-stack | train |
b41fae58ad12650e6f80d955 | train | function | @borg.on(admin_cmd(pattern=r"makeqr(?: |$)([\s\S]*)", outgoing=True))
async def make_qr(makeqr):
""" For .makeqr command, make a QR Code containing the given content. """
input_str = makeqr.pattern_match.group(1)
message = "SYNTAX: `.makeqr <long text to include>`"
reply_msg_id = None
if input_str:
... | @borg.on(admin_cmd(pattern=r"makeqr(?: |$)([\s\S]*)", outgoing=True))
async def make_qr(makeqr):
| """ For .makeqr command, make a QR Code containing the given content. """
input_str = makeqr.pattern_match.group(1)
message = "SYNTAX: `.makeqr <long text to include>`"
reply_msg_id = None
if input_str:
message = input_str
elif makeqr.reply_to_msg_id:
previous_message = await mak... | =reply_msg_id,
)
os.remove(filename)
except Exception as e:
await event.edit(str(e))
return
end = datetime.now()
ms = (end - start).seconds
await event.edit("Created BarCode in {} seconds".format(ms))
await asyncio.sleep(5)
await event.delete()
@borg.on(admin_cmd(... | 101 | 101 | 337 | 30 | 71 | vv65/ae.thon | userbot/plugins/Decode_berlin.py | Python | make_qr | make_qr | 99 | 137 | 99 | 100 | aacc581bb30b13d2befae6541928d3a3217dae4d | bigcode/the-stack | train |
b2a8e0ff430aec1b862d9397 | train | function | @borg.on(admin_cmd(pattern="barcode ?(.*)"))
async def _(event):
if event.fwd_from:
return
await event.edit("...")
start = datetime.now()
input_str = event.pattern_match.group(1)
message = "SYNTAX: `.barcode <long text to include>`"
reply_msg_id = event.message.id
if input_str:
... | @borg.on(admin_cmd(pattern="barcode ?(.*)"))
async def _(event):
| if event.fwd_from:
return
await event.edit("...")
start = datetime.now()
input_str = event.pattern_match.group(1)
message = "SYNTAX: `.barcode <long text to include>`"
reply_msg_id = event.message.id
if input_str:
message = input_str
elif event.reply_to_msg_id:
pr... | ()
e_response = stderr.decode().strip()
t_response = stdout.decode().strip()
os.remove(downloaded_file_name)
if not t_response:
logger.info(e_response)
logger.info(t_response)
await qr_e.edit("Failed to decode.")
return
soup = BeautifulSoup(t_response, "html.parser")
... | 111 | 111 | 371 | 18 | 93 | vv65/ae.thon | userbot/plugins/Decode_berlin.py | Python | _ | _ | 49 | 97 | 49 | 50 | a49e3c6274d854dd93ecdac131906f4c0a2d80bc | bigcode/the-stack | train |
09e79bb865b86eb411a820f9 | train | class | class WebhookSaltAPIHandler(SaltAPIHandler): # pylint: disable=W0223
'''
A generic web hook entry point that fires an event on Salt's event bus
External services can POST data to this URL to trigger an event in Salt.
For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks.
.. note::... | class WebhookSaltAPIHandler(SaltAPIHandler): # pylint: disable=W0223
| '''
A generic web hook entry point that fires an event on Salt's event bus
External services can POST data to this URL to trigger an event in Salt.
For example, Amazon SNS, Jenkins-CI or Travis-CI, or GitHub web hooks.
.. note:: Be mindful of security
Salt's Reactor can run any code. A Re... | 08995", "return": true, "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2014-01-12_01:01:49.819316", "fun": "test.ping", "id": "jerry"}}
'''
# if you aren't authenticated, redirect to login
if not self._verify_auth():
self.redirect('/login')
return
# s... | 256 | 256 | 1,305 | 20 | 235 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | WebhookSaltAPIHandler | WebhookSaltAPIHandler | 1,581 | 1,741 | 1,581 | 1,581 | 4f828ef49024a2121ea7db569cf4749f10ec952e | bigcode/the-stack | train |
4094fab9e535c8bb0e14cf13 | train | class | class SaltAPIHandler(BaseSaltAPIHandler): # pylint: disable=W0223
'''
Main API handler for base "/"
'''
def get(self):
'''
An endpoint to determine salt-api capabilities
.. http:get:: /
:reqheader Accept: |req_accept|
:status 200: |200|
:st... | class SaltAPIHandler(BaseSaltAPIHandler): # pylint: disable=W0223
| '''
Main API handler for base "/"
'''
def get(self):
'''
An endpoint to determine salt-api capabilities
.. http:get:: /
:reqheader Accept: |req_accept|
:status 200: |200|
:status 401: |401|
:status 406: |406|
**Example r... | _groups = set(token['groups'])
eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')])
for group in user_groups & eauth_groups:
perms.extend(eauth['{0}%'.format(group)])
perms = sorted(list(set(perms)))
# If we can't find the... | 256 | 256 | 2,893 | 18 | 238 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | SaltAPIHandler | SaltAPIHandler | 786 | 1,151 | 786 | 786 | 0142987059c7fcb14d09f415897e4f96ca783060 | bigcode/the-stack | train |
516ec8ec610838f4ceb1f522 | train | function | def _json_dumps(obj, **kwargs):
'''
Invoke salt.utils.json.dumps using the alternate json module loaded using
salt.utils.json.import_json(). This ensures that we properly encode any
strings in the object before we perform the serialization.
'''
return salt.utils.json.dumps(obj, _json_module=json... | def _json_dumps(obj, **kwargs):
| '''
Invoke salt.utils.json.dumps using the alternate json module loaded using
salt.utils.json.import_json(). This ensures that we properly encode any
strings in the object before we perform the serialization.
'''
return salt.utils.json.dumps(obj, _json_module=json, **kwargs)
| import salt.runner
import salt.auth
from salt.exceptions import (
AuthenticationError,
AuthorizationError,
EauthAuthenticationError
)
salt.utils.zeromq.install_zmq()
json = salt.utils.json.import_json()
log = logging.getLogger(__name__)
def _json_dumps(obj, **kwargs):
| 64 | 64 | 70 | 10 | 54 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | _json_dumps | _json_dumps | 230 | 236 | 230 | 230 | 1d958f173114c0922ffeec2f96c90ca77e3f185e | bigcode/the-stack | train |
fc067d4dfc45d0ac26311cc8 | train | class | class Any(Future):
'''
Future that wraps other futures to "block" until one is done
'''
def __init__(self, futures): # pylint: disable=E1002
super(Any, self).__init__()
for future in futures:
future.add_done_callback(self.done_callback)
def done_callback(self, future):
... | class Any(Future):
| '''
Future that wraps other futures to "block" until one is done
'''
def __init__(self, futures): # pylint: disable=E1002
super(Any, self).__init__()
for future in futures:
future.add_done_callback(self.done_callback)
def done_callback(self, future):
# Any is co... | local_async" (done)
# # master side
# - "runner" (done)
# - "wheel" (need asynchronous api...)
AUTH_TOKEN_HEADER = 'X-Auth-Token'
AUTH_COOKIE_NAME = 'session_id'
class TimeoutException(Exception):
pass
class Any(Future):
| 64 | 64 | 105 | 5 | 58 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | Any | Any | 257 | 269 | 257 | 257 | 3e1e1024130559760eeb3e32b89b94ae00b463dc | bigcode/the-stack | train |
a18939fb337f86392cda04f2 | train | class | class EventsSaltAPIHandler(SaltAPIHandler): # pylint: disable=W0223
'''
Expose the Salt event bus
The event bus on the Salt master exposes a large variety of things, notably
when executions are started on the master and also when minions ultimately
return their results. This URL provides a real-ti... | class EventsSaltAPIHandler(SaltAPIHandler): # pylint: disable=W0223
| '''
Expose the Salt event bus
The event bus on the Salt master exposes a large variety of things, notably
when executions are started on the master and also when minions ultimately
return their results. This URL provides a real-time window into a running
Salt infrastructure.
.. seealso:: :... | 8000/run \\
-H 'Accept: application/x-yaml' \\
-d client='local' \\
-d tgt='*' \\
-d fun='test.ping' \\
-d username='saltdev' \\
-d password='saltdev' \\
-d eauth='pam'
.. code-block:: text
... | 256 | 256 | 1,169 | 19 | 237 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | EventsSaltAPIHandler | EventsSaltAPIHandler | 1,453 | 1,578 | 1,453 | 1,453 | d8dae2f6760b97ce05b4bc75176c8c11b4ac2ea1 | bigcode/the-stack | train |
ab43bfdd72e24245ababb104 | train | class | class EventListener(object):
'''
Class responsible for listening to the salt master event bus and updating
futures. This is the core of what makes this asynchronous, this allows us to do
non-blocking work in the main processes and "wait" for an event to happen
'''
def __init__(self, mod_opts, o... | class EventListener(object):
| '''
Class responsible for listening to the salt master event bus and updating
futures. This is the core of what makes this asynchronous, this allows us to do
non-blocking work in the main processes and "wait" for an event to happen
'''
def __init__(self, mod_opts, opts):
self.mod_opts =... | encode any
strings in the object before we perform the serialization.
'''
return salt.utils.json.dumps(obj, _json_module=json, **kwargs)
# The clients rest_cherrypi supports. We want to mimic the interface, but not
# necessarily use the same API under the hood
# # all of these require coordinating min... | 256 | 256 | 932 | 5 | 251 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | EventListener | EventListener | 272 | 398 | 272 | 272 | 0f91e76eff17ac000b61aa57130a69d54d09356c | bigcode/the-stack | train |
c03b77fa44104f8cae13060e | train | class | class TimeoutException(Exception):
pass
| class TimeoutException(Exception):
| pass
| " (done)
# - "local_async" (done)
# # master side
# - "runner" (done)
# - "wheel" (need asynchronous api...)
AUTH_TOKEN_HEADER = 'X-Auth-Token'
AUTH_COOKIE_NAME = 'session_id'
class TimeoutException(Exception):
| 64 | 64 | 8 | 5 | 59 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | TimeoutException | TimeoutException | 253 | 254 | 253 | 253 | 221cd0e4f099b4b0c86ee1ee4b8e2dbd4ce7329a | bigcode/the-stack | train |
a6fcde5b464279565151e5d9 | train | class | class SaltAuthHandler(BaseSaltAPIHandler): # pylint: disable=W0223
'''
Handler for login requests
'''
def get(self):
'''
All logins are done over post, this is a parked endpoint
.. http:get:: /login
:status 401: |401|
:status 406: |406|
**Examp... | class SaltAuthHandler(BaseSaltAPIHandler): # pylint: disable=W0223
| '''
Handler for login requests
'''
def get(self):
'''
All logins are done over post, this is a parked endpoint
.. http:get:: /login
:status 401: |401|
:status 406: |406|
**Example request:**
.. code-block:: bash
curl -i loc... |
def set_default_headers(self):
'''
Set default CORS headers
'''
mod_opts = self.application.mod_opts
if mod_opts.get('cors_origin'):
origin = self.request.headers.get('Origin')
allowed_origin = _check_cors_origin(origin, mod_opts['cors_origin'])
... | 256 | 256 | 1,171 | 18 | 238 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | SaltAuthHandler | SaltAuthHandler | 614 | 783 | 614 | 614 | ad785a080602c252dfd970fb327578d05c98b323 | bigcode/the-stack | train |
10aae05fe2b5cc8cfa37ff74 | train | class | class JobsSaltAPIHandler(SaltAPIHandler): # pylint: disable=W0223
'''
A convenience endpoint for job cache data
'''
@tornado.web.asynchronous
def get(self, jid=None): # pylint: disable=W0221
'''
A convenience URL for getting lists of previously run jobs or getting
the retur... | class JobsSaltAPIHandler(SaltAPIHandler): # pylint: disable=W0223
| '''
A convenience endpoint for job cache data
'''
@tornado.web.asynchronous
def get(self, jid=None): # pylint: disable=W0221
'''
A convenience URL for getting lists of previously run jobs or getting
the return from a single job
.. http:get:: /jobs/(jid)
... | '
minions: [ms-4, ms-3, ms-2, ms-1, ms-0]
'''
# if you aren't authenticated, redirect to login
if not self._verify_auth():
self.redirect('/login')
return
# verify that all lowstates are the correct client type
for low in self.lowstate:
... | 185 | 185 | 618 | 19 | 166 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | JobsSaltAPIHandler | JobsSaltAPIHandler | 1,283 | 1,386 | 1,283 | 1,283 | efe938e834d2acb5700adaa66bb8b200e615ae77 | bigcode/the-stack | train |
d2cab80b2411a1ce185bfbba | train | function | def _check_cors_origin(origin, allowed_origins):
'''
Check if an origin match cors allowed origins
'''
if isinstance(allowed_origins, list):
if origin in allowed_origins:
return origin
elif allowed_origins == '*':
return allowed_origins
elif allowed_origins == origin:... | def _check_cors_origin(origin, allowed_origins):
| '''
Check if an origin match cors allowed origins
'''
if isinstance(allowed_origins, list):
if origin in allowed_origins:
return origin
elif allowed_origins == '*':
return allowed_origins
elif allowed_origins == origin:
# Cors origin is either * or specific or... | # is a dictionary. We must cast this as
# a dictionary in order for msgpack to
# serialize it.
'headers': dict(self.request.headers),
}, tag)
self.write(self.serialize({'success': ret}))
def _check_cors_origin(origin, allowed_origins):
| 63 | 64 | 87 | 12 | 51 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | _check_cors_origin | _check_cors_origin | 1,744 | 1,755 | 1,744 | 1,744 | 87f4ea780945e22ea87dfc76d4eb905fc36c81af | bigcode/the-stack | train |
764124aec3e65c84b268a585 | train | class | class BaseSaltAPIHandler(tornado.web.RequestHandler): # pylint: disable=W0223
ct_out_map = (
('application/json', _json_dumps),
('application/x-yaml', salt.utils.yaml.safe_dump),
)
def _verify_client(self, low):
'''
Verify that the client is in fact one we have
'''
... | class BaseSaltAPIHandler(tornado.web.RequestHandler): # pylint: disable=W0223
| ct_out_map = (
('application/json', _json_dumps),
('application/x-yaml', salt.utils.yaml.safe_dump),
)
def _verify_client(self, low):
'''
Verify that the client is in fact one we have
'''
if 'client' not in low or low.get('client') not in self.saltclients:
... | _exception(TimeoutException())
self.tag_map[(tag, matcher)].remove(future)
if len(self.tag_map[(tag, matcher)]) == 0:
del self.tag_map[(tag, matcher)]
def _handle_event_socket_recv(self, raw):
'''
Callback for events on the event sub socket
'''
mtag, ... | 256 | 256 | 1,440 | 20 | 236 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | BaseSaltAPIHandler | BaseSaltAPIHandler | 401 | 611 | 401 | 401 | 6d39d0d5b39dd7b6813f8b2c2eee055bc1a5994f | bigcode/the-stack | train |
d9ccc2abbb60310820b5eeb6 | train | class | class MinionSaltAPIHandler(SaltAPIHandler): # pylint: disable=W0223
'''
A convenience endpoint for minion related functions
'''
@tornado.web.asynchronous
def get(self, mid=None): # pylint: disable=W0221
'''
A convenience URL for getting lists of minions or getting minion
de... | class MinionSaltAPIHandler(SaltAPIHandler): # pylint: disable=W0223
| '''
A convenience endpoint for minion related functions
'''
@tornado.web.asynchronous
def get(self, mid=None): # pylint: disable=W0221
'''
A convenience URL for getting lists of minions or getting minion
details
.. http:get:: /minions/(mid)
:reqheader X... | clients['runner'](chunk)
tag = pub_data['tag'] + '/ret'
try:
event = yield self.application.event_listener.get_event(self, tag=tag)
# only return the return data
ret = event if full_return else event['data']['return']
raise tornado.gen.Return(ret)
... | 246 | 246 | 820 | 20 | 225 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | MinionSaltAPIHandler | MinionSaltAPIHandler | 1,154 | 1,280 | 1,154 | 1,154 | 76cdeb1ad2eb5c02c14ee8cf0c70ad37ac7f2535 | bigcode/the-stack | train |
628ca2a753a7b2485f966dd2 | train | class | class RunSaltAPIHandler(SaltAPIHandler): # pylint: disable=W0223
'''
Endpoint to run commands without normal session handling
'''
@tornado.web.asynchronous
def post(self):
'''
Run commands bypassing the :ref:`normal session handling
<rest_cherrypy-auth>`
.. http:pos... | class RunSaltAPIHandler(SaltAPIHandler): # pylint: disable=W0223
| '''
Endpoint to run commands without normal session handling
'''
@tornado.web.asynchronous
def post(self):
'''
Run commands bypassing the :ref:`normal session handling
<rest_cherrypy-auth>`
.. http:post:: /run
This entry point is primarily for "one-off" ... | 6.9141387939453125e-06
'''
# if you aren't authenticated, redirect to login
if not self._verify_auth():
self.redirect('/login')
return
if jid:
self.lowstate = [{
'fun': 'jobs.list_job',
'jid': jid,
'cli... | 129 | 129 | 433 | 19 | 110 | yosnoop/salt | salt/netapi/rest_tornado/saltnado.py | Python | RunSaltAPIHandler | RunSaltAPIHandler | 1,389 | 1,450 | 1,389 | 1,389 | 3604eb9dbd7cda4360179db5ad15c48196d57e41 | bigcode/the-stack | train |
da6315df519d9df80701950c | train | function | def __move_fig(fig, width=None, height=None, offset_x=None, offset_y=None):
"""
Move figure's upper left corner to pixel (x, y)
Coordinate system starts in upper left corner of the monitor
"""
# Get the current position of the figure 'fig_width_inch'x'height'+'offset_x'+'offset_y'
current_geome... | def __move_fig(fig, width=None, height=None, offset_x=None, offset_y=None):
| """
Move figure's upper left corner to pixel (x, y)
Coordinate system starts in upper left corner of the monitor
"""
# Get the current position of the figure 'fig_width_inch'x'height'+'offset_x'+'offset_y'
current_geometry = fig.canvas.manager.window.wm_geometry()
c_width, current_geometry ... | position '{}', "
"Choose from: 'top', 'bottom', 'left', 'right', "
"'top left', 'top right', 'bottom left', 'bottom right'".format(position_str))
def __move_fig(fig, width=None, height=None, offset_x=None, offset_y=None):
| 64 | 64 | 208 | 20 | 44 | DDDong2666/tum-adlr-ws20-02 | wzk/mpl/move_figure.py | Python | __move_fig | __move_fig | 107 | 128 | 107 | 107 | db7a4340eb731f2ab2d139f3e067eaab84f1b499 | bigcode/the-stack | train |
6f46333124717762b26854d2 | train | function | def __position_string_wrapper(position_str='top right'):
"""
Convert the string into the format n_rows, n_cols, index
"""
if position_str == 'full':
return 1, 1, 1
elif position_str == 'top':
return 2, 1, 1
elif position_str == 'bottom':
return 2, 1, 2
elif position... | def __position_string_wrapper(position_str='top right'):
| """
Convert the string into the format n_rows, n_cols, index
"""
if position_str == 'full':
return 1, 1, 1
elif position_str == 'top':
return 2, 1, 1
elif position_str == 'bottom':
return 2, 1, 2
elif position_str == 'left':
return 1, 2, 1
elif position_... | ravel_index(index-1, dims=(n_rows, n_cols))
offset_x *= fig_width
offset_y *= fig_height
offset_x += offset_x_monitors
__move_fig(fig, width=fig_width, height=fig_height, offset_x=offset_x, offset_y=offset_y)
def __position_string_wrapper(position_str='top right'):
| 77 | 77 | 259 | 11 | 66 | DDDong2666/tum-adlr-ws20-02 | wzk/mpl/move_figure.py | Python | __position_string_wrapper | __position_string_wrapper | 76 | 104 | 76 | 76 | 5e1ce4edd63eb6676183d2bd99ccd8fe269c97a2 | bigcode/the-stack | train |
6e71b5ee469867b63c93b094 | train | function | def move_fig(fig, position=None, monitor=-1):
"""
FROM
http://stackoverflow.com/questions/7449585/how-do-you-set-the-absolute-position-of-figure-windows-with-matplotlib#19943546
With small change regarding the display resolution
Move and resize a window to a set of standard positions on the screen.
... | def move_fig(fig, position=None, monitor=-1):
| """
FROM
http://stackoverflow.com/questions/7449585/how-do-you-set-the-absolute-position-of-figure-windows-with-matplotlib#19943546
With small change regarding the display resolution
Move and resize a window to a set of standard positions on the screen.
Possible positions are:
top, bottom, l... |
monitors = [[1440, 900]]
if screeninfo is not None:
try:
monitors = [(m.fig_width_inch, m.height) for m in screeninfo.get_monitors()]
except screeninfo.common.ScreenInfoError:
# Fallback for my mac
# monitors = [[2560, 1600]]
monitors = [[1440, 900]]
# from screeninf... | 148 | 149 | 497 | 12 | 136 | DDDong2666/tum-adlr-ws20-02 | wzk/mpl/move_figure.py | Python | move_fig | move_fig | 21 | 73 | 21 | 21 | 81f75c6dab2154610293881a6ee6a63dc3b06e44 | bigcode/the-stack | train |
7239f3e00b06e8c326d812bb | train | function | def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument("--model_type", default=None, type=str, required=True,
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()))
parser.add_argument("--model_name_or_path", default=None, t... | def main():
| parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument("--model_type", default=None, type=str, required=True,
help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()))
parser.add_argument("--model_name_or_path", default=None, type=str, req... | .barrier() # Make sure only the first process in distributed training process the dataset,
# and the others will use the cache
# Convert to Tensors and build dataset
all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
all_input_mask = torch.tensor([f.input_mask for f in... | 256 | 256 | 2,745 | 3 | 252 | yumere/for-QuAC | bert_coqa_order.py | Python | main | main | 474 | 691 | 474 | 474 | 49591055f5b5acd2961de5dfe75917b118db8d83 | bigcode/the-stack | train |
8d289635ac8e1757177e7c41 | train | function | def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False):
if args.local_rank not in [-1, 0] and not evaluate:
torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset,
# and the others will use the cache
# Load data f... | def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=False):
| if args.local_rank not in [-1, 0] and not evaluate:
torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset,
# and the others will use the cache
# Load data features from cache or dataset file
input_file = args.predict_file if evaluate els... | model.config.end_n_top,
tokenizer, args.verbose_logging)
else:
pred, nbest_pred = write_predictions(examples, features, all_results, args.n_best_size,
args.max_answer_length, args.do_lower_case, output_prediction_file,
... | 175 | 175 | 586 | 16 | 158 | yumere/for-QuAC | bert_coqa_order.py | Python | load_and_cache_examples | load_and_cache_examples | 421 | 471 | 421 | 421 | 9cccee3bec35554a1a800e48d98498d80ec0660d | bigcode/the-stack | train |
b138926d2dbf288c1ca4c197 | train | function | def to_list(tensor):
return tensor.detach().cpu().tolist()
| def to_list(tensor):
| return tensor.detach().cpu().tolist()
| param = param.data
cur_params[name].copy_(param)
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def to_list(tensor):
| 64 | 64 | 15 | 6 | 58 | yumere/for-QuAC | bert_coqa_order.py | Python | to_list | to_list | 208 | 209 | 208 | 208 | e3f0eeb173637c84e2064a78acfc229a4f62f4a7 | bigcode/the-stack | train |
a0008e791ebcc389147d223c | train | class | class GeLU(nn.Module):
def __init__(self):
super(GeLU, self).__init__()
def forward(self, x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
| class GeLU(nn.Module):
| def __init__(self):
super(GeLU, self).__init__()
def forward(self, x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
| (BertConfig, BertForQuestionAnswering, BertTokenizer),
'xlnet': (XLNetConfig, XLNetForQuestionAnswering, XLNetTokenizer),
'xlm': (XLMConfig, XLMForQuestionAnswering, XLMTokenizer),
}
class GeLU(nn.Module):
| 64 | 64 | 70 | 6 | 58 | yumere/for-QuAC | bert_coqa_order.py | Python | GeLU | GeLU | 66 | 71 | 66 | 66 | 023b687d3e1c84b181113e899f8c3a447833b3c0 | bigcode/the-stack | train |
92c25ff24353330f31b8f015 | train | class | class CoQABaseline(BertPreTrainedModel):
def __init__(self, config):
super(BertPreTrainedModel, self).__init__(config)
self.num_labels = config.num_labels
self.bert = BertModel(config)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
self.class_outputs = nn... | class CoQABaseline(BertPreTrainedModel):
| def __init__(self, config):
super(BertPreTrainedModel, self).__init__(config)
self.num_labels = config.num_labels
self.bert = BertModel(config)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
self.class_outputs = nn.Linear(config.hidden_size, 4)
s... | .stack(outputs, dim=1)
return probs
def create_read_module(self, in_features, hidden_size, out_features, n_layer=1):
in_layer = nn.Sequential(nn.BatchNorm1d(in_features), nn.Linear(in_features, hidden_size), GeLU())
inner_layer = nn.Sequential(nn.BatchNorm1d(hidden_size), nn.Linear(hidden_... | 177 | 177 | 592 | 13 | 164 | yumere/for-QuAC | bert_coqa_order.py | Python | CoQABaseline | CoQABaseline | 139 | 197 | 139 | 139 | 098f538e94f396f4bd676e96355e8c5f097f5f23 | bigcode/the-stack | train |
3c527a87752d84a2c025b601 | train | function | def train(args, train_dataset, model, tokenizer):
""" Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter()
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedS... | def train(args, train_dataset, model, tokenizer):
| """ Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter()
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset)
train_dataloader = DataL... | _index)
loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
class_loss_fct = nn.CrossEntropyLoss(ignore_index=3)
class_loss = class_loss_fct(class_logi... | 256 | 256 | 1,431 | 11 | 245 | yumere/for-QuAC | bert_coqa_order.py | Python | train | train | 212 | 339 | 212 | 212 | 656cb133b590fb294a5cd9030944557525f144c2 | bigcode/the-stack | train |
3d23e819a9672000ff7e264d | train | class | class OrderNet(nn.Module):
def __init__(self, in_features, read_hidden_size, read_out_features, rnn_hidden_size, dropout, attn_dropout):
super(OrderNet, self).__init__()
self.rnn_hidden_size = rnn_hidden_size
self.read = self.create_read_module(in_features, read_hidden_size, read_out_featur... | class OrderNet(nn.Module):
| def __init__(self, in_features, read_hidden_size, read_out_features, rnn_hidden_size, dropout, attn_dropout):
super(OrderNet, self).__init__()
self.rnn_hidden_size = rnn_hidden_size
self.read = self.create_read_module(in_features, read_hidden_size, read_out_features, 1)
self.encode... | .utils import coqa_performance
from coqa_baselines.utils_coqa import (read_coqa_examples, convert_examples_to_features,
RawResult, write_predictions, write_predictions_extended)
logger = logging.getLogger(__name__)
ALL_MODELS = sum((tuple(conf.pretrained_config_archive_map.keys(... | 223 | 224 | 749 | 6 | 217 | yumere/for-QuAC | bert_coqa_order.py | Python | OrderNet | OrderNet | 74 | 136 | 74 | 74 | 1bc4026d62a6646f4db875e05fae2ab26a7b9b0f | bigcode/the-stack | train |
3db9c887a03abc3c06980a58 | train | function | def evaluate(args, model, tokenizer, prefix=""):
dataset, examples, features = load_and_cache_examples(args, tokenizer, evaluate=True, output_examples=True)
if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:
os.makedirs(args.output_dir)
args.eval_batch_size = args.per_gpu_eval_... | def evaluate(args, model, tokenizer, prefix=""):
| dataset, examples, features = load_and_cache_examples(args, tokenizer, evaluate=True, output_examples=True)
if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:
os.makedirs(args.output_dir)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
# Note that D... | args.save_steps > 0 and global_step % args.save_steps == 0:
# Save model checkpoint
output_dir = os.path.join(args.output_dir, 'checkpoint-{}'.format(global_step))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
... | 248 | 249 | 831 | 11 | 237 | yumere/for-QuAC | bert_coqa_order.py | Python | evaluate | evaluate | 346 | 418 | 346 | 346 | f37fc8eaed4a17465f4a480420b989ce25c94f2b | bigcode/the-stack | train |
971e1f20566a8718d1195e68 | train | function | def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
| def set_seed(args):
| random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
| _order_weight(self, order_params):
cur_params = self.state_dict()
for name, param in order_params.items():
if name not in cur_params:
continue
if isinstance(param, nn.Parameter):
param = param.data
cur_params[name].copy_(param)
def set_... | 64 | 64 | 43 | 5 | 59 | yumere/for-QuAC | bert_coqa_order.py | Python | set_seed | set_seed | 200 | 205 | 200 | 200 | e5cb32f488d8aa4cf6a0ee4ace9ea07425ab973c | bigcode/the-stack | train |
2f97c264367c4059ce238aa4 | train | function | def delete(tweetjs_path, until_date, filters, s, min_l, min_r, dry_run=False):
with io.open(tweetjs_path, mode="r", encoding="utf-8") as tweetjs_file:
count = 0
api = twitter.Api(consumer_key=os.environ["TWITTER_CONSUMER_KEY"],
consumer_secret=os.environ["TWITTER_CONSUMER_... | def delete(tweetjs_path, until_date, filters, s, min_l, min_r, dry_run=False):
| with io.open(tweetjs_path, mode="r", encoding="utf-8") as tweetjs_file:
count = 0
api = twitter.Api(consumer_key=os.environ["TWITTER_CONSUMER_KEY"],
consumer_secret=os.environ["TWITTER_CONSUMER_SECRET"],
access_token_key=os.environ["TWITTER_ACCESS... | _count")) >= self.min_likes) or \
(self.min_retweets > 0 and int(row.get("retweet_count")) >= self.min_retweets):
continue
yield row
def delete(tweetjs_path, until_date, filters, s, min_l, min_r, dry_run=False):
| 64 | 64 | 190 | 23 | 40 | vlaship/delete-tweets | deletetweets/deletetweets.py | Python | delete | delete | 60 | 77 | 60 | 60 | 88b3117600b3d2f075d5706d63be5b5ebf7b32a0 | bigcode/the-stack | train |
fcf4cdf17bce726ff27c949b | train | class | class TweetReader(object):
def __init__(self, reader, until_date=None, filters=[], spare=[], min_likes=0, min_retweets=0):
self.reader = reader
self.until_date = datetime.now() if until_date is None else parser.parse(until_date, ignoretz=True)
self.filters = filters
self.spare = spar... | class TweetReader(object):
| def __init__(self, reader, until_date=None, filters=[], spare=[], min_likes=0, min_retweets=0):
self.reader = reader
self.until_date = datetime.now() if until_date is None else parser.parse(until_date, ignoretz=True)
self.filters = filters
self.spare = spare
self.min_likes = ... | (self, tweet_id):
try:
print("delete tweet %s" % tweet_id)
if not self.dry_run:
self.twitter_api.DestroyStatus(tweet_id)
# NOTE: A poor man's solution to honor Twitter's rate limits.
time.sleep(0.5)
except twitter.TwitterError as err:
... | 87 | 87 | 291 | 5 | 82 | vlaship/delete-tweets | deletetweets/deletetweets.py | Python | TweetReader | TweetReader | 28 | 57 | 28 | 28 | a9203943ac2309556c3c5e520651d05981519e7d | bigcode/the-stack | train |
2bd17b710f7e1fc144376653 | train | class | class TweetDestroyer(object):
def __init__(self, twitter_api, dry_run=False):
self.twitter_api = twitter_api
self.dry_run = dry_run
def destroy(self, tweet_id):
try:
print("delete tweet %s" % tweet_id)
if not self.dry_run:
self.twitter_api.Destroy... | class TweetDestroyer(object):
| def __init__(self, twitter_api, dry_run=False):
self.twitter_api = twitter_api
self.dry_run = dry_run
def destroy(self, tweet_id):
try:
print("delete tweet %s" % tweet_id)
if not self.dry_run:
self.twitter_api.DestroyStatus(tweet_id)
#... | import io
import os
import sys
import time
import json
import twitter
from datetime import datetime
from dateutil import parser
class TweetDestroyer(object):
| 35 | 64 | 122 | 6 | 28 | vlaship/delete-tweets | deletetweets/deletetweets.py | Python | TweetDestroyer | TweetDestroyer | 12 | 25 | 12 | 12 | e451cb8643b949ace440ca80b9dd94e5e4e74302 | bigcode/the-stack | train |
679c5bf40a296493f741fc90 | train | class | @final
class GCSimple(GCStrategy):
"""The GCSimple Strategy."""
def reap(self, pointer: Pointer) -> None:
"""
Send a message to delete the remote object.
Args:
pointer (Pointer): Pointer that indicates to an object
that should get deleted
Re... | @final
class GCSimple(GCStrategy):
| """The GCSimple Strategy."""
def reap(self, pointer: Pointer) -> None:
"""
Send a message to delete the remote object.
Args:
pointer (Pointer): Pointer that indicates to an object
that should get deleted
Return:
None
"""
... | heuritics."""
# third party
from typing_extensions import final
# syft relative
from ...node.common.action.garbage_collect_object_action import (
GarbageCollectObjectAction,
)
from ..pointer import Pointer
from .gc_strategy import GCStrategy
@final
class GCSimple(GCStrategy):
| 64 | 64 | 124 | 11 | 52 | exityan/PySyft | packages/syft/src/syft/core/pointer/garbage_collection/gc_simple.py | Python | GCSimple | GCSimple | 13 | 35 | 13 | 14 | b8d5c142b4346e450564ac53f9a8c29b2294f08e | bigcode/the-stack | train |
2641e53698ace4792c877b86 | train | class | class TestReportFrequency(unittest.TestCase):
"""ReportFrequency unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testReportFrequency(self):
"""Test ReportFrequency"""
# FIXME: construct object with mandatory attributes with example values
... | class TestReportFrequency(unittest.TestCase):
| """ReportFrequency unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testReportFrequency(self):
"""Test ReportFrequency"""
# FIXME: construct object with mandatory attributes with example values
# model = swagger_client.models.report_frequen... |
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.models.report_frequency import ReportFrequency # noqa: E501
from swagger_client.rest import ApiException
class TestReportFrequency(unittest.Test... | 64 | 64 | 83 | 8 | 55 | pdeardorff-r7/vm-console-client-python | test/test_report_frequency.py | Python | TestReportFrequency | TestReportFrequency | 23 | 36 | 23 | 23 | a517133a9133b63887c01fb8c806c00504c93f77 | bigcode/the-stack | train |
d47d9e2ccaba83667693f7b8 | train | function | def ParseXML(img_folder, file):
for xml_file in glob.glob(img_folder+'/*.xml'):
tree=ET.parse(open(xml_file))
root = tree.getroot()
image_name = root.find('filename').text
img_path = img_folder+'/'+image_name
for i, obj in enumerate(root.iter('object')):
difficult... | def ParseXML(img_folder, file):
| for xml_file in glob.glob(img_folder+'/*.xml'):
tree=ET.parse(open(xml_file))
root = tree.getroot()
image_name = root.find('filename').text
img_path = img_folder+'/'+image_name
for i, obj in enumerate(root.iter('object')):
difficult = obj.find('difficult').text
... | os.chdir("..")
data_dir = '/custom_dataset/'
Dataset_names_path = "model_data/deer_names.txt"
Dataset_train = "model_data/deer_train.txt"
Dataset_test = "model_data/deer_test.txt"
is_subfolder = False
Dataset_names = []
def ParseXML(img_folder, file):
| 64 | 65 | 217 | 8 | 56 | Pradeep-Gopal/yolo_deer_people_final_project | yolov3_tiny_deer_detection/tools/XML_to_YOLOv3.py | Python | ParseXML | ParseXML | 18 | 38 | 18 | 18 | b3dd8ae925fa9bc5015909f9f64610074832dc26 | bigcode/the-stack | train |
6689c7a0ad18b1eae66739ad | train | function | def run_XML_to_YOLOv3():
for i, folder in enumerate(['train','test']):
with open([Dataset_train,Dataset_test][i], "w") as file:
print(os.getcwd()+data_dir+folder)
img_path = os.path.join(os.getcwd()+data_dir+folder)
if is_subfolder:
for directory in os.lis... | def run_XML_to_YOLOv3():
| for i, folder in enumerate(['train','test']):
with open([Dataset_train,Dataset_test][i], "w") as file:
print(os.getcwd()+data_dir+folder)
img_path = os.path.join(os.getcwd()+data_dir+folder)
if is_subfolder:
for directory in os.listdir(img_path):
... | (xmlbox.find('xmax').text)))+','
+str(int(float(xmlbox.find('ymax').text)))+','
+str(cls_id))
img_path += ' '+OBJECT
print(img_path)
file.write(img_path+'\n')
def run_XML_to_YOLOv3():
| 64 | 64 | 150 | 10 | 54 | Pradeep-Gopal/yolo_deer_people_final_project | yolov3_tiny_deer_detection/tools/XML_to_YOLOv3.py | Python | run_XML_to_YOLOv3 | run_XML_to_YOLOv3 | 40 | 55 | 40 | 40 | 346a3315e8e8fa75e78bdf9556d546932be1f45b | bigcode/the-stack | train |
7a079bf1e550afcaac9b3bce | train | class | class IPsecPoliciesTab(tabs.TableTab, htables.DataTableView):
table_classes = (tables.IPsecPoliciesTable,)
name = _("IPsec Policies")
slug = "ipsecpolicies"
template_name = ("horizon/common/_detail_table.html")
def get_ipsecpoliciestable_data(self):
try:
filters = self.get_filte... | class IPsecPoliciesTab(tabs.TableTab, htables.DataTableView):
| table_classes = (tables.IPsecPoliciesTable,)
name = _("IPsec Policies")
slug = "ipsecpolicies"
template_name = ("horizon/common/_detail_table.html")
def get_ipsecpoliciestable_data(self):
try:
filters = self.get_filters()
tenant_id = self.request.user.tenant_id
... | = self._tables['ikepoliciestable']
self.handle_server_filter(self.request, table=self.table)
self.update_server_filter_action(self.request, table=self.table)
return super(IKEPoliciesTab, self).get_filters()
class IPsecPoliciesTab(tabs.TableTab, htables.DataTableView):
| 64 | 64 | 214 | 16 | 48 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | IPsecPoliciesTab | IPsecPoliciesTab | 169 | 192 | 169 | 169 | c088694e46f55c602808cc69108cbef765e925c0 | bigcode/the-stack | train |
3fc841ff69806717a0cbf8ed | train | class | class IPsecPolicyDetailsTab(tabs.Tab):
name = _("IPsec Policy Details")
slug = "ipsecpolicydetails"
template_name = "project/vpn/_ipsecpolicy_details.html"
def get_context_data(self, request):
ipsecpolicy = self.tab_group.kwargs['ipsecpolicy']
return {'ipsecpolicy': ipsecpolicy}
| class IPsecPolicyDetailsTab(tabs.Tab):
| name = _("IPsec Policy Details")
slug = "ipsecpolicydetails"
template_name = "project/vpn/_ipsecpolicy_details.html"
def get_context_data(self, request):
ipsecpolicy = self.tab_group.kwargs['ipsecpolicy']
return {'ipsecpolicy': ipsecpolicy}
| , request):
ikepolicy = self.tab_group.kwargs['ikepolicy']
return {'ikepolicy': ikepolicy}
class IKEPolicyDetailsTabs(tabs.TabGroup):
slug = "ikepolicytabs"
tabs = (IKEPolicyDetailsTab,)
class IPsecPolicyDetailsTab(tabs.Tab):
| 63 | 64 | 81 | 10 | 53 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | IPsecPolicyDetailsTab | IPsecPolicyDetailsTab | 218 | 225 | 218 | 218 | e270abbe304e56bdfb557dc96ae85e82f55533ff | bigcode/the-stack | train |
c95d2e9c71012d424e19cdcb | train | class | class VPNTabs(tabs.TabGroup):
slug = "vpntabs"
tabs = (IKEPoliciesTab, IPsecPoliciesTab,
VPNServicesTab, EndpointGroupTab,
IPsecSiteConnectionsTab,)
sticky = True
| class VPNTabs(tabs.TabGroup):
| slug = "vpntabs"
tabs = (IKEPoliciesTab, IPsecPoliciesTab,
VPNServicesTab, EndpointGroupTab,
IPsecSiteConnectionsTab,)
sticky = True
| _filters(self):
self.table = self._tables['ipsecpoliciestable']
self.handle_server_filter(self.request, table=self.table)
self.update_server_filter_action(self.request, table=self.table)
return super(IPsecPoliciesTab, self).get_filters()
class VPNTabs(tabs.TabGroup):
| 64 | 64 | 52 | 9 | 55 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | VPNTabs | VPNTabs | 195 | 200 | 195 | 195 | 4bc6b22a040d712075f4ea92d920baefcc0e19d7 | bigcode/the-stack | train |
f66c6ed8054e1282735ef03b | train | class | class IPsecPolicyDetailsTabs(tabs.TabGroup):
slug = "ipsecpolicytabs"
tabs = (IPsecPolicyDetailsTab,)
| class IPsecPolicyDetailsTabs(tabs.TabGroup):
| slug = "ipsecpolicytabs"
tabs = (IPsecPolicyDetailsTab,)
| "
template_name = "project/vpn/_ipsecpolicy_details.html"
def get_context_data(self, request):
ipsecpolicy = self.tab_group.kwargs['ipsecpolicy']
return {'ipsecpolicy': ipsecpolicy}
class IPsecPolicyDetailsTabs(tabs.TabGroup):
| 64 | 64 | 30 | 11 | 53 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | IPsecPolicyDetailsTabs | IPsecPolicyDetailsTabs | 228 | 230 | 228 | 228 | f0d4af38531e7ba41a7deb51ce94dca0b391eb40 | bigcode/the-stack | train |
c48f06629f221dbb83aa5d1d | train | class | class EndpointGroupTab(tabs.TableTab, htables.DataTableView):
table_classes = (tables.EndpointGroupTable,)
name = _("Endpoint Groups")
slug = "endpointgroups"
template_name = ("horizon/common/_detail_table.html")
def get_endpointgroupstable_data(self):
try:
filters = self.get_fi... | class EndpointGroupTab(tabs.TableTab, htables.DataTableView):
| table_classes = (tables.EndpointGroupTable,)
name = _("Endpoint Groups")
slug = "endpointgroups"
template_name = ("horizon/common/_detail_table.html")
def get_endpointgroupstable_data(self):
try:
filters = self.get_filters()
tenant_id = self.request.user.tenant_id
... | = self._tables['vpnservicestable']
self.handle_server_filter(self.request, table=self.table)
self.update_server_filter_action(self.request, table=self.table)
return super(VPNServicesTab, self).get_filters()
class EndpointGroupTab(tabs.TableTab, htables.DataTableView):
| 64 | 64 | 196 | 15 | 49 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | EndpointGroupTab | EndpointGroupTab | 117 | 140 | 117 | 117 | 6ca9375050186bd015cb7b8b98f31261241f4a54 | bigcode/the-stack | train |
03b730dc37cb8c39188c9cea | train | class | class IKEPolicyDetailsTabs(tabs.TabGroup):
slug = "ikepolicytabs"
tabs = (IKEPolicyDetailsTab,)
| class IKEPolicyDetailsTabs(tabs.TabGroup):
| slug = "ikepolicytabs"
tabs = (IKEPolicyDetailsTab,)
| = "ikepolicydetails"
template_name = "project/vpn/_ikepolicy_details.html"
def get_context_data(self, request):
ikepolicy = self.tab_group.kwargs['ikepolicy']
return {'ikepolicy': ikepolicy}
class IKEPolicyDetailsTabs(tabs.TabGroup):
| 64 | 64 | 28 | 11 | 53 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | IKEPolicyDetailsTabs | IKEPolicyDetailsTabs | 213 | 215 | 213 | 213 | 9d40ee5de29c586eaf344a1c78def725577232ee | bigcode/the-stack | train |
343e27f41784468eca2e1f83 | train | class | class IKEPolicyDetailsTab(tabs.Tab):
name = _("IKE Policy Details")
slug = "ikepolicydetails"
template_name = "project/vpn/_ikepolicy_details.html"
def get_context_data(self, request):
ikepolicy = self.tab_group.kwargs['ikepolicy']
return {'ikepolicy': ikepolicy}
| class IKEPolicyDetailsTab(tabs.Tab):
| name = _("IKE Policy Details")
slug = "ikepolicydetails"
template_name = "project/vpn/_ikepolicy_details.html"
def get_context_data(self, request):
ikepolicy = self.tab_group.kwargs['ikepolicy']
return {'ikepolicy': ikepolicy}
| _filters()
class VPNTabs(tabs.TabGroup):
slug = "vpntabs"
tabs = (IKEPoliciesTab, IPsecPoliciesTab,
VPNServicesTab, EndpointGroupTab,
IPsecSiteConnectionsTab,)
sticky = True
class IKEPolicyDetailsTab(tabs.Tab):
| 64 | 64 | 73 | 10 | 53 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | IKEPolicyDetailsTab | IKEPolicyDetailsTab | 203 | 210 | 203 | 203 | 826ed9534c548a2a8034e2b9409711f38669bb6b | bigcode/the-stack | train |
98f04eef87d9c091f291558f | train | class | class EndpointGroupDetailsTabs(tabs.TabGroup):
slug = "endpointgrouptabs"
tabs = (EndpointGroupDetailsTab,)
| class EndpointGroupDetailsTabs(tabs.TabGroup):
| slug = "endpointgrouptabs"
tabs = (EndpointGroupDetailsTab,)
| ")
slug = "endpointgroupdetails"
template_name = "project/vpn/_endpointgroup_details.html"
def get_context_data(self, request):
endpointgroup = self.tab_group.kwargs['endpointgroup']
return {'endpointgroup': endpointgroup}
class EndpointGroupDetailsTabs(tabs.TabGroup):
| 64 | 64 | 29 | 10 | 54 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | EndpointGroupDetailsTabs | EndpointGroupDetailsTabs | 258 | 260 | 258 | 258 | ac6bf6057600b29d93b58b144061c96f1bf95452 | bigcode/the-stack | train |
ecbdcff8d0ab313c6e9df5b8 | train | class | class VPNServicesTab(tabs.TableTab, htables.DataTableView):
table_classes = (tables.VPNServicesTable,)
name = _("VPN Services")
slug = "vpnservices"
template_name = ("horizon/common/_detail_table.html")
def get_vpnservicestable_data(self):
try:
filters = self.get_filters()
... | class VPNServicesTab(tabs.TableTab, htables.DataTableView):
| table_classes = (tables.VPNServicesTable,)
name = _("VPN Services")
slug = "vpnservices"
template_name = ("horizon/common/_detail_table.html")
def get_vpnservicestable_data(self):
try:
filters = self.get_filters()
tenant_id = self.request.user.tenant_id
i... | self.tab_group.request,
_('Unable to retrieve IPsec site connections list.'))
return ipsecsiteconnections
def get_filters(self):
self.table = self._tables['ipsecsiteconnectionstable']
self.handle_server_filter(self.request, table=self.table)
self.update_server_filte... | 107 | 107 | 357 | 16 | 91 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | VPNServicesTab | VPNServicesTab | 74 | 114 | 74 | 74 | 62f2545f5069dbe62c1bf0a5befe7fbb0d6097e4 | bigcode/the-stack | train |
3beb9fd2f31d7f19b421a9b7 | train | class | class VPNServiceDetailsTabs(tabs.TabGroup):
slug = "vpnservicetabs"
tabs = (VPNServiceDetailsTab,)
| class VPNServiceDetailsTabs(tabs.TabGroup):
| slug = "vpnservicetabs"
tabs = (VPNServiceDetailsTab,)
| slug = "vpnservicedetails"
template_name = "project/vpn/_vpnservice_details.html"
def get_context_data(self, request):
vpnservice = self.tab_group.kwargs['vpnservice']
return {'vpnservice': vpnservice}
class VPNServiceDetailsTabs(tabs.TabGroup):
| 64 | 64 | 29 | 10 | 54 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | VPNServiceDetailsTabs | VPNServiceDetailsTabs | 243 | 245 | 243 | 243 | e3613ac579b770c27a462cd516fd374bf5b5499a | bigcode/the-stack | train |
39140de1c9bec25d6ea30783 | train | class | class IKEPoliciesTab(tabs.TableTab, htables.DataTableView):
table_classes = (tables.IKEPoliciesTable,)
name = _("IKE Policies")
slug = "ikepolicies"
template_name = ("horizon/common/_detail_table.html")
def get_ikepoliciestable_data(self):
try:
filters = self.get_filters()
... | class IKEPoliciesTab(tabs.TableTab, htables.DataTableView):
| table_classes = (tables.IKEPoliciesTable,)
name = _("IKE Policies")
slug = "ikepolicies"
template_name = ("horizon/common/_detail_table.html")
def get_ikepoliciestable_data(self):
try:
filters = self.get_filters()
tenant_id = self.request.user.tenant_id
i... | .table = self._tables['endpointgroupstable']
self.handle_server_filter(self.request, table=self.table)
self.update_server_filter_action(self.request, table=self.table)
return super(EndpointGroupTab, self).get_filters()
class IKEPoliciesTab(tabs.TableTab, htables.DataTableView):
| 64 | 64 | 207 | 16 | 48 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | IKEPoliciesTab | IKEPoliciesTab | 143 | 166 | 143 | 143 | 7e41c23c9ba37e3bed4e17dcaedc9de75bd7c4cb | bigcode/the-stack | train |
5d2a0d61fb5c68754daed981 | train | class | class IPsecSiteConnectionsTab(tabs.TableTab, htables.DataTableView):
table_classes = (tables.IPsecSiteConnectionsTable,)
name = _("IPsec Site Connections")
slug = "ipsecsiteconnections"
template_name = ("horizon/common/_detail_table.html")
FILTERS_MAPPING = {'admin_state_up': {_("up"): True, _("down... | class IPsecSiteConnectionsTab(tabs.TableTab, htables.DataTableView):
| table_classes = (tables.IPsecSiteConnectionsTable,)
name = _("IPsec Site Connections")
slug = "ipsecsiteconnections"
template_name = ("horizon/common/_detail_table.html")
FILTERS_MAPPING = {'admin_state_up': {_("up"): True, _("down"): False}}
def get_ipsecsiteconnectionstable_data(self):
... | is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from ho... | 131 | 131 | 438 | 17 | 113 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | IPsecSiteConnectionsTab | IPsecSiteConnectionsTab | 27 | 71 | 27 | 27 | 3e336f13d3e41eaa66f29a94f5e6460eeb7d7819 | bigcode/the-stack | train |
4f8e3c63c19c33ab024c1e3a | train | class | class IPsecSiteConnectionDetailsTabs(tabs.TabGroup):
slug = "ipsecsiteconnectiontabs"
tabs = (IPsecSiteConnectionDetailsTab,)
| class IPsecSiteConnectionDetailsTabs(tabs.TabGroup):
| slug = "ipsecsiteconnectiontabs"
tabs = (IPsecSiteConnectionDetailsTab,)
| = "project/vpn/_ipsecsiteconnection_details.html"
def get_context_data(self, request):
ipsecsiteconnection = self.tab_group.kwargs['ipsecsiteconnection']
return {'ipsecsiteconnection': ipsecsiteconnection}
class IPsecSiteConnectionDetailsTabs(tabs.TabGroup):
| 64 | 64 | 33 | 12 | 52 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | IPsecSiteConnectionDetailsTabs | IPsecSiteConnectionDetailsTabs | 273 | 275 | 273 | 273 | 9d226707d69352f54060abf4927d9f0814da5131 | bigcode/the-stack | train |
f5a3533a04ffe296739267b3 | train | class | class EndpointGroupDetailsTab(tabs.Tab):
name = _("Endpoint Groups Details")
slug = "endpointgroupdetails"
template_name = "project/vpn/_endpointgroup_details.html"
def get_context_data(self, request):
endpointgroup = self.tab_group.kwargs['endpointgroup']
return {'endpointgroup': endpo... | class EndpointGroupDetailsTab(tabs.Tab):
| name = _("Endpoint Groups Details")
slug = "endpointgroupdetails"
template_name = "project/vpn/_endpointgroup_details.html"
def get_context_data(self, request):
endpointgroup = self.tab_group.kwargs['endpointgroup']
return {'endpointgroup': endpointgroup}
| , request):
vpnservice = self.tab_group.kwargs['vpnservice']
return {'vpnservice': vpnservice}
class VPNServiceDetailsTabs(tabs.TabGroup):
slug = "vpnservicetabs"
tabs = (VPNServiceDetailsTab,)
class EndpointGroupDetailsTab(tabs.Tab):
| 63 | 64 | 70 | 9 | 54 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | EndpointGroupDetailsTab | EndpointGroupDetailsTab | 248 | 255 | 248 | 248 | d990b618b26fffc50a42635d36b9e094fa128977 | bigcode/the-stack | train |
6b51279d39a8378851ad3bdb | train | class | class IPsecSiteConnectionDetailsTab(tabs.Tab):
name = _("IPsec Site Connection Details")
slug = "ipsecsiteconnectiondetails"
template_name = "project/vpn/_ipsecsiteconnection_details.html"
def get_context_data(self, request):
ipsecsiteconnection = self.tab_group.kwargs['ipsecsiteconnection']
... | class IPsecSiteConnectionDetailsTab(tabs.Tab):
| name = _("IPsec Site Connection Details")
slug = "ipsecsiteconnectiondetails"
template_name = "project/vpn/_ipsecsiteconnection_details.html"
def get_context_data(self, request):
ipsecsiteconnection = self.tab_group.kwargs['ipsecsiteconnection']
return {'ipsecsiteconnection': ipsecsitec... | ):
endpointgroup = self.tab_group.kwargs['endpointgroup']
return {'endpointgroup': endpointgroup}
class EndpointGroupDetailsTabs(tabs.TabGroup):
slug = "endpointgrouptabs"
tabs = (EndpointGroupDetailsTab,)
class IPsecSiteConnectionDetailsTab(tabs.Tab):
| 63 | 64 | 86 | 11 | 52 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | IPsecSiteConnectionDetailsTab | IPsecSiteConnectionDetailsTab | 263 | 270 | 263 | 263 | 0f4240bdac5e128f14c9c93cee0b8df8fef49e99 | bigcode/the-stack | train |
f2cc18d1b69e6052aa2ad783 | train | class | class VPNServiceDetailsTab(tabs.Tab):
name = _("VPN Service Details")
slug = "vpnservicedetails"
template_name = "project/vpn/_vpnservice_details.html"
def get_context_data(self, request):
vpnservice = self.tab_group.kwargs['vpnservice']
return {'vpnservice': vpnservice}
| class VPNServiceDetailsTab(tabs.Tab):
| name = _("VPN Service Details")
slug = "vpnservicedetails"
template_name = "project/vpn/_vpnservice_details.html"
def get_context_data(self, request):
vpnservice = self.tab_group.kwargs['vpnservice']
return {'vpnservice': vpnservice}
| olicy = self.tab_group.kwargs['ipsecpolicy']
return {'ipsecpolicy': ipsecpolicy}
class IPsecPolicyDetailsTabs(tabs.TabGroup):
slug = "ipsecpolicytabs"
tabs = (IPsecPolicyDetailsTab,)
class VPNServiceDetailsTab(tabs.Tab):
| 63 | 64 | 71 | 9 | 54 | openstack/neutron-vpnaas-dashboard | neutron_vpnaas_dashboard/dashboards/project/vpn/tabs.py | Python | VPNServiceDetailsTab | VPNServiceDetailsTab | 233 | 240 | 233 | 233 | 9dfed3c9893d6ec09cc97aa4859aac125a29cce5 | bigcode/the-stack | train |
2b1ee6d7002d40eaaf4e0fdc | train | class | class DisparateMistreatment(object):
def __init__(
self,
dataframe: pd.DataFrame,
supp_metadata: pd.DataFrame,
metric: str,
column: str,
item_column: str,
prediction_key: str,
):
self._dataframe = dataframe.fillna("-")
self._supp_metadata =... | class DisparateMistreatment(object):
| def __init__(
self,
dataframe: pd.DataFrame,
supp_metadata: pd.DataFrame,
metric: str,
column: str,
item_column: str,
prediction_key: str,
):
self._dataframe = dataframe.fillna("-")
self._supp_metadata = supp_metadata
self._column =... | import pandas as pd
import numpy as np
np.seterr(divide="ignore", invalid="ignore")
from typing import List, Dict, Any
from sklearn.metrics import confusion_matrix
from recsys_fair_metrics.util.util import mean_confidence_interval
import plotly.figure_factory as ff
import plotly.express as px
import plotly.graph_objec... | 91 | 256 | 1,689 | 7 | 84 | marlesson/recsys-fair-metrics | recsys_fair_metrics/fairness/disparate_mistreatment.py | Python | DisparateMistreatment | DisparateMistreatment | 15 | 238 | 15 | 15 | 5d023180530bf7df5891367ac4f97302bb35008b | bigcode/the-stack | train |
8d95c0db9be13671beb5d553 | train | class | class Quota(Model):
"""Describes a quota for or usage details about a resource.
:param current_value: The current value of the quota. If null or missing,
the current value cannot be determined in the context of the request.
:type current_value: float
:param id: The resource ID of the quota object
... | class Quota(Model):
| """Describes a quota for or usage details about a resource.
:param current_value: The current value of the quota. If null or missing,
the current value cannot be determined in the context of the request.
:type current_value: float
:param id: The resource ID of the quota object
:type id: str
... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 88 | 100 | 335 | 5 | 82 | rahulgouthamDOTgs/azure-cli-extensions | src/datamigration/azext_dms/vendored_sdks/datamigration/models/quota.py | Python | Quota | Quota | 15 | 47 | 15 | 15 | 9547ea25b0cc1cda323dacefca1d5d22ccbcaf35 | bigcode/the-stack | train |
def6b9c9ccb8854417b66062 | train | class | class BaseSupersetSchema(Schema):
"""
Extends Marshmallow schema so that we can pass a Model to load
(following marshamallow-sqlalchemy pattern). This is useful
to perform partial model merges on HTTP PUT
"""
__class_model__: Model = None
def __init__(self, **kwargs: Any) -> None:
... | class BaseSupersetSchema(Schema):
| """
Extends Marshmallow schema so that we can pass a Model to load
(following marshamallow-sqlalchemy pattern). This is useful
to perform partial model merges on HTTP PUT
"""
__class_model__: Model = None
def __init__(self, **kwargs: Any) -> None:
self.instance: Optional[Model] = N... | flask_appbuilder import Model
from marshmallow import post_load, pre_load, Schema, ValidationError
from sqlalchemy.orm.exc import NoResultFound
def validate_owner(value: int) -> None:
try:
(
current_app.appbuilder.get_session.query(
current_app.appbuilder.sm.user_model.id
... | 112 | 112 | 374 | 8 | 103 | Altinity/superset | superset/views/base_schemas.py | Python | BaseSupersetSchema | BaseSupersetSchema | 38 | 83 | 38 | 38 | 57bc06a1aa9bf64b9a58c19643ba3e7e0f66fcf4 | bigcode/the-stack | train |
690e1f76ded759fea8525d12 | train | function | def validate_owner(value: int) -> None:
try:
(
current_app.appbuilder.get_session.query(
current_app.appbuilder.sm.user_model.id
)
.filter_by(id=value)
.one()
)
except NoResultFound as ex:
raise ValidationError(f"User {value... | def validate_owner(value: int) -> None:
| try:
(
current_app.appbuilder.get_session.query(
current_app.appbuilder.sm.user_model.id
)
.filter_by(id=value)
.one()
)
except NoResultFound as ex:
raise ValidationError(f"User {value} does not exist") from ex
| , Iterable, List, Mapping, Optional, Sequence, Set, Union
from flask import current_app, g
from flask_appbuilder import Model
from marshmallow import post_load, pre_load, Schema, ValidationError
from sqlalchemy.orm.exc import NoResultFound
def validate_owner(value: int) -> None:
| 64 | 64 | 74 | 10 | 53 | Altinity/superset | superset/views/base_schemas.py | Python | validate_owner | validate_owner | 25 | 35 | 25 | 25 | c6114aa20c7be4a62f6121be33f3f0f4c967f302 | bigcode/the-stack | train |
e8409e77f0bb3494c4dab8ef | train | class | class BaseOwnedSchema(BaseSupersetSchema):
"""
Implements owners validation,pre load and post_load
(to populate the owners field) on Marshmallow schemas
"""
owners_field_name = "owners"
@post_load
def make_object(
self, data: Dict[str, Any], discard: Optional[List[str]] = None
... | class BaseOwnedSchema(BaseSupersetSchema):
| """
Implements owners validation,pre load and post_load
(to populate the owners field) on Marshmallow schemas
"""
owners_field_name = "owners"
@post_load
def make_object(
self, data: Dict[str, Any], discard: Optional[List[str]] = None
) -> Model:
discard = discard or []... | : Schema data payload
:param discard: List of fields to not set on the model
"""
discard = discard or []
if not self.instance:
self.instance = self.__class_model__() # pylint: disable=not-callable
for field in data:
if field not in discard:
... | 92 | 92 | 308 | 9 | 82 | Altinity/superset | superset/views/base_schemas.py | Python | BaseOwnedSchema | BaseOwnedSchema | 86 | 123 | 86 | 86 | eb815c6481629fdff4a9dfe788cd25136da9062c | bigcode/the-stack | train |
7b5ce6e99bd7527a65dba19e | train | class | @abstract
class AbstractSlider(Widget):
""" """
def __init__(self, **kwargs):
if 'start' in kwargs and 'end' in kwargs:
if kwargs['start'] == kwargs['end']:
raise ValueError("Slider 'start' and 'end' cannot be equal.")
super(Widget, self).__init__(**kwargs)
titl... | @abstract
class AbstractSlider(Widget):
| """ """
def __init__(self, **kwargs):
if 'start' in kwargs and 'end' in kwargs:
if kwargs['start'] == kwargs['end']:
raise ValueError("Slider 'start' and 'end' cannot be equal.")
super(Widget, self).__init__(**kwargs)
title = String(default="", help="""
Slid... | """ Various kinds of slider widgets.
"""
from __future__ import absolute_import
from datetime import datetime
import numbers
from ...core.has_props import abstract
from ...core.properties import Bool, Int, Float, String, Date, Enum, Tuple, Instance, Color, Override
from ...core.enums import SliderCallbackPolicy
from... | 107 | 131 | 437 | 9 | 97 | ndepal/bokeh | bokeh/models/widgets/sliders.py | Python | AbstractSlider | AbstractSlider | 17 | 73 | 17 | 18 | 48ff5af2c4884c46cd1ff57515fe5d1ec46597d7 | bigcode/the-stack | train |
215f81a3f405fbb76a112f4c | train | class | class DateSlider(AbstractSlider):
""" Slider-based date selection widget. """
value = Date(help="""
Initial or selected value.
""")
start = Date(help="""
The minimum allowable value.
""")
end = Date(help="""
The maximum allowable value.
""")
step = Int(default=1, help="""... | class DateSlider(AbstractSlider):
| """ Slider-based date selection widget. """
value = Date(help="""
Initial or selected value.
""")
start = Date(help="""
The minimum allowable value.
""")
end = Date(help="""
The maximum allowable value.
""")
step = Int(default=1, help="""
The step between consecutive ... | "
The minimum allowable value.
""")
end = Float(help="""
The maximum allowable value.
""")
step = Float(default=1, help="""
The step between consecutive values.
""")
format = Override(default="0[.]00")
class DateSlider(AbstractSlider):
| 64 | 64 | 96 | 6 | 58 | ndepal/bokeh | bokeh/models/widgets/sliders.py | Python | DateSlider | DateSlider | 117 | 136 | 117 | 117 | 0a7dc1bbfe9310bc576959b5db7817698a8dc84f | bigcode/the-stack | train |
ee50aa3b54a3b2a21ea49540 | train | class | class DateRangeSlider(AbstractSlider):
""" Slider-based date range selection widget. """
@property
def value_as_datetime(self):
''' Convenience property to retrieve the value tuple as a tuple of
datetime objects.
'''
if self.value is None:
return None
v1... | class DateRangeSlider(AbstractSlider):
| """ Slider-based date range selection widget. """
@property
def value_as_datetime(self):
''' Convenience property to retrieve the value tuple as a tuple of
datetime objects.
'''
if self.value is None:
return None
v1, v2 = self.value
if isinstance... | Date(help="""
The minimum allowable value.
""")
end = Date(help="""
The maximum allowable value.
""")
step = Int(default=1, help="""
The step between consecutive values.
""")
format = Override(default="%d %b %Y")
class DateRangeSlider(AbstractSlider):
| 69 | 69 | 230 | 7 | 62 | ndepal/bokeh | bokeh/models/widgets/sliders.py | Python | DateRangeSlider | DateRangeSlider | 138 | 176 | 138 | 138 | 6ae52db605567db67c509b0f88e6b61401ce7983 | bigcode/the-stack | train |
6ebb47674e69953b0e2b8e96 | train | class | class Slider(AbstractSlider):
""" Slider-based number selection widget. """
start = Float(help="""
The minimum allowable value.
""")
end = Float(help="""
The maximum allowable value.
""")
value = Float(help="""
Initial or selected value.
""")
step = Float(default=1, help=... | class Slider(AbstractSlider):
| """ Slider-based number selection widget. """
start = Float(help="""
The minimum allowable value.
""")
end = Float(help="""
The maximum allowable value.
""")
value = Float(help="""
Initial or selected value.
""")
step = Float(default=1, help="""
The step between conse... | )
@error(EQUAL_SLIDER_START_END)
def _check_missing_dimension(self):
if hasattr(self, 'start') and hasattr(self, 'end'):
if self.start == self.end:
return '{!s} with title {!s}'.format(self, self.title)
class Slider(AbstractSlider):
| 64 | 64 | 94 | 5 | 59 | ndepal/bokeh | bokeh/models/widgets/sliders.py | Python | Slider | Slider | 75 | 94 | 75 | 75 | 78b80a97033bff143839ea666f7d372a6e0c4808 | bigcode/the-stack | train |
24d7978a54c1bc1e30b6518a | train | class | class RangeSlider(AbstractSlider):
""" Range-slider based number range selection widget. """
value = Tuple(Float, Float, help="""
Initial or selected range.
""")
start = Float(help="""
The minimum allowable value.
""")
end = Float(help="""
The maximum allowable value.
""")
... | class RangeSlider(AbstractSlider):
| """ Range-slider based number range selection widget. """
value = Tuple(Float, Float, help="""
Initial or selected range.
""")
start = Float(help="""
The minimum allowable value.
""")
end = Float(help="""
The maximum allowable value.
""")
step = Float(default=1, help="""
... | "
The maximum allowable value.
""")
value = Float(help="""
Initial or selected value.
""")
step = Float(default=1, help="""
The step between consecutive values.
""")
format = Override(default="0[.]00")
class RangeSlider(AbstractSlider):
| 64 | 64 | 101 | 6 | 58 | ndepal/bokeh | bokeh/models/widgets/sliders.py | Python | RangeSlider | RangeSlider | 96 | 115 | 96 | 96 | 96f71cc854ade6d680d93d3a1626d9819789bea5 | bigcode/the-stack | train |
15911fb1291e4f55841cba8e | train | class | class PluginLoader():
@staticmethod
def get_extractor(name):
return PluginLoader._import("Extract", "Extract_{0}".format(name))
@staticmethod
def get_converter(name):
return PluginLoader._import("Convert", "Convert_{0}".format(name))
@staticmethod
def get_mode... | class PluginLoader():
@staticmethod
| def get_extractor(name):
return PluginLoader._import("Extract", "Extract_{0}".format(name))
@staticmethod
def get_converter(name):
return PluginLoader._import("Convert", "Convert_{0}".format(name))
@staticmethod
def get_model(name):
return PluginLoader._imp... | import os
class PluginLoader():
@staticmethod
| 11 | 78 | 263 | 8 | 2 | huangjiancong1/faceswap-huang | plugins/PluginLoader.py | Python | PluginLoader | PluginLoader | 3 | 37 | 3 | 4 | ea346318a53499720652a355b9fd91a30b80df75 | bigcode/the-stack | train |
9d2500f4a8de3b2dab95b5af | train | class | class DCganDataset(keras.utils.Sequence):
def __init__(self, train_lines, image_size, batch_size):
super(DCganDataset, self).__init__()
self.train_lines = train_lines
self.train_batches = len(train_lines)
self.image_size = image_size
self.batch_size = batch_size
... | class DCganDataset(keras.utils.Sequence):
| def __init__(self, train_lines, image_size, batch_size):
super(DCganDataset, self).__init__()
self.train_lines = train_lines
self.train_batches = len(train_lines)
self.image_size = image_size
self.batch_size = batch_size
self.global_index = 0
def __len_... | import math
from random import shuffle
import cv2
import keras
import numpy as np
from matplotlib.colors import hsv_to_rgb, rgb_to_hsv
from PIL import Image
class DCganDataset(keras.utils.Sequence):
| 47 | 93 | 312 | 9 | 37 | bubbliiiing/dcgan-keras | utils/dataloader.py | Python | DCganDataset | DCganDataset | 11 | 46 | 11 | 11 | fd05867c0552b77f7871041fc4952a3d56ba4fc6 | bigcode/the-stack | train |
498c3df581a9a64384ff9bf5 | train | function | @app.route("/kilpailjat/delete/<kilpailija_id>", methods=["POST"])
@login_required(role="admin")
def kilpailijat_delete(kilpailija_id):
kilpailija = Kilpailija.query.get(kilpailija_id)
db.session().delete(kilpailija)
db.session().commit()
return redirect(url_for("kilpailijat_index")) | @app.route("/kilpailjat/delete/<kilpailija_id>", methods=["POST"])
@login_required(role="admin")
def kilpailijat_delete(kilpailija_id):
| kilpailija = Kilpailija.query.get(kilpailija_id)
db.session().delete(kilpailija)
db.session().commit()
return redirect(url_for("kilpailijat_index")) | .data
db.session().commit()
return redirect(url_for("kilpailijat_index"))
# Poistetaan kilpailja sen id:n perusteella
@app.route("/kilpailjat/delete/<kilpailija_id>", methods=["POST"])
@login_required(role="admin")
def kilpailijat_delete(kilpailija_id):
| 64 | 64 | 75 | 33 | 30 | tikibeni/windsurf-ranking | application/kilpailijat/views.py | Python | kilpailijat_delete | kilpailijat_delete | 62 | 69 | 62 | 64 | fb035a3e4ce8913f49c15a1c4b64f160672555f4 | bigcode/the-stack | train |
2b9f42b03fca5d139c183f1d | train | function | @app.route("/kilpailijat/", methods=["GET"])
def kilpailijat_index():
return render_template("kilpailijat/list.html", kilpailijat=Kilpailija.query.all(), kilpailijaLinkki=User.kilpailijaLinkki())
| @app.route("/kilpailijat/", methods=["GET"])
def kilpailijat_index():
| return render_template("kilpailijat/list.html", kilpailijat=Kilpailija.query.all(), kilpailijaLinkki=User.kilpailijaLinkki())
| _manager, login_required
from application.auth.models import User
from application.kilpailijat.models import Kilpailija
from application.kilpailijat.forms import KilpailijaForm
# Haetaan kaikki kilpailijat list.html:ään
@app.route("/kilpailijat/", methods=["GET"])
def kilpailijat_index():
| 64 | 64 | 49 | 16 | 47 | tikibeni/windsurf-ranking | application/kilpailijat/views.py | Python | kilpailijat_index | kilpailijat_index | 10 | 12 | 10 | 11 | 784c46f5ef98f2495ed9c40dd4f8483b8d73e292 | bigcode/the-stack | train |
2592f5a07d89b868cc490c84 | train | function | @app.route("/kilpailijat/<kilpailija_id>/", methods=["GET"])
@login_required(role="admin")
def kilpailijat_show(kilpailija_id):
kilpailija = Kilpailija.query.get(kilpailija_id)
return render_template("kilpailijat/edit.html", kilpailija=kilpailija, form=KilpailijaForm(obj=kilpailija))
| @app.route("/kilpailijat/<kilpailija_id>/", methods=["GET"])
@login_required(role="admin")
def kilpailijat_show(kilpailija_id):
| kilpailija = Kilpailija.query.get(kilpailija_id)
return render_template("kilpailijat/edit.html", kilpailija=kilpailija, form=KilpailijaForm(obj=kilpailija))
| /new.html", form=KilpailijaForm())
# Haetaan muokattava kilpailija id:n avulla muokkaamista varten edit.html:ään
@app.route("/kilpailijat/<kilpailija_id>/", methods=["GET"])
@login_required(role="admin")
def kilpailijat_show(kilpailija_id):
| 64 | 64 | 78 | 33 | 30 | tikibeni/windsurf-ranking | application/kilpailijat/views.py | Python | kilpailijat_show | kilpailijat_show | 21 | 25 | 21 | 23 | f6de6210fcb26b943f4ad5ee1bbc918ce6d84d01 | bigcode/the-stack | train |
c87395b1c6dbc933835fea9d | train | function | @app.route("/kilpailijat/<kilpailija_id>/", methods=["POST"])
@login_required(role="admin")
def kilpailijat_edit(kilpailija_id):
form = KilpailijaForm(request.form)
kilpailija = Kilpailija.query.get(kilpailija_id)
if not form.validate():
return render_template("kilpailijat/edit.html", kilpailija=ki... | @app.route("/kilpailijat/<kilpailija_id>/", methods=["POST"])
@login_required(role="admin")
def kilpailijat_edit(kilpailija_id):
| form = KilpailijaForm(request.form)
kilpailija = Kilpailija.query.get(kilpailija_id)
if not form.validate():
return render_template("kilpailijat/edit.html", kilpailija=kilpailija, form=form)
kilpailija.name = form.name.data
kilpailija.sailnumber = form.sailnumber.data
kilpailija.sailcl... | (url_for("kilpailijat_index"))
# Käsitellään lomakkeeseen laitetut tiedot ja muokataan kilpailijan tietoja
@app.route("/kilpailijat/<kilpailija_id>/", methods=["POST"])
@login_required(role="admin")
def kilpailijat_edit(kilpailija_id):
| 64 | 64 | 137 | 33 | 30 | tikibeni/windsurf-ranking | application/kilpailijat/views.py | Python | kilpailijat_edit | kilpailijat_edit | 44 | 59 | 44 | 46 | d689f753d7e671a8a9ba5fe105a24d21e439b5e3 | bigcode/the-stack | train |
70d697bae7dfd9dba1fc307c | train | function | @app.route("/kilpailijat/", methods=["POST"])
@login_required(role="admin")
def kilpailijat_create():
form = KilpailijaForm(request.form)
if not form.validate():
return render_template("kilpailijat/new.html", form=form)
kil = Kilpailija(form.name.data, form.sailnumber.data, form.sailclub.data)
... | @app.route("/kilpailijat/", methods=["POST"])
@login_required(role="admin")
def kilpailijat_create():
| form = KilpailijaForm(request.form)
if not form.validate():
return render_template("kilpailijat/new.html", form=form)
kil = Kilpailija(form.name.data, form.sailnumber.data, form.sailclub.data)
db.session().add(kil)
db.session().commit()
return redirect(url_for("kilpailijat_index"))
| ", kilpailija=kilpailija, form=KilpailijaForm(obj=kilpailija))
# Haetaan syötetyt tiedot lomakkeesta Kilpailija-olion luomista varten
@app.route("/kilpailijat/", methods=["POST"])
@login_required(role="admin")
def kilpailijat_create():
| 64 | 64 | 99 | 22 | 41 | tikibeni/windsurf-ranking | application/kilpailijat/views.py | Python | kilpailijat_create | kilpailijat_create | 28 | 41 | 28 | 30 | 4fbab71c7a69ce3540aa0c0a8e73a939a844c7f6 | bigcode/the-stack | train |
ac6d9becf1632d66a82f199e | train | function | @app.route("/kilpailijat/new/", methods=["GET"])
@login_required(role="admin")
def kilpailijat_form():
return render_template("kilpailijat/new.html", form=KilpailijaForm())
| @app.route("/kilpailijat/new/", methods=["GET"])
@login_required(role="admin")
def kilpailijat_form():
| return render_template("kilpailijat/new.html", form=KilpailijaForm())
| .html", kilpailijat=Kilpailija.query.all(), kilpailijaLinkki=User.kilpailijaLinkki())
# Haetaan lomake uuden kilpailijan luomista varten new.html:ään
@app.route("/kilpailijat/new/", methods=["GET"])
@login_required(role="admin")
def kilpailijat_form():
| 64 | 64 | 41 | 23 | 40 | tikibeni/windsurf-ranking | application/kilpailijat/views.py | Python | kilpailijat_form | kilpailijat_form | 15 | 18 | 15 | 17 | f8c2f2274666d35491390c56f919693b449a1152 | bigcode/the-stack | train |
26993f635a3675bd318c8a9d | train | class | class ExcludeNoneAttributes(Serializable):
"""Mixin for Serializable classes that exclude None-valued attributes when
serializing.
This class must appear BEFORE Serializable in the inheritence list of the
class::
class Foo(ExcludeNone, Serializable):
...
"""
def attributes... | class ExcludeNoneAttributes(Serializable):
| """Mixin for Serializable classes that exclude None-valued attributes when
serializing.
This class must appear BEFORE Serializable in the inheritence list of the
class::
class Foo(ExcludeNone, Serializable):
...
"""
def attributes(self):
"""Returns a list of class ... | *args: optional positional arguments for `self.from_dict()`
**kwargs: optional keyword arguments for `self.from_dict()`
Returns:
an instance of the Serializable class
"""
return cls.from_dict(read_json(path), *args, **kwargs)
class ExcludeNoneAttributes(Seria... | 64 | 64 | 126 | 8 | 56 | ErfanTagh/eta | eta/core/serial.py | Python | ExcludeNoneAttributes | ExcludeNoneAttributes | 515 | 535 | 515 | 515 | 707b3bcb64109243e85a580822a15bb4162c75bc | bigcode/the-stack | train |
4749a347ffed1267baf66efa | train | function | def read_ndjson(path):
"""Reads the NDJSON from file.
Args:
path: the path to the NDJSON file
Returns:
a list of JSON dicts
"""
with open(path, "rt") as f:
return ndjson.load(f)
| def read_ndjson(path):
| """Reads the NDJSON from file.
Args:
path: the path to the NDJSON file
Returns:
a list of JSON dicts
"""
with open(path, "rt") as f:
return ndjson.load(f)
| readable format with
newlines and indentations. By default, this is False
"""
s = json_to_str(obj, pretty_print=pretty_print)
etau.ensure_basedir(path)
with open(path, "wt") as f:
f.write(s)
def read_ndjson(path):
| 64 | 64 | 60 | 6 | 58 | ErfanTagh/eta | eta/core/serial.py | Python | read_ndjson | read_ndjson | 128 | 138 | 128 | 128 | 3aa8309b210f363fb4e498fadb940c7867e377d8 | bigcode/the-stack | train |
e16a24f9b6ec408f1d214ce5 | train | class | class ETAJSONEncoder(json.JSONEncoder):
"""Extends basic JSONEncoder to handle ETA conventions and types."""
# pylint: disable=method-hidden
def default(self, obj):
if isinstance(obj, Serializable):
return obj.serialize()
if isinstance(obj, np.integer):
return int(ob... | class ETAJSONEncoder(json.JSONEncoder):
| """Extends basic JSONEncoder to handle ETA conventions and types."""
# pylint: disable=method-hidden
def default(self, obj):
if isinstance(obj, Serializable):
return obj.serialize()
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floatin... | ):
"""Loads the .npz file from disk and returns an NpzWriteable instance.
Args:
path: the path to an .npz file
Returns:
an NpzWriteable instance
"""
return cls(**np.load(path))
class ETAJSONEncoder(json.JSONEncoder):
| 64 | 64 | 137 | 8 | 56 | ErfanTagh/eta | eta/core/serial.py | Python | ETAJSONEncoder | ETAJSONEncoder | 2,894 | 2,911 | 2,894 | 2,894 | bec6f1b2d189ef15b171b81918fb161417005041 | bigcode/the-stack | train |
833b035c5ef39662670433cd | train | function | def _recurse(v, reflective):
if isinstance(v, Serializable):
return v.serialize(reflective=reflective)
if isinstance(v, set):
v = list(v) # convert sets to lists
if isinstance(v, list):
return [_recurse(vi, reflective) for vi in v]
if isinstance(v, dict):
return Order... | def _recurse(v, reflective):
| if isinstance(v, Serializable):
return v.serialize(reflective=reflective)
if isinstance(v, set):
v = list(v) # convert sets to lists
if isinstance(v, list):
return [_recurse(vi, reflective) for vi in v]
if isinstance(v, dict):
return OrderedDict(
(str(ki),... | to be serialized.
Any attributes whose value is None are omitted.
Returns:
the list of attributes
"""
attrs = super(ExcludeNoneAttributes, self).attributes()
return [a for a in attrs if getattr(self, a) is not None]
def _recurse(v, reflective):
| 64 | 64 | 161 | 8 | 56 | ErfanTagh/eta | eta/core/serial.py | Python | _recurse | _recurse | 538 | 562 | 538 | 538 | fcda549193ac42847a19bc2072f5b334cfb62e78 | bigcode/the-stack | train |
85c59442351ac44a1e34a578 | train | class | class BigMixin(object):
"""Mixin class for "big" Serializable classes, which store their elements
on disk rather than in-memory.
Subclasses must call BigMixin's constructor to properly initialize the
Big object, and they must implement the `add_by_path()` and
`add_iterable()` methods.
`backing... | class BigMixin(object):
| """Mixin class for "big" Serializable classes, which store their elements
on disk rather than in-memory.
Subclasses must call BigMixin's constructor to properly initialize the
Big object, and they must implement the `add_by_path()` and
`add_iterable()` methods.
`backing_dir` is an optional key... | self._ELE_ATTR is None:
raise SetError(
"Cannot instantiate a Set for which _ELE_ATTR is None"
)
if not issubclass(self._ELE_CLS, Serializable):
raise SetError("%s is not Serializable" % self._ELE_CLS)
if self._ELE_KEY_ATTR is None:
rais... | 255 | 256 | 1,794 | 5 | 250 | ErfanTagh/eta | eta/core/serial.py | Python | BigMixin | BigMixin | 1,092 | 1,323 | 1,092 | 1,092 | bcf6eae95944daf7b48d96d0038408c07aa49140 | bigcode/the-stack | train |
742afde8222b921fe92835dd | train | class | class BigContainer(BigMixin, Container):
"""Container that stores a (potentially huge) list of `Serializable`
objects. The elements are stored on disk in a backing directory; accessing
any element in the list causes an immediate READ from disk, and
adding/setting an element causes an immediate WRITE to ... | class BigContainer(BigMixin, Container):
| """Container that stores a (potentially huge) list of `Serializable`
objects. The elements are stored on disk in a backing directory; accessing
any element in the list causes an immediate READ from disk, and
adding/setting an element causes an immediate WRITE to disk.
BigContainers provide native s... | _CLS is None:
raise ContainerError(
"Cannot instantiate a Container for which _ELE_CLS is None"
)
if self._ELE_ATTR is None:
raise ContainerError(
"Cannot instantiate a Container for which _ELE_ATTR is None"
)
if not issubcl... | 255 | 256 | 3,537 | 8 | 247 | ErfanTagh/eta | eta/core/serial.py | Python | BigContainer | BigContainer | 2,350 | 2,817 | 2,350 | 2,350 | ea1f1013a526f272c725ca975cbaf5389d53b1fe | bigcode/the-stack | train |
eb3179d5455043635545f809 | train | function | def json_to_str(obj, pretty_print=True):
"""Converts the JSON object to a string.
Args:
obj: a JSON dictionary or an instance of a Serializable subclass
pretty_print: whether to render the JSON in human readable format with
newlines and indentations. By default, this is True
"""... | def json_to_str(obj, pretty_print=True):
| """Converts the JSON object to a string.
Args:
obj: a JSON dictionary or an instance of a Serializable subclass
pretty_print: whether to render the JSON in human readable format with
newlines and indentations. By default, this is True
"""
if isinstance(obj, Serializable):
... | .getsize(path) > 0:
prefix = os.linesep
else:
prefix = ""
mode = "at" if append else "wt"
with open(path, mode) as f:
f.write(prefix + ndjson.dumps(obj))
def json_to_str(obj, pretty_print=True):
| 64 | 64 | 134 | 10 | 54 | ErfanTagh/eta | eta/core/serial.py | Python | json_to_str | json_to_str | 191 | 210 | 191 | 191 | e44129a27d9837577b298f499e587526c6cb0be8 | bigcode/the-stack | train |
1aeb32d71eeec527094b59e2 | train | class | class Set(Serializable):
"""Abstract base class for flexible sets that store homogeneous elements
of a `Serializable` class and provides O(1) lookup of elements by a
subclass-configurable element attribute.
This class cannot be instantiated directly. Instead a subclass should
be created for each ty... | class Set(Serializable):
| """Abstract base class for flexible sets that store homogeneous elements
of a `Serializable` class and provides O(1) lookup of elements by a
subclass-configurable element attribute.
This class cannot be instantiated directly. Instead a subclass should
be created for each type of element to be store... | ence list of the
class::
class Foo(ExcludeNone, Serializable):
...
"""
def attributes(self):
"""Returns a list of class attributes to be serialized.
Any attributes whose value is None are omitted.
Returns:
the list of attributes
"""
... | 256 | 256 | 3,522 | 5 | 250 | ErfanTagh/eta | eta/core/serial.py | Python | Set | Set | 565 | 1,089 | 565 | 565 | dc62d6b9065be626a1325c5f09cf85628f2794e8 | bigcode/the-stack | train |
645728f84eeb7fb29d319d93 | train | function | def deserialize_numpy_array(numpy_str, allow_pickle=False):
"""Loads a serialized numpy array from string.
Args:
numpy_str: serialized numpy array string
allow_pickle: whether to allow loading pickled objects, which is
necessary if the array has ``dtype=object``
Returns:
... | def deserialize_numpy_array(numpy_str, allow_pickle=False):
| """Loads a serialized numpy array from string.
Args:
numpy_str: serialized numpy array string
allow_pickle: whether to allow loading pickled objects, which is
necessary if the array has ``dtype=object``
Returns:
the numpy array
"""
#
# We currently serialize... | io.BytesIO() as f:
allow_pickle = array.dtype == object
np.save(f, array, allow_pickle=allow_pickle)
bytes_str = zlib.compress(f.getvalue())
return b64encode(bytes_str).decode("ascii")
def deserialize_numpy_array(numpy_str, allow_pickle=False):
| 64 | 64 | 144 | 12 | 52 | ErfanTagh/eta | eta/core/serial.py | Python | deserialize_numpy_array | deserialize_numpy_array | 274 | 291 | 274 | 274 | 7efc2d321465f27bc0175d67ea610b50eab32a0f | bigcode/the-stack | train |
2b2e751c8f7db2af72f8b299 | train | function | def read_json(path):
"""Reads JSON from file.
Args:
path: the path to the JSON file
Returns:
a dict or list containing the loaded JSON
Raises:
ValueError: if the JSON file was invalid
"""
try:
with open(path, "rt") as f:
return json.load(f)
exce... | def read_json(path):
| """Reads JSON from file.
Args:
path: the path to the JSON file
Returns:
a dict or list containing the loaded JSON
Raises:
ValueError: if the JSON file was invalid
"""
try:
with open(path, "rt") as f:
return json.load(f)
except ValueError:
... | % path_or_str)
def _load_json(str_or_bytes):
try:
return json.loads(str_or_bytes)
except TypeError:
# Must be a Python version for which json.loads() cannot handle bytes
return json.loads(str_or_bytes.decode("utf-8"))
def read_json(path):
| 63 | 64 | 95 | 5 | 58 | ErfanTagh/eta | eta/core/serial.py | Python | read_json | read_json | 93 | 109 | 93 | 93 | 87d1b2fb3851e4b2ad4622ea1b9baa4319d40cf0 | bigcode/the-stack | train |
f520184d785871e463e46e74 | train | class | class BigSet(BigMixin, Set):
"""Set that stores a (potentially huge) list of `Serializable`
objects. The elements are stored on disk in a backing directory; accessing
any element in the list causes an immediate READ from disk, and
adding/setting an element causes an immediate WRITE to disk.
BigSets... | class BigSet(BigMixin, Set):
| """Set that stores a (potentially huge) list of `Serializable`
objects. The elements are stored on disk in a backing directory; accessing
any element in the list causes an immediate READ from disk, and
adding/setting an element causes an immediate WRITE to disk.
BigSets store a `backing_dir` attrib... | to element JSON files
Returns:
a Big iterable
"""
big = cls(backing_dir=backing_dir)
for path in paths:
big.add_by_path(path)
return big
@classmethod
def from_dir(cls, source_dir, backing_dir=None):
"""Creates a Big iterable from an unst... | 256 | 256 | 3,462 | 8 | 248 | ErfanTagh/eta | eta/core/serial.py | Python | BigSet | BigSet | 1,326 | 1,777 | 1,326 | 1,326 | daf78c29cf2f195727876f9ac4701a1f61fdb2f4 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.