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
a04d427ff2934a60fd40dbd9
train
class
class TreeEnsembleRegressorCommon(OpRunUnaryNum): def __init__(self, dtype, onnx_node, desc=None, expected_attributes=None, **options): OpRunUnaryNum.__init__(self, onnx_node, desc=desc, expected_attributes=expected_attributes, ...
class TreeEnsembleRegressorCommon(OpRunUnaryNum):
def __init__(self, dtype, onnx_node, desc=None, expected_attributes=None, **options): OpRunUnaryNum.__init__(self, onnx_node, desc=desc, expected_attributes=expected_attributes, **options) self._init(dtype=dtype) def...
# -*- encoding: utf-8 -*- # pylint: disable=E0203,E1101,C0111 """ @file @brief Runtime operator. """ from collections import OrderedDict import numpy from ._op_helper import _get_typed_class_attribute from ._op import OpRunUnaryNum, RuntimeTypeError from ._new_ops import OperatorSchema from .op_tree_ensemble_regressor_...
130
142
476
12
118
Exlsunshine/mlprodict
mlprodict/onnxrt/ops_cpu/op_tree_ensemble_regressor.py
Python
TreeEnsembleRegressorCommon
TreeEnsembleRegressorCommon
18
64
18
19
6ae54b3aa937c2223278ea7dee4808e5e4c12824
bigcode/the-stack
train
aa09c97b0b8fd2caedee7fc3
train
class
class TreeEnsembleRegressorDoubleSchema(OperatorSchema): """ Defines a schema for operators added in this package such as @see cl TreeEnsembleRegressorDouble. """ def __init__(self): OperatorSchema.__init__(self, 'TreeEnsembleRegressorDouble') self.attributes = TreeEnsembleRegressor...
class TreeEnsembleRegressorDoubleSchema(OperatorSchema):
""" Defines a schema for operators added in this package such as @see cl TreeEnsembleRegressorDouble. """ def __init__(self): OperatorSchema.__init__(self, 'TreeEnsembleRegressorDouble') self.attributes = TreeEnsembleRegressorDouble.atts
onnx_node, desc=None, **options): TreeEnsembleRegressorCommon.__init__( self, numpy.float64, onnx_node, desc=desc, expected_attributes=TreeEnsembleRegressorDouble.atts, **options) class TreeEnsembleRegressorDoubleSchema(OperatorSchema):
64
64
76
12
52
Exlsunshine/mlprodict
mlprodict/onnxrt/ops_cpu/op_tree_ensemble_regressor.py
Python
TreeEnsembleRegressorDoubleSchema
TreeEnsembleRegressorDoubleSchema
125
133
125
125
15642866d423719e151b57e2b42da8085e32fe7c
bigcode/the-stack
train
df1c78966cac107a20837775
train
class
class TreeEnsembleRegressor(TreeEnsembleRegressorCommon): atts = OrderedDict([ ('aggregate_function', b'SUM'), ('base_values', numpy.empty(0, dtype=numpy.float32)), ('n_targets', 1), ('nodes_falsenodeids', numpy.empty(0, dtype=numpy.int64)), ('nodes_featureids', numpy.empty(...
class TreeEnsembleRegressor(TreeEnsembleRegressorCommon):
atts = OrderedDict([ ('aggregate_function', b'SUM'), ('base_values', numpy.empty(0, dtype=numpy.float32)), ('n_targets', 1), ('nodes_falsenodeids', numpy.empty(0, dtype=numpy.int64)), ('nodes_featureids', numpy.empty(0, dtype=numpy.int64)), ('nodes_hitrates', numpy.em...
:class:`RuntimeTreeEnsembleRegressorDouble <mlprodict.onnxrt.ops_cpu.op_tree_ensemble_regressor_.RuntimeTreeEnsembleRegressorDouble>`. """ pred = self.rt_.compute(x) if pred.shape[0] != x.shape[0]: pred = pred.reshape(x.shape[0], pred.shape[0] // x.shape[0]) return (...
101
101
338
13
88
Exlsunshine/mlprodict
mlprodict/onnxrt/ops_cpu/op_tree_ensemble_regressor.py
Python
TreeEnsembleRegressor
TreeEnsembleRegressor
67
93
67
68
1ff5ba631a35883431daac28e9b063b1ae4b8ddf
bigcode/the-stack
train
cb5562bcae2856812a75cb12
train
class
class SpiderOpticError(Exception): """Generic errors.""" pass
class SpiderOpticError(Exception):
"""Generic errors.""" pass
class SpiderOpticError(Exception):
7
64
15
7
0
fearless-spider/spideroptic-cli
spideroptic/core/exc.py
Python
SpiderOpticError
SpiderOpticError
2
4
2
2
6ba449a5699fb568e649754a4d3c9593242b3722
bigcode/the-stack
train
b28d8bf204207c812f3ebfa2
train
class
class AwesomeJavaParser(AbstractAwesomeParser): AWESOME_TITLE = 'java' AWESOME_README_URL = 'https://raw.githubusercontent.com/akullpp/awesome-java/master/README.md' def find_content(self): readme = self.read_readme() content = readme.split(' - [Websites](#websites)')[1] lines = []...
class AwesomeJavaParser(AbstractAwesomeParser):
AWESOME_TITLE = 'java' AWESOME_README_URL = 'https://raw.githubusercontent.com/akullpp/awesome-java/master/README.md' def find_content(self): readme = self.read_readme() content = readme.split(' - [Websites](#websites)')[1] lines = [] for line in content.split('\n'): ...
from . import AbstractAwesomeParser class AwesomeJavaParser(AbstractAwesomeParser):
15
74
249
8
6
jcardibo/awesome-finder
awesome/parsers/java.py
Python
AwesomeJavaParser
AwesomeJavaParser
4
37
4
4
5171a694fc40031e49babda37c925246dcca06da
bigcode/the-stack
train
68e0f36712b3fd1a56786eba
train
function
def create_confirmed_utxos(node, count, age=101): """ Helper to create at least "count" utxos """ to_generate = int(0.5 * count) + age while to_generate > 0: node.generate(min(25, to_generate)) to_generate -= 25 utxos = node.listunspent() iterations = count - len(utxos) a...
def create_confirmed_utxos(node, count, age=101):
""" Helper to create at least "count" utxos """ to_generate = int(0.5 * count) + age while to_generate > 0: node.generate(min(25, to_generate)) to_generate -= 25 utxos = node.listunspent() iterations = count - len(utxos) addr1 = node.getnewaddress() addr2 = node.getne...
return count def get_legacy_sigopcount_tx(tx, fAccurate=True): count = 0 for i in tx.vout: count += i.scriptPubKey.GetSigOpCount(fAccurate) for j in tx.vin: # scriptSig might be of type bytes, so convert to CScript for the moment count += CScript(j.scriptSig).GetSigOpCount(fAcc...
111
111
370
15
95
DaSpawn/bitcoin-abc
test/functional/test_framework/blocktools.py
Python
create_confirmed_utxos
create_confirmed_utxos
110
146
110
110
8811355674ada537a56d6e8198041479baa8f520
bigcode/the-stack
train
eabda74ff52a26d2ed8249bc
train
function
def mine_big_block(node, utxos=None): # generate a 66k transaction, # and 14 of them is close to the 1MB block limit num = 14 utxos = utxos if utxos is not None else [] if len(utxos) < num: utxos.clear() utxos.extend(node.listunspent()) send_big_transactions(node, utxos, num, 100...
def mine_big_block(node, utxos=None): # generate a 66k transaction, # and 14 of them is close to the 1MB block limit
num = 14 utxos = utxos if utxos is not None else [] if len(utxos) < num: utxos.clear() utxos.extend(node.listunspent()) send_big_transactions(node, utxos, num, 100) node.generate(1)
utxos = node.listunspent() assert(len(utxos) >= count) return utxos def mine_big_block(node, utxos=None): # generate a 66k transaction, # and 14 of them is close to the 1MB block limit
64
64
108
37
26
DaSpawn/bitcoin-abc
test/functional/test_framework/blocktools.py
Python
mine_big_block
mine_big_block
149
158
149
151
6e76480c8d3f90f7f244f547b8330515a0876800
bigcode/the-stack
train
1d97087aa4b30fe6b476f81c
train
function
def create_block(hashprev, coinbase, nTime=None): block = CBlock() if nTime is None: import time block.nTime = int(time.time() + 600) else: block.nTime = nTime block.hashPrevBlock = hashprev block.nBits = 0x207fffff # Will break after a difficulty adjustment... block.vtx...
def create_block(hashprev, coinbase, nTime=None):
block = CBlock() if nTime is None: import time block.nTime = int(time.time() + 600) else: block.nTime = nTime block.hashPrevBlock = hashprev block.nBits = 0x207fffff # Will break after a difficulty adjustment... block.vtx.append(coinbase) block.hashMerkleRoot = block...
, OP_HASH160, OP_EQUALVERIFY from .mininode import CTransaction, CTxOut, CTxIn from .util import satoshi_round from .txtools import pad_tx # Create a block (with regtest difficulty) def create_block(hashprev, coinbase, nTime=None):
64
64
115
13
51
DaSpawn/bitcoin-abc
test/functional/test_framework/blocktools.py
Python
create_block
create_block
16
28
16
16
9c22017d9178d9a882b7a106357727226bf51996
bigcode/the-stack
train
a01c5c52f56a20e6065a5ebd
train
function
def get_legacy_sigopcount_block(block, fAccurate=True): count = 0 for tx in block.vtx: count += get_legacy_sigopcount_tx(tx, fAccurate) return count
def get_legacy_sigopcount_block(block, fAccurate=True):
count = 0 for tx in block.vtx: count += get_legacy_sigopcount_tx(tx, fAccurate) return count
CTxIn(COutPoint(prevtx.sha256, n), sig, 0xffffffff)) tx.vout.append(CTxOut(value, scriptPubKey)) pad_tx(tx) tx.calc_sha256() return tx def get_legacy_sigopcount_block(block, fAccurate=True):
64
64
49
15
48
DaSpawn/bitcoin-abc
test/functional/test_framework/blocktools.py
Python
get_legacy_sigopcount_block
get_legacy_sigopcount_block
93
97
93
93
958553ad9b9bba4d916330e8d95a8d10f944a4c1
bigcode/the-stack
train
2a85798bea4a48eff51214f3
train
function
def get_legacy_sigopcount_tx(tx, fAccurate=True): count = 0 for i in tx.vout: count += i.scriptPubKey.GetSigOpCount(fAccurate) for j in tx.vin: # scriptSig might be of type bytes, so convert to CScript for the moment count += CScript(j.scriptSig).GetSigOpCount(fAccurate) return c...
def get_legacy_sigopcount_tx(tx, fAccurate=True):
count = 0 for i in tx.vout: count += i.scriptPubKey.GetSigOpCount(fAccurate) for j in tx.vin: # scriptSig might be of type bytes, so convert to CScript for the moment count += CScript(j.scriptSig).GetSigOpCount(fAccurate) return count
def get_legacy_sigopcount_block(block, fAccurate=True): count = 0 for tx in block.vtx: count += get_legacy_sigopcount_tx(tx, fAccurate) return count def get_legacy_sigopcount_tx(tx, fAccurate=True):
64
64
92
15
48
DaSpawn/bitcoin-abc
test/functional/test_framework/blocktools.py
Python
get_legacy_sigopcount_tx
get_legacy_sigopcount_tx
100
107
100
100
4236aab1761fd6673356ebfa8c22c3c2b48da0c4
bigcode/the-stack
train
066b3b7f20c0fdd48e95aef2
train
function
def make_conform_to_ctor(block): for tx in block.vtx: pad_tx(tx) tx.rehash() block.vtx = [block.vtx[0]] + \ sorted(block.vtx[1:], key=lambda tx: tx.get_id())
def make_conform_to_ctor(block):
for tx in block.vtx: pad_tx(tx) tx.rehash() block.vtx = [block.vtx[0]] + \ sorted(block.vtx[1:], key=lambda tx: tx.get_id())
= hashprev block.nBits = 0x207fffff # Will break after a difficulty adjustment... block.vtx.append(coinbase) block.hashMerkleRoot = block.calc_merkle_root() block.calc_sha256() return block def make_conform_to_ctor(block):
64
64
56
8
55
DaSpawn/bitcoin-abc
test/functional/test_framework/blocktools.py
Python
make_conform_to_ctor
make_conform_to_ctor
31
36
31
31
0e9e71d7b68545231bb40884869f48c5869f4099
bigcode/the-stack
train
fadf844c8dd7ff717ac99344
train
function
def send_big_transactions(node, utxos, num, fee_multiplier): from .cashaddr import decode txids = [] padding = "1"*(512*127) addrHash = decode(node.getnewaddress())[2] for _ in range(num): ctx = CTransaction() utxo = utxos.pop() txid = int(utxo['txid'], 16) ctx.vin.a...
def send_big_transactions(node, utxos, num, fee_multiplier):
from .cashaddr import decode txids = [] padding = "1"*(512*127) addrHash = decode(node.getnewaddress())[2] for _ in range(num): ctx = CTransaction() utxo = utxos.pop() txid = int(utxo['txid'], 16) ctx.vin.append(CTxIn(COutPoint(txid, int(utxo["vout"])), b"")) ...
num = 14 utxos = utxos if utxos is not None else [] if len(utxos) < num: utxos.clear() utxos.extend(node.listunspent()) send_big_transactions(node, utxos, num, 100) node.generate(1) def send_big_transactions(node, utxos, num, fee_multiplier):
86
86
287
15
71
DaSpawn/bitcoin-abc
test/functional/test_framework/blocktools.py
Python
send_big_transactions
send_big_transactions
161
183
161
161
321cbac94f0450edf8404dea39b70d6ad9129248
bigcode/the-stack
train
56845ca726d5d15893ae9715
train
function
def create_transaction(prevtx, n, sig, value, scriptPubKey=CScript()): tx = CTransaction() assert(n < len(prevtx.vout)) tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), sig, 0xffffffff)) tx.vout.append(CTxOut(value, scriptPubKey)) pad_tx(tx) tx.calc_sha256() return tx
def create_transaction(prevtx, n, sig, value, scriptPubKey=CScript()):
tx = CTransaction() assert(n < len(prevtx.vout)) tx.vin.append(CTxIn(COutPoint(prevtx.sha256, n), sig, 0xffffffff)) tx.vout.append(CTxOut(value, scriptPubKey)) pad_tx(tx) tx.calc_sha256() return tx
100 bytes pad_tx(coinbase) coinbase.calc_sha256() return coinbase # Create a transaction. # If the scriptPubKey is not specified, make it anyone-can-spend. def create_transaction(prevtx, n, sig, value, scriptPubKey=CScript()):
64
64
90
19
45
DaSpawn/bitcoin-abc
test/functional/test_framework/blocktools.py
Python
create_transaction
create_transaction
83
90
83
83
559694f117da4fa15aa8e2d47ebca5e6a4c8562a
bigcode/the-stack
train
95e1fb5430b50a881b125773
train
function
def serialize_script_num(value): r = bytearray(0) if value == 0: return r neg = value < 0 absvalue = -value if neg else value while (absvalue): r.append(int(absvalue & 0xff)) absvalue >>= 8 if r[-1] & 0x80: r.append(0x80 if neg else 0) elif neg: r[-1] ...
def serialize_script_num(value):
r = bytearray(0) if value == 0: return r neg = value < 0 absvalue = -value if neg else value while (absvalue): r.append(int(absvalue & 0xff)) absvalue >>= 8 if r[-1] & 0x80: r.append(0x80 if neg else 0) elif neg: r[-1] |= 0x80 return r
block def make_conform_to_ctor(block): for tx in block.vtx: pad_tx(tx) tx.rehash() block.vtx = [block.vtx[0]] + \ sorted(block.vtx[1:], key=lambda tx: tx.get_id()) def serialize_script_num(value):
64
64
112
6
58
DaSpawn/bitcoin-abc
test/functional/test_framework/blocktools.py
Python
serialize_script_num
serialize_script_num
39
52
39
39
b3e792c15490ee284abddf5124f4fa2db96bb279
bigcode/the-stack
train
401b359a282b4bdc61da41ab
train
function
def create_coinbase(height, pubkey=None): coinbase = CTransaction() coinbase.vin.append(CTxIn(COutPoint(0, 0xffffffff), ser_string(serialize_script_num(height)), 0xffffffff)) coinbaseoutput = CTxOut() coinbaseoutput.nValue = 50 * COIN halvings = int(height / 150) # reg...
def create_coinbase(height, pubkey=None):
coinbase = CTransaction() coinbase.vin.append(CTxIn(COutPoint(0, 0xffffffff), ser_string(serialize_script_num(height)), 0xffffffff)) coinbaseoutput = CTxOut() coinbaseoutput.nValue = 50 * COIN halvings = int(height / 150) # regtest coinbaseoutput.nValue >>= halving...
[-1] |= 0x80 return r # Create a coinbase transaction, assuming no miner fees. # If pubkey is passed in, the coinbase output will be a P2PK output; # otherwise an anyone-can-spend output. def create_coinbase(height, pubkey=None):
64
64
184
10
54
DaSpawn/bitcoin-abc
test/functional/test_framework/blocktools.py
Python
create_coinbase
create_coinbase
59
77
59
59
74099544e7b507990c69e8ea033b6cc9aef3c56b
bigcode/the-stack
train
85083b437f80ffa9c2b45f95
train
class
class IManagedLoadConnection(IManagedDBConnection): """ A managed connection intended for loading.
class IManagedLoadConnection(IManagedDBConnection): """ A managed connection intended for loading.
be called up to twice if it raises a disconnected exception on the first try. :return: The return value of ``f``. """ def enter_critical_phase_until_transaction_end(): """ As for :meth:`IDBDriver.enter_critical_phase_until_transaction_end`. """
63
64
21
1
63
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IManagedLoadConnection
IManagedLoadConnection
610
613
610
610
c9a16ce054e55d4ea57ae8304ca1caaed687350a
bigcode/the-stack
train
1c50c4ac5507cb212830d3c9
train
class
class IScriptRunner(Interface): """Run database-agnostic SQL scripts. Using an IScriptRunner is appropriate for batch operations and uncommon operations that can be slow, but is not appropriate for performance-critical code. """ script_vars = Attribute( """A mapping providing replace...
class IScriptRunner(Interface): """Run database-agnostic SQL scripts. Using an IScriptRunner is appropriate for batch operations and uncommon operations that can be slow, but is not appropriate for performance-critical code. """ script_vars = Attribute( """A mapping providing replacem...
schema that's installed can be used by this RelStorage. If it cannot, for example it's history-preserving and we were configured to be history-free, raise an exception. """ def zap_all(): """Clear all data out of the database.""" def drop_all(): """Drop all ta...
69
70
235
1
69
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IScriptRunner
IScriptRunner
1,100
1,139
1,100
1,100
6426b831c14d2024ee1d36020dc7577a00e61058
bigcode/the-stack
train
aac8f85eba72eb14b2815294
train
class
"A lock cannot be acquired." class UnableToAcquireCommitLockError(StorageError, UnableToAcquireLockError): """ The commit lock cannot be acquired due to a timeout. This means some other transaction had the lock we needed. Retrying the transaction may succeed.
"A lock cannot be acquired."
class UnableToAcquireCommitLockError(StorageError, UnableToAcquireLockError): """ The commit lock cannot be acquired due to a timeout. This means some other transaction had the lock we needed. Retrying the transaction may succeed.
:param read_current_oids: A mapping from oid integer to tid integer that the transaction expects. """ ### # Exceptions ### class ReplicaClosedException(Exception): """The connection to the replica has been closed""" class UnableToAcquireLockError(Exception): "A lock cannot be acq...
64
64
59
8
56
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
UnableToAcquireCommitLockError
UnableToAcquireCommitLockError
1,630
1,638
1,630
1,630
ae67f8206b0fa50b86b9ce291aed1a53d4ea2c91
bigcode/the-stack
train
37752d1c3b9ac5ce97c302c5
train
class
class IDBDriverSupportsCritical(IDBDriver): """ A marker for database drivers that support critical phases. They promise that :meth:`enter_critical_phase_until_transaction_end` will do something useful. """
class IDBDriverSupportsCritical(IDBDriver):
""" A marker for database drivers that support critical phases. They promise that :meth:`enter_critical_phase_until_transaction_end` will do something useful. """
_in_critical_phase(connection, cursor): """ Answer whether :meth:`enter_critical_phase_until_transaction_end` is in effect. """ def exit_critical_phase(connection, cursor): "If currently in a critical phase, de-escalate." class IDBDriverSupportsCritical(IDBDriver):
64
64
48
10
54
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IDBDriverSupportsCritical
IDBDriverSupportsCritical
200
207
200
200
7de8a8134f047aec3f7f2c31060cf792eaaa9e5b
bigcode/the-stack
train
eee60a11131c137ce9f18286
train
class
class IRelStorageAdapter(Interface): """ A database adapter for RelStorage. Historically, this has just been a holding place for other components for the particular database. However, it is moving to holding algorithms involved in the storage; this facilitates moving chunks of functionality i...
class IRelStorageAdapter(Interface): """ A database adapter for RelStorage. Historically, this has just been a holding place for other components for the particular database. However, it is moving to holding algorithms involved in the storage; this facilitates moving chunks of functionality in...
This is what must be committed. :param load_connection: An :class:`IManagedLoadConnection` corresponding to the store connection. If helpful to the database, (for example, for resource reasons) implementations may rollback the connection immediately before committing the store ...
255
256
3,916
1
255
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IRelStorageAdapter
IRelStorageAdapter
1,219
1,617
1,219
1,219
d451938142211bda603b5cd43b5d44ccc08c61bf
bigcode/the-stack
train
0f8e283cfe114d3bddf5154b
train
class
""" class ILocker(Interface): """Acquire and release the commit and pack locks.""" def lock_current_objects(cursor, read_current_oid_ints, shared_locks_block): """ Lock the objects being modified in the current transaction exclusively, plus the relevant rows for the objects who...
"""
class ILocker(Interface): """Acquire and release the commit and pack locks.""" def lock_current_objects(cursor, read_current_oid_ints, shared_locks_block): """ Lock the objects being modified in the current transaction exclusively, plus the relevant rows for the objects whose OIDs ...
iter_current_records(cursor, start_oid_int=0): """ Cause the *cursor* (which should be a server-side cursor) to execute a query that will iterate over ``(oid_int, tid_int, state_bytes)`` values for all the current objects. Each current object is returned only once, at the trans...
122
122
409
2
120
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
ILocker
ILocker
696
750
696
696
1c116880027efb579223b81555b351a7f0a9cb6b
bigcode/the-stack
train
9d1ff34ee53cc57994ff0369
train
class
""" class ISchemaInstaller(Interface): """Install the schema in the database, clear it, or uninstall it""" def prepare(): """ Create the database schema if it does not already exist. Perform any migration steps needed, and call :meth:`verify` before returning. ...
"""
class ISchemaInstaller(Interface): """Install the schema in the database, clear it, or uninstall it""" def prepare(): """ Create the database schema if it does not already exist. Perform any migration steps needed, and call :meth:`verify` before returning. """ def...
:`StaleConnectionError` (a ``ReadConflictError``) if the database has reverted to an earlier transaction, which can happen in an asynchronously replicated database. This exception is one that is transient and most transaction middleware will catch it and retry the transaction. ...
64
64
129
2
62
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
ISchemaInstaller
ISchemaInstaller
1,073
1,097
1,073
1,073
7cf28150c7284519ed2a0a2f1c6e2ac78bd6f58f
bigcode/the-stack
train
ebe75c6f84eceb63e71ff583
train
class
class AggregateOperationTimeoutError(Exception): """ Raised when an aggregate operation in RelStorage detects that it has exceeded a specified timeout. """ #: If the function knows a useful, partial result, it may set this
class AggregateOperationTimeoutError(Exception): """ Raised when an aggregate operation in RelStorage detects that it has exceeded a specified timeout. """ #: If the function knows a useful, partial result, it may set this
@classmethod def from_prev_and_new_tid(cls, prev_polled_tid, new_polled_tid): return cls( "The database connection is stale: new_polled_tid=%d, " "prev_polled_tid=%d." % (new_polled_tid, prev_polled_tid))
63
64
49
1
63
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
AggregateOperationTimeoutError
AggregateOperationTimeoutError
1,683
1,691
1,683
1,683
a363aa9cef5ccf91349f79414cf199544280f825
bigcode/the-stack
train
05b29a944018ce19bb1ec11e
train
class
class IManagedStoreConnection(IManagedDBConnection): """ A managed connection intended for storing data.
class IManagedStoreConnection(IManagedDBConnection): """ A managed connection intended for storing data.
The return value of ``f``. """ def enter_critical_phase_until_transaction_end(): """ As for :meth:`IDBDriver.enter_critical_phase_until_transaction_end`. """ class IManagedLoadConnection(IManagedDBConnection): """ A managed connection intended for loading. """
63
64
22
1
63
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IManagedStoreConnection
IManagedStoreConnection
615
618
615
615
6c023d036a908cb3a69a24a7e9ab2cc905e921ae
bigcode/the-stack
train
7e5891bf4eccec3dbfb333db
train
class
class IConnectionManager(Interface): """ Open and close database connections. This is a low-level interface; most operations should instead use a pre-existing :class:`IManagedDBConnection`. """ isolation_load = Attribute("Default load isolation level.") isolation_store = Attribute("Defaul...
class IConnectionManager(Interface): """ Open and close database connections. This is a low-level interface; most operations should instead use a pre-existing :class:`IManagedDBConnection`. """ isolation_load = Attribute("Default load isolation level.") isolation_store = Attribute("Default...
Error(DriverNotAvailableError): """ Raised when there are no drivers available. """ def __init__(self, driver_name='auto', driver_options=None, reason=None): super(NoDriversAvailableError, self).__init__(driver_name, driver_options, reason) class IDBDriverOptions(Interface): """ Imple...
255
256
1,414
1
255
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IConnectionManager
IConnectionManager
334
530
334
334
fe12f5ebad88181a496f054f476a486a5f0c3bc9
bigcode/the-stack
train
ba613e20f93690c5368eba2c
train
class
"""
"""
Current()`` was called on. This means another transaction already had the rows locked with intent to modify them, and thus we are in conflict with that transaction. Retrying the transaction may succeed. This is a type of ``ReadConflictError``, which is a transient error. """
64
64
2
2
62
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
UnableToAcquirePackUndoLockError
UnableToAcquirePackUndoLockError
1,666
1,667
1,666
1,666
a951d21fa56fb240d3054a774ec8991ade750a5f
bigcode/the-stack
train
d4e9773d3b230b86b6b5838a
train
class
""" class IPoller(Interface): """Poll for new data""" def get_current_tid(cursor): """ Returns the highest transaction ID visible to the cursor. If there are no transactions, returns 0. """ def poll_invalidations(conn, cursor, prev_polled_tid): """ ...
"""
class IPoller(Interface): """Poll for new data""" def get_current_tid(cursor): """ Returns the highest transaction ID visible to the cursor. If there are no transactions, returns 0. """ def poll_invalidations(conn, cursor, prev_polled_tid): """ Polls for n...
single revision of *oid_int* (which *should* be checked to verify it is at *tid_int*), leading all access to *oid_int* in the future to throw ``POSKeyError``. In history preserving databases, this means to set the state for the object at the transaction to NULL, signifying that...
95
95
317
2
93
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IPoller
IPoller
1,033
1,071
1,033
1,033
6eddcdd12b42fd2754b815c7791f25eea17dda8c
bigcode/the-stack
train
359dac5646539e57300e8884
train
class
class DriverNotAvailableError(Exception): """ Raised when a requested driver isn't available. """ #: The name of the requested driver driver_name = None #: The `IDBDriverOptions` that was asked for the driver. driver_options = None #: The underlying reason string, for example, from an...
class DriverNotAvailableError(Exception):
""" Raised when a requested driver isn't available. """ #: The name of the requested driver driver_name = None #: The `IDBDriverOptions` that was asked for the driver. driver_options = None #: The underlying reason string, for example, from an import error #: if such is available....
def check_availability(): """ Return a boolean indicating whether a call to this factory will return a driver (True) or will raise an error (False). """ def __call__(): # pylint:disable=signature-differs """ Return a new `IDBDriver` as represented by this factory. ...
107
107
358
7
100
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
DriverNotAvailableError
DriverNotAvailableError
231
284
231
231
d216156255677947a8d7491d9d9273f46011a6a9
bigcode/the-stack
train
bdc026d70b7dad1ff45bb6a6
train
class
class StaleConnectionError(ReadConflictError): """ Raised by `IPoller.poll_invalidations` when a stale connection is detected. """ @classmethod def from_prev_and_new_tid(cls, prev_polled_tid, new_polled_tid): return cls(
class StaleConnectionError(ReadConflictError): """ Raised by `IPoller.poll_invalidations` when a stale connection is detected. """ @classmethod def from_prev_and_new_tid(cls, prev_polled_tid, new_polled_tid): return cls(
in conflict with that transaction. Retrying the transaction may succeed. This is a type of ``ReadConflictError``, which is a transient error. """ class UnableToAcquirePackUndoLockError(StorageError, UnableToAcquireLockError): """A pack or undo operation is in progress."""
63
64
60
1
63
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
StaleConnectionError
StaleConnectionError
1,670
1,680
1,670
1,670
87e38d62bb86fb2fe2b7b80b174c49042c84df35
bigcode/the-stack
train
30729771391147151342deef
train
class
class IDBDriverFactory(Interface): """ Information about, and a way to get, an `IDBDriver` implementation. """ driver_name = Attribute("The name of this driver produced by this factory.") def check_availability(): """ Return a boolean indicating whether a call to this factory ...
class IDBDriverFactory(Interface):
""" Information about, and a way to get, an `IDBDriver` implementation. """ driver_name = Attribute("The name of this driver produced by this factory.") def check_availability(): """ Return a boolean indicating whether a call to this factory will return a driver (True) ...
critical phase, de-escalate." class IDBDriverSupportsCritical(IDBDriver): """ A marker for database drivers that support critical phases. They promise that :meth:`enter_critical_phase_until_transaction_end` will do something useful. """ class IDBDriverFactory(Interface):
64
64
148
8
56
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IDBDriverFactory
IDBDriverFactory
209
229
209
209
a080538a86b7f5608d49577ec79f61820d661c9f
bigcode/the-stack
train
4b56eead3309e0d9aeb31187
train
class
class IPackUndo(Interface): """Perform pack and undo operations""" MAX_TID = Attribute("The maximum TID that can be stored.") def verify_undoable(cursor, undo_tid): """Raise UndoError if it is not safe to undo the specified txn. """ def undo(cursor, undo_tid, self_tid): """U...
class IPackUndo(Interface): """Perform pack and undo operations""" MAX_TID = Attribute("The maximum TID that can be stored.") def verify_undoable(cursor, undo_tid): """Raise UndoError if it is not safe to undo the specified txn. """ def undo(cursor, undo_tid, self_tid): """Un...
class IOIDAllocator(Interface): """ Allocate OIDs and control future allocation. The cursor passed here must be from a :meth:`store connection <IConnectionManager.open_for_store>`. """ def new_oids(cursor): """ Return a new :class:`list` of new, unused integer OIDs. Th...
168
169
565
1
168
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IPackUndo
IPackUndo
958
1,031
958
958
56dcb4ca6913fadf0f262bb4cb659c93102da152
bigcode/the-stack
train
6d7cb21d2853fd8271eca013
train
class
class NoDriversAvailableError(DriverNotAvailableError): """ Raised when there are no drivers available. """ def __init__(self, driver_name='auto', driver_options=None, reason=None): super(NoDriversAvailableError, self).__init__(driver_name, driver_options, reason)
class NoDriversAvailableError(DriverNotAvailableError):
""" Raised when there are no drivers available. """ def __init__(self, driver_name='auto', driver_options=None, reason=None): super(NoDriversAvailableError, self).__init__(driver_name, driver_options, reason)
self.driver_name, reason, self._format_drivers() ) __repr__ = __str__ class UnknownDriverError(DriverNotAvailableError): """ Raised when a driver that isn't registered at all is requested. """ class NoDriversAvailableError(DriverNotAvailableError):
63
64
62
11
52
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
NoDriversAvailableError
NoDriversAvailableError
293
299
293
293
c2c91afd41223c322250e2bc99e9f9566bc3b1bd
bigcode/the-stack
train
2175f4e5121f23df291bdeb2
train
class
class IManagedDBConnection(Interface): """ A managed DB connection consists of a DB-API ``connection`` object and a single DB-API ``cursor`` from that connection. This encapsulates proper use of ``IConnectionManager``, including handling disconnections and re-connecting at appropriate times. ...
class IManagedDBConnection(Interface): """ A managed DB connection consists of a DB-API ``connection`` object and a single DB-API ``cursor`` from that connection. This encapsulates proper use of ``IConnectionManager``, including handling disconnections and re-connecting at appropriate times. I...
lock. If the database doesn't actually use a pack lock, this may return ``(None, None)``. """ def cursor_for_connection(conn): """ If the cursor returned by an open method was discarded for state management purposes, use this to get a new cursor. """ d...
153
154
514
1
153
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IManagedDBConnection
IManagedDBConnection
533
608
533
533
bc1c260128068f91dece68c2bca9c32dbd6a4dd3
bigcode/the-stack
train
27bbdc38a6a4db94fda6689c
train
class
# TransientError -> ConflictError -> ReadConflictError class UnableToLockRowsToModifyError(ConflictError, UnableToAcquireLockError): """ We were unable to lock one or more rows that we intend to modify due to a timeout. This means another transaction already had the rows locked, and thus we are in...
# TransientError -> ConflictError -> ReadConflictError
class UnableToLockRowsToModifyError(ConflictError, UnableToAcquireLockError): """ We were unable to lock one or more rows that we intend to modify due to a timeout. This means another transaction already had the rows locked, and thus we are in conflict with that transaction. Retrying the trans...
The commit lock cannot be acquired due to a timeout. This means some other transaction had the lock we needed. Retrying the transaction may succeed. However, for historical reasons, this exception is not a ``TransientError``. """ # TransientError -> ConflictError -> ReadConflictError
64
64
85
12
52
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
UnableToLockRowsToModifyError
UnableToLockRowsToModifyError
1,642
1,652
1,642
1,642
ed5be1420d3bf8727ebd92d676ce631a3de68ccc
bigcode/the-stack
train
4a8bbb4887c9419647f05bbb
train
class
class IDatabaseIterator(Interface): """Iterate over the available data in the database""" def iter_objects(cursor, tid): """Iterate over object states in a transaction. Yields (oid, prev_tid, state) for each object state. """ def iter_transactions(cursor): """ It...
class IDatabaseIterator(Interface): """Iterate over the available data in the database""" def iter_objects(cursor, tid): """Iterate over object states in a transaction. Yields (oid, prev_tid, state) for each object state. """ def iter_transactions(cursor): """ Ite...
ManagedDBConnection): """ A managed connection intended for storing data. """ class IReplicaSelector(Interface): """Selects a database replica""" def current(): """Get the current replica. Return a string. For PostgreSQL and MySQL, the string is either a host:port specifi...
111
114
382
1
111
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IDatabaseIterator
IDatabaseIterator
640
694
640
640
843a04cee5fce172e4bb10059544b74d7f2f18c6
bigcode/the-stack
train
395dc01de2d781965ebf2cdf
train
class
class IReplicaSelector(Interface): """Selects a database replica""" def current(): """Get the current replica. Return a string. For PostgreSQL and MySQL, the string is either a host:port specification or host name. For Oracle, the string is a DSN. """ def next()...
class IReplicaSelector(Interface): """Selects a database replica""" def current(): """Get the current replica. Return a string. For PostgreSQL and MySQL, the string is either a host:port specification or host name. For Oracle, the string is a DSN. """ def next():...
As for :meth:`IDBDriver.enter_critical_phase_until_transaction_end`. """ class IManagedLoadConnection(IManagedDBConnection): """ A managed connection intended for loading. """ class IManagedStoreConnection(IManagedDBConnection): """ A managed connection intended for storing data. """ ...
63
64
93
1
63
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IReplicaSelector
IReplicaSelector
620
635
620
620
2dee76b0e23fb1f77761fc6fdeab751af706456e
bigcode/the-stack
train
99b2754c4f7fd1e20b5dab17
train
class
""" class UnableToLockRowsToReadCurrentError(ReadConflictError, UnableToAcquireLockError): """ We were unable to lock one or more rows that belong to an object that ``Connection.readCurrent()`` was called on. This means another transaction already had the rows locked with intent to modify them...
"""
class UnableToLockRowsToReadCurrentError(ReadConflictError, UnableToAcquireLockError): """ We were unable to lock one or more rows that belong to an object that ``Connection.readCurrent()`` was called on. This means another transaction already had the rows locked with intent to modify them, and th...
more rows that we intend to modify due to a timeout. This means another transaction already had the rows locked, and thus we are in conflict with that transaction. Retrying the transaction may succeed. This is a type of ``ConflictError``, which is a transient error. """
64
64
88
2
62
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
UnableToLockRowsToReadCurrentError
UnableToLockRowsToReadCurrentError
1,654
1,664
1,654
1,654
24c861e56494898548036dd6293192941b728eec
bigcode/the-stack
train
9c4dd153975b7fc657686107
train
class
class IDBDialect(Interface): """ Handles converting from our internal "standard" SQL queries to something database specific. """ # TODO: Fill this in. def boolean_str(value): """ Given exactly a `bool` (`True` or `False`) return the string the database uses to represent...
class IDBDialect(Interface):
""" Handles converting from our internal "standard" SQL queries to something database specific. """ # TODO: Fill this in. def boolean_str(value): """ Given exactly a `bool` (`True` or `False`) return the string the database uses to represent that literal. By de...
too-many-ancestors,too-many-lines from relstorage.interfaces import Tuple from relstorage.interfaces import Object from relstorage.interfaces import Bool from relstorage.interfaces import Factory from relstorage.interfaces import IException ### # Abstractions to support multiple databases. ### class IDBDialect(Interf...
64
64
113
7
57
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IDBDialect
IDBDialect
36
51
36
36
2fa9b059fbe80e2e2ce5610383ac7d3f70673e42
bigcode/the-stack
train
a064f7019f74957be0df813b
train
class
"""The connection to the replica has been closed"""
"""The connection to the replica has been closed"""
exception without holding any other locks. :param cursor: The store cursor. :param read_current_oids: A mapping from oid integer to tid integer that the transaction expects. """ ### # Exceptions ### class ReplicaClosedException(Exception): """The connection to the replica ha...
64
64
11
11
53
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
UnableToAcquireLockError
UnableToAcquireLockError
1,627
1,628
1,627
1,627
4a9c44d1859a71ab82455ac312e7c5210341f9d2
bigcode/the-stack
train
6f6f86ffa53fffb7eb4a6522
train
class
class IObjectMover(Interface): """Move object states to/from the database and within the database.""" def load_current(cursor, oid): """ Returns the current state and integer tid for an object. *oid* is an integer. Returns (None, None) if object does not exist. """ ...
class IObjectMover(Interface): """Move object states to/from the database and within the database.""" def load_current(cursor, oid): """ Returns the current state and integer tid for an object. *oid* is an integer. Returns (None, None) if object does not exist. """ ...
PC, before taking out the final commit lock. Returns nothing. Typically this will be followed by a call to :meth:`detect_conflict`. """ def hold_commit_lock(cursor, ensure_current=True, nowait=False): """ Acquire the commit lock. If *ensure_current...
255
256
1,272
1
255
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IObjectMover
IObjectMover
753
927
753
753
3647623e38f16ea4232340e4ae28c7c3a4194c36
bigcode/the-stack
train
0fe638ae40e4c477fec67491
train
class
""" class IDBStats(Interface): """ Collecting, viewing and updating database information. """ def get_object_count(): """Returns the approximate number of objects in the database""" def get_db_size(): """Returns the approximate size of the database in bytes""" def lar...
"""
class IDBStats(Interface): """ Collecting, viewing and updating database information. """ def get_object_count(): """Returns the approximate number of objects in the database""" def get_db_size(): """Returns the approximate size of the database in bytes""" def large_database_...
:param store_connection: An :class:`IManagedStoreConnection` :return: A true value if the connection was rolled back without ignoring any exceptions; if an exception was ignored, returns a false value (and the connection and cursor are closed before th...
64
64
91
2
62
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IDBStats
IDBStats
1,200
1,216
1,200
1,200
753094be026fdb9e9f57d2f741f26839b924c9d8
bigcode/the-stack
train
7d55424da20f0e52dda67c92
train
class
class IDBDriverOptions(Interface): """ Implemented by a module to provide alternative drivers. """ database_type = Attribute("A string naming the type of database. Informational only.") def select_driver(driver_name=None): """ Choose and return an `IDBDriver`. The *driver_...
class IDBDriverOptions(Interface):
""" Implemented by a module to provide alternative drivers. """ database_type = Attribute("A string naming the type of database. Informational only.") def select_driver(driver_name=None): """ Choose and return an `IDBDriver`. The *driver_name* of "auto" is equivalent to a ...
DriverNotAvailableError): """ Raised when there are no drivers available. """ def __init__(self, driver_name='auto', driver_options=None, reason=None): super(NoDriversAvailableError, self).__init__(driver_name, driver_options, reason) class IDBDriverOptions(Interface):
64
64
163
8
56
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IDBDriverOptions
IDBDriverOptions
302
326
302
302
76cc4475ced7e2466d8badb86ec45544892ecb50
bigcode/the-stack
train
a7d67f229cdc338b0d2bb1f6
train
class
class IDBDriver(Interface): """ An abstraction over the information needed for RelStorage to work with an arbitrary DB-API driver. """ __name__ = Attribute("The name of this driver") disconnected_exceptions = Tuple( description=(u"A tuple of exceptions this driver can raise on any oper...
class IDBDriver(Interface):
""" An abstraction over the information needed for RelStorage to work with an arbitrary DB-API driver. """ __name__ = Attribute("The name of this driver") disconnected_exceptions = Tuple( description=(u"A tuple of exceptions this driver can raise on any operation if it is " ...
Interfaces provided by RelStorage database adapters""" from __future__ import absolute_import from ZODB.POSException import StorageError from ZODB.POSException import ReadConflictError from ZODB.POSException import ConflictError from zope.interface import Attribute from zope.interface import Interface # pylint:disabl...
256
256
1,264
7
249
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IDBDriver
IDBDriver
53
198
53
53
f0f5d165135adf8e950aa90a4bdd69d6ec336fa1
bigcode/the-stack
train
3397751b715b0b4d8f4e0650
train
class
class UnknownDriverError(DriverNotAvailableError): """ Raised when a driver that isn't registered at all is requested. """
class UnknownDriverError(DriverNotAvailableError):
""" Raised when a driver that isn't registered at all is requested. """
else: reason = '' return '%s: Driver %r is not available%s.%s' % ( type(self).__name__, self.driver_name, reason, self._format_drivers() ) __repr__ = __str__ class UnknownDriverError(DriverNotAvailableError):
63
64
27
10
53
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
UnknownDriverError
UnknownDriverError
287
290
287
287
a24df134de36f8af679e471bf9c96a425f7bfead
bigcode/the-stack
train
820edfcbb5cc478b303af105
train
class
class ITransactionControl(Interface): """Begin, commit, and abort transactions.""" def get_tid(cursor): """Returns the most recent tid.""" def add_transaction(cursor, tid, username, description, extension, packed=False): """Add a transaction.""" def delete_tr...
class ITransactionControl(Interface): """Begin, commit, and abort transactions.""" def get_tid(cursor): """Returns the most recent tid.""" def add_transaction(cursor, tid, username, description, extension, packed=False): """Add a transaction.""" def delete_tra...
. params should be either an empty tuple (no parameters) or a map. The statements are transformed by run_script_stmt before execution. """ def run_many(cursor, stmt, items): """Execute a statement repeatedly. Items should be a list of tuples. stmt should ...
108
109
366
1
108
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
ITransactionControl
ITransactionControl
1,145
1,198
1,145
1,145
6016e5debc0792eb5005e3f2db4f4d2b2ed86ac1
bigcode/the-stack
train
3a2a8b518c4dc7967bf93c40
train
class
class IOIDAllocator(Interface): """ Allocate OIDs and control future allocation. The cursor passed here must be from a :meth:`store connection <IConnectionManager.open_for_store>`. """ def new_oids(cursor): """ Return a new :class:`list` of new, unused integer OIDs. ...
class IOIDAllocator(Interface): """ Allocate OIDs and control future allocation. The cursor passed here must be from a :meth:`store connection <IConnectionManager.open_for_store>`. """ def new_oids(cursor): """ Return a new :class:`list` of new, unused integer OIDs. T...
oid, tid, filename): """Download a blob into a file. Returns the size of the blob file in bytes. """ def upload_blob(cursor, oid, tid, filename): """Upload a blob from a file. If tid is None, upload to the temporary table. """
63
64
153
1
63
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
IOIDAllocator
IOIDAllocator
930
955
930
930
d5c8fd594cb41cb9e1c77c5e4a5555ee121da493
bigcode/the-stack
train
d235b4d80ae3b7883969a7c4
train
class
###
###
immediately able to determine that 2 has been modified and quickly raise an exception without holding any other locks. :param cursor: The store cursor. :param read_current_oids: A mapping from oid integer to tid integer that the transaction expects. """ ### # Excep...
64
64
1
1
62
IMIO/relstorage
src/relstorage/adapters/interfaces.py
Python
ReplicaClosedException
ReplicaClosedException
1,624
1,625
1,624
1,624
d547b007e5e6ff3ed7aa6fece816a87a37ddacfc
bigcode/the-stack
train
76f18d7ffdc918ebaf526b22
train
class
class FFTWConan(ConanFile): name = "fftw" description = "C subroutine library for computing the Discrete Fourier Transform (DFT) in one or more dimensions" url = "https://github.com/conan-io/conan-center-index" homepage = "http://www.fftw.org/" license = "GPL-2.0" topics = ("conan", "fftw", "dft...
class FFTWConan(ConanFile):
name = "fftw" description = "C subroutine library for computing the Discrete Fourier Transform (DFT) in one or more dimensions" url = "https://github.com/conan-io/conan-center-index" homepage = "http://www.fftw.org/" license = "GPL-2.0" topics = ("conan", "fftw", "dft", "dct", "dst") exports...
from conans import ConanFile, CMake, tools from conans.errors import ConanInvalidConfiguration import os required_conan_version = ">=1.43.0" class FFTWConan(ConanFile):
47
256
1,370
10
37
rockandsalt/conan-center-index
recipes/fftw/all/conanfile.py
Python
FFTWConan
FFTWConan
7
132
7
7
9af2cd6cf3a4b05a8e7b5e1094d576817e2fac7b
bigcode/the-stack
train
9b99334db21928fd9904b6fe
train
class
class OrganizationIntegrationSetupPermissionTest(PermissionTestCase): def setUp(self): super(OrganizationIntegrationSetupPermissionTest, self).setUp() self.path = '/organizations/{}/integrations/example/setup/'.format( self.organization.slug, ) # this currently redirects the...
class OrganizationIntegrationSetupPermissionTest(PermissionTestCase):
def setUp(self): super(OrganizationIntegrationSetupPermissionTest, self).setUp() self.path = '/organizations/{}/integrations/example/setup/'.format( self.organization.slug, ) # this currently redirects the user @pytest.mark.xfail def test_manager_can_load(self): ...
from __future__ import absolute_import import pytest from sentry.testutils import PermissionTestCase, TestCase class OrganizationIntegrationSetupPermissionTest(PermissionTestCase):
35
64
120
11
23
hieast/sentry
tests/sentry/web/frontend/test_organization_integration_setup.py
Python
OrganizationIntegrationSetupPermissionTest
OrganizationIntegrationSetupPermissionTest
8
23
8
8
7c53d08c7d9b2221c39bbbb4a63a3bcc8cdab600
bigcode/the-stack
train
d7162a5c77a9f77b8130ed5b
train
class
class OrganizationIntegrationSetupTest(TestCase): def setUp(self): super(OrganizationIntegrationSetupTest, self).setUp() self.organization = self.create_organization(name='foo', owner=self.user) self.login_as(self.user) self.path = '/organizations/{}/integrations/example/setup/'.form...
class OrganizationIntegrationSetupTest(TestCase):
def setUp(self): super(OrganizationIntegrationSetupTest, self).setUp() self.organization = self.create_organization(name='foo', owner=self.user) self.login_as(self.user) self.path = '/organizations/{}/integrations/example/setup/'.format( self.organization.slug, ) ...
.mark.xfail def test_manager_can_load(self): self.assert_role_can_access(self.path, 'manager') # this currently redirects the user @pytest.mark.xfail def test_owner_can_load(self): self.assert_owner_can_access(self.path) class OrganizationIntegrationSetupTest(TestCase):
64
64
157
8
56
hieast/sentry
tests/sentry/web/frontend/test_organization_integration_setup.py
Python
OrganizationIntegrationSetupTest
OrganizationIntegrationSetupTest
26
44
26
26
f72d1abf6e5b87bedaa0a11372bccd9e19e4c72c
bigcode/the-stack
train
f86a30bdaf32e0c6aed2bc8b
train
function
def participants(request): participant_list = Participant.objects.all() context = { 'participant_list': participant_list, } return render(request, 'family_member_data/participants.html', context)
def participants(request):
participant_list = Participant.objects.all() context = { 'participant_list': participant_list, } return render(request, 'family_member_data/participants.html', context)
from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from .models import Participant def index(request): return render(request, 'family_member_data/index.html') def participants(request):
45
64
41
4
41
ctvanzandt42/django-secret-santa-generator
family_member_data/views.py
Python
participants
participants
11
16
11
11
97af7b2a0b6eb5b937442a287feea0ea296a905d
bigcode/the-stack
train
33b3a7b74d9a43522df9da65
train
function
def index(request): return render(request, 'family_member_data/index.html')
def index(request):
return render(request, 'family_member_data/index.html')
from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from .models import Participant def index(request):
29
64
16
4
24
ctvanzandt42/django-secret-santa-generator
family_member_data/views.py
Python
index
index
7
8
7
7
ecc979b5516dfa42759c831a0c45bd021c97448f
bigcode/the-stack
train
b8e772b69066ffdab8856add
train
function
def participant_details(request, participant_id): participant = get_object_or_404(Participant, pk=participant_id) context = { 'participant': participant, 'participant_id': participant_id, } return render(request, 'family_member_data/participant_detail.html', context)
def participant_details(request, participant_id):
participant = get_object_or_404(Participant, pk=participant_id) context = { 'participant': participant, 'participant_id': participant_id, } return render(request, 'family_member_data/participant_detail.html', context)
index(request): return render(request, 'family_member_data/index.html') def participants(request): participant_list = Participant.objects.all() context = { 'participant_list': participant_list, } return render(request, 'family_member_data/participants.html', context) def participant_detai...
64
64
60
8
56
ctvanzandt42/django-secret-santa-generator
family_member_data/views.py
Python
participant_details
participant_details
19
25
19
19
530e1073de01552e5be373626479f1c571135b1f
bigcode/the-stack
train
e49f917628f65c75bf802b96
train
function
def gen_nested_dict(inlist, val): inlist.reverse() for idx, item in enumerate(inlist): _indict = {item: val} if idx is 0 else {item: _indict} return _indict
def gen_nested_dict(inlist, val):
inlist.reverse() for idx, item in enumerate(inlist): _indict = {item: val} if idx is 0 else {item: _indict} return _indict
): try: # is it an int rv = int(value) except: try: # is it a float rv = float(value) except: # then return a str rv = value return rv def gen_nested_dict(inlist, val):
64
64
53
9
54
jakebrinkmann/espa-web
src/utils.py
Python
gen_nested_dict
gen_nested_dict
64
68
64
64
5f888aa6526b6880cc19afa733cf00b30d57305d
bigcode/the-stack
train
66f803d283bb8b165b76e0d4
train
class
class Order(APIObject): def __init__(self, **kwargs): super(Order, self).__init__(**kwargs)
class Order(APIObject):
def __init__(self, **kwargs): super(Order, self).__init__(**kwargs)
def __repr__(self): return str(self.__dict__) class User(APIObject): def __init__(self, **kwargs): super(User, self).__init__(**kwargs) @property def is_staff(self): return 'staff' in self.roles class Order(APIObject):
64
64
26
5
58
jakebrinkmann/espa-web
src/utils.py
Python
Order
Order
22
24
22
22
168fd2070ababce89c77e73b43e6f431357edffe
bigcode/the-stack
train
b0580d40bd4ae54667d57df8
train
function
def deep_update(source, overrides): """ update a nested dictionary. modify source in place credit: stackoverflow user charlax http://stackoverflow.com/questions/3232943 :param source: dictionary to update :param overrides: values to override :return: updated source """ for key, value...
def deep_update(source, overrides):
""" update a nested dictionary. modify source in place credit: stackoverflow user charlax http://stackoverflow.com/questions/3232943 :param source: dictionary to update :param overrides: values to override :return: updated source """ for key, value in overrides.iteritems(): i...
' in self.roles class Order(APIObject): def __init__(self, **kwargs): super(Order, self).__init__(**kwargs) class Scene(APIObject): def __init__(self, **kwargs): super(Scene, self).__init__(**kwargs) def deep_update(source, overrides):
64
64
123
7
57
jakebrinkmann/espa-web
src/utils.py
Python
deep_update
deep_update
32
47
32
32
729dae44bdfce3e92b595329586c18ba0912e307
bigcode/the-stack
train
22656fb56a40f3531d88e8a7
train
class
class APIObject(object): def __init__(self, **kwargs): for k, v in kwargs.iteritems(): self.__setattr__(k, v) def __repr__(self): return str(self.__dict__)
class APIObject(object):
def __init__(self, **kwargs): for k, v in kwargs.iteritems(): self.__setattr__(k, v) def __repr__(self): return str(self.__dict__)
import collections class APIObject(object):
8
64
48
5
2
jakebrinkmann/espa-web
src/utils.py
Python
APIObject
APIObject
4
10
4
4
4d075307d7fe63a88940b9cff92252138f0d81ba
bigcode/the-stack
train
b5d254e0c62773d72450532a
train
class
class Scene(APIObject): def __init__(self, **kwargs): super(Scene, self).__init__(**kwargs)
class Scene(APIObject):
def __init__(self, **kwargs): super(Scene, self).__init__(**kwargs)
**kwargs): super(User, self).__init__(**kwargs) @property def is_staff(self): return 'staff' in self.roles class Order(APIObject): def __init__(self, **kwargs): super(Order, self).__init__(**kwargs) class Scene(APIObject):
64
64
26
5
59
jakebrinkmann/espa-web
src/utils.py
Python
Scene
Scene
27
29
27
27
d0e217903c5da867aaf3b09952682f5232fdd7f8
bigcode/the-stack
train
24f5e6f7b0cbfe43d9596e79
train
class
class User(APIObject): def __init__(self, **kwargs): super(User, self).__init__(**kwargs) @property def is_staff(self): return 'staff' in self.roles
class User(APIObject):
def __init__(self, **kwargs): super(User, self).__init__(**kwargs) @property def is_staff(self): return 'staff' in self.roles
import collections class APIObject(object): def __init__(self, **kwargs): for k, v in kwargs.iteritems(): self.__setattr__(k, v) def __repr__(self): return str(self.__dict__) class User(APIObject):
56
64
45
5
51
jakebrinkmann/espa-web
src/utils.py
Python
User
User
13
19
13
13
a55e9fab1bd3c7df1f579055d800be8dfdaca7a1
bigcode/the-stack
train
0036e83c4b7e6d739823b56f
train
function
def format_messages(inmessages): outlist = [] if isinstance(inmessages, dict): for key in inmessages: outlist.append(key+"<br/>") if isinstance(inmessages[key], basestring): outlist.append(inmessages[key]) else: for item in inmessages[k...
def format_messages(inmessages):
outlist = [] if isinstance(inmessages, dict): for key in inmessages: outlist.append(key+"<br/>") if isinstance(inmessages[key], basestring): outlist.append(inmessages[key]) else: for item in inmessages[key]: outlist....
return rv def gen_nested_dict(inlist, val): inlist.reverse() for idx, item in enumerate(inlist): _indict = {item: val} if idx is 0 else {item: _indict} return _indict def format_messages(inmessages):
64
64
151
6
57
jakebrinkmann/espa-web
src/utils.py
Python
format_messages
format_messages
71
88
71
71
a81506a8ad0df4a9ec41efaaae7be5314dbc1188
bigcode/the-stack
train
dbda45f6ca6ebd8d8d0c7e48
train
function
def is_num(value): try: # is it an int rv = int(value) except: try: # is it a float rv = float(value) except: # then return a str rv = value return rv
def is_num(value):
try: # is it an int rv = int(value) except: try: # is it a float rv = float(value) except: # then return a str rv = value return rv
source """ for key, value in overrides.iteritems(): if isinstance(value, collections.Mapping) and value: returned = deep_update(source.get(key, {}), value) source[key] = returned else: source[key] = overrides[key] return source def is_num(value):
64
64
59
5
58
jakebrinkmann/espa-web
src/utils.py
Python
is_num
is_num
50
61
50
50
b098e7b9cf5bc205c3c79f130bef3624cbf4ad12
bigcode/the-stack
train
cc4f02bb375c34ec53a2935b
train
class
class NodeTypeEdgeFeatureGraphCRF(TypedCRF): """ Pairwise CRF with features/strength associated to each edge and different types of nodes Pairwise potentials are asymmetric and shared over all edges of same type. They are weighted by an edge-specific features, though. This allows for contrast s...
class NodeTypeEdgeFeatureGraphCRF(TypedCRF):
""" Pairwise CRF with features/strength associated to each edge and different types of nodes Pairwise potentials are asymmetric and shared over all edges of same type. They are weighted by an edge-specific features, though. This allows for contrast sensitive potentials or directional potentials...
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software...
256
256
3,792
13
242
LemonLison/pystruct
pystruct/models/node_type_edge_feature_graph_crf.py
Python
NodeTypeEdgeFeatureGraphCRF
NodeTypeEdgeFeatureGraphCRF
41
440
41
41
a32c4901dd7864b18bee6bf4e30f063ebe970832
bigcode/the-stack
train
12daebebd0cd43635a64986d
train
class
class WSPool(interfaces.TokenInterface): # Python 3.7 hint #_outgoing_starting: Dict[PoolKey, asyncio.Task] #_pool: Dict[PoolKey, WSRemote] # #_servers: List[websockets.WebSocketServer] def __init__(self, tman, log, loop): self.loop = loop self._pool = {} self._outgoing...
class WSPool(interfaces.TokenInterface): # Python 3.7 hint #_outgoing_starting: Dict[PoolKey, asyncio.Task] #_pool: Dict[PoolKey, WSRemote] # #_servers: List[websockets.WebSocketServer]
def __init__(self, tman, log, loop): self.loop = loop self._pool = {} self._outgoing_starting = {} self._servers = [] self._tokenmanager = tman self.log = log @classmethod async def create_transport(cls, tman: interfaces.TokenManager, log, loop, *, client_...
_code)) # Unlike _send_message, this is pulled out of the the _abort_with function # as it's also used in _run_recv_loop async def _abort_with_waiting(self, msg, *, close_code): self.log.debug("Aborting with message: %r", msg) try: await self._connection.send(_serialize(msg)) ...
256
256
1,542
63
193
DylanJPettij/CoapTemperatureSensor
build/lib/aiocoap/transports/ws.py
Python
WSPool
WSPool
159
359
159
165
d905ddd46a365bcade31f819359ade5ec9891c03
bigcode/the-stack
train
50e80f60755ceb184528cb68
train
class
class WSRemote(rfc8323common.RFC8323Remote, interfaces.EndpointAddress): _connection: websockets.WebSocketCommonProtocol # Only used to ensure that remotes are associated to the right pool -- not # that there'd be any good reason to have multiple of those. # Python 3.7 hint #_pool: weakref.Reference...
class WSRemote(rfc8323common.RFC8323Remote, interfaces.EndpointAddress):
_connection: websockets.WebSocketCommonProtocol # Only used to ensure that remotes are associated to the right pool -- not # that there'd be any good reason to have multiple of those. # Python 3.7 hint #_pool: weakref.ReferenceType # [WSPool] -- but that'd be circular scheme = None # Override p...
:tokenoffset + tkl] msg = Message(code=code, token=token) msg.payload = msg.opt.decode(data[tokenoffset + tkl:]) return msg def _serialize(msg: Message) -> bytes: tkl = len(msg.token) if tkl > 8: raise ValueError("Overly long token") data = [ bytes((tkl, msg.code,)), ...
157
157
526
18
139
DylanJPettij/CoapTemperatureSensor
build/lib/aiocoap/transports/ws.py
Python
WSRemote
WSRemote
103
157
103
103
fbdddc1dc1e2b3d02b61bca64f04b6b0196854a8
bigcode/the-stack
train
51d342f8328921299d6c4c9f
train
function
def _serialize(msg: Message) -> bytes: tkl = len(msg.token) if tkl > 8: raise ValueError("Overly long token") data = [ bytes((tkl, msg.code,)), msg.token, msg.opt.encode(), ] if msg.payload: data += [b'\xff', msg.payload] return b"".j...
def _serialize(msg: Message) -> bytes:
tkl = len(msg.token) if tkl > 8: raise ValueError("Overly long token") data = [ bytes((tkl, msg.code,)), msg.token, msg.opt.encode(), ] if msg.payload: data += [b'\xff', msg.payload] return b"".join(data)
token") code = data[codeoffset] token = data[tokenoffset:tokenoffset + tkl] msg = Message(code=code, token=token) msg.payload = msg.opt.decode(data[tokenoffset + tkl:]) return msg def _serialize(msg: Message) -> bytes:
64
64
85
10
53
DylanJPettij/CoapTemperatureSensor
build/lib/aiocoap/transports/ws.py
Python
_serialize
_serialize
86
99
86
86
42a475a10e8c71c84a101acec286d028e5890ce1
bigcode/the-stack
train
bb5238d2f7e0d78d207bc82a
train
function
def _decode_message(data: bytes) -> Message: codeoffset = 1 tokenoffset = 2 tkl = data[0] if tkl > 8: raise error.UnparsableMessage("Overly long token") code = data[codeoffset] token = data[tokenoffset:tokenoffset + tkl] msg = Message(code=code, token=token) msg.payload = msg....
def _decode_message(data: bytes) -> Message:
codeoffset = 1 tokenoffset = 2 tkl = data[0] if tkl > 8: raise error.UnparsableMessage("Overly long token") code = data[codeoffset] token = data[tokenoffset:tokenoffset + tkl] msg = Message(code=code, token=token) msg.payload = msg.opt.decode(data[tokenoffset + tkl:]) ret...
, Optional from collections import namedtuple import asyncio import functools import http import weakref from aiocoap import Message, interfaces, ABORT, util from aiocoap.transports import rfc8323common import websockets def _decode_message(data: bytes) -> Message:
64
64
106
11
52
DylanJPettij/CoapTemperatureSensor
build/lib/aiocoap/transports/ws.py
Python
_decode_message
_decode_message
70
84
70
70
d016d2d1728c9c3d45e5b97ab77daceba7a906da
bigcode/the-stack
train
294822fab4fb8f23669495c0
train
class
class EncoderBase(nn.Module): """ Base encoder class. Specifies the interface used by different encoder types and required by :obj:`onmt.Models.NMTModel`. .. mermaid:: graph BT A[Input] subgraph RNN C[Pos 1] D[Pos 2] E[Pos N] end...
class EncoderBase(nn.Module):
""" Base encoder class. Specifies the interface used by different encoder types and required by :obj:`onmt.Models.NMTModel`. .. mermaid:: graph BT A[Input] subgraph RNN C[Pos 1] D[Pos 2] E[Pos N] end F[Memory_Bank] ...
"""Base class for encoders and generic multi encoders.""" from __future__ import division import torch.nn as nn from onmt.utils.misc import aeq class EncoderBase(nn.Module):
40
87
291
6
33
sys1874/OpenNMT-py
onmt/encoders/encoder.py
Python
EncoderBase
EncoderBase
10
54
10
10
c31cc4a35b644afd02ed144dc6b0bcf61fbd7d1e
bigcode/the-stack
train
3e6da6c0a9429211756005cc
train
function
def get_args(args=None): return _parser.parse_args(args)
def get_args(args=None):
return _parser.parse_args(args)
("-t", "--test", "--dry-run", action="store_true", help="Verify only") _parser.add_argument("-v", "--verbose", action="store_true", help="Output more information for diagnostic") _parser.add_argument("source", help="Base directory from config file") def get_args(args=None):
64
64
14
6
58
ttimasdf/ebp
ebp/options.py
Python
get_args
get_args
20
21
20
20
8072903c9c01ffd83c068b22a2e003e0ccda26db
bigcode/the-stack
train
ab9827d7a1fb0f55fac5ca56
train
class
@mx.operator.register("intdense") class IntDenseProp(mx.operator.CustomOpProp): def __init__(self, bit, num_hidden): super(IntDenseProp, self).__init__(True) # we use constant bias here to illustrate how to pass arguments # to operators. All arguments are in string format so you nee...
@mx.operator.register("intdense") class IntDenseProp(mx.operator.CustomOpProp):
def __init__(self, bit, num_hidden): super(IntDenseProp, self).__init__(True) # we use constant bias here to illustrate how to pass arguments # to operators. All arguments are in string format so you need # to convert them back to the type you want. self.num_bit = bit ...
num_bit = self.num_bit.as_in_context(x.context) frac_len = num_bit - int_len f = (2 ** (frac_len)).astype('float32') int_x = ((x * f)).floor() int_w = ((w * f)).floor() return int_x, int_w, frac_len return x, w, 0 @mx.operator.register("intdense...
97
97
324
18
78
CortexFoundation/tvm-cvm
tutorials/Quantization/layers.py
Python
IntDenseProp
IntDenseProp
110
143
110
113
739a9ed94b7785a69087417bbf0fd92fffc20125
bigcode/the-stack
train
15777e0dffe948c15de49366
train
class
@mx.operator.register("intconv") class IntConvProp(mx.operator.CustomOpProp): def __init__(self, bit, num_filter, kernel, stride=[], pad=[], no_bias=False, workspace=1024, name=None): super(IntConvProp, self).__init__(True) # we use constant bias here to illustrate how to pass arguments ...
@mx.operator.register("intconv") class IntConvProp(mx.operator.CustomOpProp):
def __init__(self, bit, num_filter, kernel, stride=[], pad=[], no_bias=False, workspace=1024, name=None): super(IntConvProp, self).__init__(True) # we use constant bias here to illustrate how to pass arguments # to operators. All arguments are in string format so you need # to co...
)) max2 = nd.max(nd.abs(w)) if max1 > max2: max = max1 else: max = max2 if max != 0: int_len = (nd.ceil(nd.log2(max))).astype('float32') num_bit = self.num_bit.as_in_context(x.context) frac_len = num_bit - int_len ...
156
156
521
18
137
CortexFoundation/tvm-cvm
tutorials/Quantization/layers.py
Python
IntConvProp
IntConvProp
301
344
301
303
66f7049fd9a1039639966b876d858e86a83f8193
bigcode/the-stack
train
0cd72d40f8ede44d4d23569d
train
class
class IntBatch(mx.operator.CustomOp): def __init__(self, bit, eps=0.001, momentum=0.9, fix_gamma=False, name=''): self.num_bit = nd.array([bit]) self.eps = eps self.momentum = momentum self.fix_gamma = fix_gamma self.name = name def forward(self, is_train, req, i...
class IntBatch(mx.operator.CustomOp):
def __init__(self, bit, eps=0.001, momentum=0.9, fix_gamma=False, name=''): self.num_bit = nd.array([bit]) self.eps = eps self.momentum = momentum self.fix_gamma = fix_gamma self.name = name def forward(self, is_train, req, in_data, out_data, aux): #globa...
, in_grad, aux): dx1 = in_grad[0] dx2 = in_grad[1] dy = out_grad[0] dx1 = dy / (2**-1) dx2 = dy / (2**-1) self.assign(in_grad[0], req[0], dx1) self.assign(in_grad[1], req[0], dx2) @mx.operator.register("short_cut") class IntAddProp(mx.operator.CustomOpProp): def __init__(self, name=''): ...
256
256
1,540
8
248
CortexFoundation/tvm-cvm
tutorials/Quantization/layers.py
Python
IntBatch
IntBatch
394
532
394
394
b696dce400e89d3c203b84c5c5a4eedd5de6b74b
bigcode/the-stack
train
76be67c9225fc1e19c045d51
train
class
class IntDense(mx.operator.CustomOp): def __init__(self, bit, num_hidden): self.num_bit = nd.array([bit]) self.num_hidden = num_hidden def forward(self, is_train, req, in_data, out_data, aux): if is_train: x = in_data[0] w = in_data[1] b = ...
class IntDense(mx.operator.CustomOp):
def __init__(self, bit, num_hidden): self.num_bit = nd.array([bit]) self.num_hidden = num_hidden def forward(self, is_train, req, in_data, out_data, aux): if is_train: x = in_data[0] w = in_data[1] b = in_data[2] quan_w = in_data[...
# -*- coding:utf-8 -*- import os import mxnet as mx import numpy as np import logging from mxnet import nd from mxnet import autograd from math import floor from mxnet.test_utils import get_mnist_iterator import copy class IntDense(mx.operator.CustomOp):
65
256
929
8
56
CortexFoundation/tvm-cvm
tutorials/Quantization/layers.py
Python
IntDense
IntDense
12
108
12
13
b29c6356aad62f3bc01d3129893acc3645bdc655
bigcode/the-stack
train
90e64ddb2b4ba0729dba828b
train
class
class IntConv(mx.operator.CustomOp): def __init__(self, bit, num_filter, kernel, stride=[], pad=[], no_bias=False, workspace=1024, name=None): self.num_bit = nd.array([bit]) self.num_filter = num_filter self.kernel = kernel self.stride = stride self.pad = pad s...
class IntConv(mx.operator.CustomOp):
def __init__(self, bit, num_filter, kernel, stride=[], pad=[], no_bias=False, workspace=1024, name=None): self.num_bit = nd.array([bit]) self.num_filter = num_filter self.kernel = kernel self.stride = stride self.pad = pad self.no_bias = no_bias self.wo...
back to the type you want. self.num_bit = bit self.num_hidden = np.long(num_hidden) def list_arguments(self): return ['data', 'weight', 'bias', 'quan_weight', 'quan_bias', 'y_shift_bit'] def list_outputs(self): # this can be omitted if you only have 1 output. ...
256
256
1,644
8
248
CortexFoundation/tvm-cvm
tutorials/Quantization/layers.py
Python
IntConv
IntConv
145
299
145
145
4df51af155ea95e396756ad52d959b064677f411
bigcode/the-stack
train
35e6639a8feae5188be2af36
train
class
class IntAdd(mx.operator.CustomOp): def __init__(self, name=''): self.name = name def forward(self, is_train, req, in_data, out_data, aux): input_1 = in_data[0] input_2 = in_data[1] output = out_data[0] output = input_1 * (2**-1) + input_2 * (2**-1) output = output.round() self.assign(out...
class IntAdd(mx.operator.CustomOp):
def __init__(self, name=''): self.name = name def forward(self, is_train, req, in_data, out_data, aux): input_1 = in_data[0] input_2 = in_data[1] output = out_data[0] output = input_1 * (2**-1) + input_2 * (2**-1) output = output.round() self.assign(out_data[0], req[0], output) def bac...
.pad, self.no_bias, self.workspace, self.name) def f(self, x, k, p, s, d): return floor((x + 2 * p - d * (k - 1) - 1) / s) + 1 class IntAdd(mx.operator.CustomOp):
65
65
217
8
56
CortexFoundation/tvm-cvm
tutorials/Quantization/layers.py
Python
IntAdd
IntAdd
346
370
346
346
4ec452aa6c3fd9002c22b6957e9e0e382843db56
bigcode/the-stack
train
dc8fb079cbd3bc728ecdfc77
train
class
@mx.operator.register("batchnorm_int") class IntBatchProp(mx.operator.CustomOpProp): def __init__(self, bit, eps=0.001, momentum=0.9, fix_gamma=1, name=''): super(IntBatchProp, self).__init__(True) self.num_bit = bit self.eps = eps self.momentum = momentum self.fix_g...
@mx.operator.register("batchnorm_int") class IntBatchProp(mx.operator.CustomOpProp):
def __init__(self, bit, eps=0.001, momentum=0.9, fix_gamma=1, name=''): super(IntBatchProp, self).__init__(True) self.num_bit = bit self.eps = eps self.momentum = momentum self.fix_gamma = fix_gamma self.name = name def list_arguments(self): retu...
astype('float32') num_bit = self.num_bit.as_in_context(x.context) frac_len = num_bit - int_len f = (2 ** (frac_len)).astype('float32') int_x = ((x * f)).floor() int_w = ((w * f)).floor() return int_x, int_w, frac_len return x, w, 0 @...
104
104
349
19
84
CortexFoundation/tvm-cvm
tutorials/Quantization/layers.py
Python
IntBatchProp
IntBatchProp
534
567
534
536
3a99b75ba458062217a650f742b6bebbea837d0e
bigcode/the-stack
train
14e68172f1040bac7be27b4a
train
class
@mx.operator.register("short_cut") class IntAddProp(mx.operator.CustomOpProp): def __init__(self, name=''): super(IntAddProp, self).__init__(True) self.name = name def list_arguments(self): return ['data1', 'data2'] def list_outputs(self): return ['output'] def infer_shape(self, in_shapes): ...
@mx.operator.register("short_cut") class IntAddProp(mx.operator.CustomOpProp):
def __init__(self, name=''): super(IntAddProp, self).__init__(True) self.name = name def list_arguments(self): return ['data1', 'data2'] def list_outputs(self): return ['output'] def infer_shape(self, in_shapes): data_shape = in_shapes[0] return [data_shape, data_shape], [data_shape], [] ...
-1) dx2 = dy / (2**-1) self.assign(in_grad[0], req[0], dx1) self.assign(in_grad[1], req[0], dx2) @mx.operator.register("short_cut") class IntAddProp(mx.operator.CustomOpProp):
64
64
157
18
46
CortexFoundation/tvm-cvm
tutorials/Quantization/layers.py
Python
IntAddProp
IntAddProp
371
392
371
372
89c501669ead75eecb55437e9231657543980497
bigcode/the-stack
train
e1a0274d5d12200cebbe3b82
train
class
class CpCrashRegisterReader(DataAbortRegisterReader): """ This is a :py:class:`~.DataAbortRegisterReader` that uses the ``cp`` console command to trigger the Data Abort used to read registers. """ _required = { 'arch': 'ARM', 'commands': ['cp'], 'crash_or_reboot': True, ...
class CpCrashRegisterReader(DataAbortRegisterReader):
""" This is a :py:class:`~.DataAbortRegisterReader` that uses the ``cp`` console command to trigger the Data Abort used to read registers. """ _required = { 'arch': 'ARM', 'commands': ['cp'], 'crash_or_reboot': True, } @classmethod def rank(cls, **_kwargs): ...
# SPDX-License-Identifier: BSD-3-Clause # Depthcharge: <https://github.com/nccgroup/depthcharge> """ Implements FDTCrashRegisterReader """ from ..operation import Operation from .data_abort import DataAbortRegisterReader class CpCrashRegisterReader(DataAbortRegisterReader):
62
64
165
10
51
youssefms/depthcharge
python/depthcharge/register/cp.py
Python
CpCrashRegisterReader
CpCrashRegisterReader
12
32
12
12
b5cf04d1bf4c20a9ecb427ba17074119ffce7672
bigcode/the-stack
train
d6b681ab745a5be9c1bcc1a0
train
function
def layer(op): '''Decorator for composable network layers.''' def layer_decorated(self, *args, **kwargs): # Automatically set a name if not provided. name = kwargs.setdefault('name', self.get_unique_name(op.__name__)) # Figure out the layer inputs. if len(self.terminals) == 0: ...
def layer(op):
'''Decorator for composable network layers.''' def layer_decorated(self, *args, **kwargs): # Automatically set a name if not provided. name = kwargs.setdefault('name', self.get_unique_name(op.__name__)) # Figure out the layer inputs. if len(self.terminals) == 0: rais...
import numpy as np import tensorflow as tf slim = tf.contrib.slim DEFAULT_PADDING = 'SAME' def layer(op):
28
64
203
4
24
VisualMine/PlaneNet
code/kaffe/tensorflow/network.py
Python
layer
layer
8
30
8
8
d90de5edee908ca8bda8b0f82c57af73484c839a
bigcode/the-stack
train
1209653137ac029c1ab6213e
train
class
class Network(object): def __init__(self, inputs, options, trainable=True, is_training=False): # The input nodes for this network self.inputs = inputs # The current list of terminal nodes self.terminals = [] # Mapping from layer names to layers self.layers = dict(inp...
class Network(object):
def __init__(self, inputs, options, trainable=True, is_training=False): # The input nodes for this network self.inputs = inputs # The current list of terminal nodes self.terminals = [] # Mapping from layer names to layers self.layers = dict(inputs) # If true, ...
import numpy as np import tensorflow as tf slim = tf.contrib.slim DEFAULT_PADDING = 'SAME' def layer(op): '''Decorator for composable network layers.''' def layer_decorated(self, *args, **kwargs): # Automatically set a name if not provided. name = kwargs.setdefault('name', self.get_unique_na...
231
256
2,241
4
226
VisualMine/PlaneNet
code/kaffe/tensorflow/network.py
Python
Network
Network
33
294
33
34
940c22116e554926948e4fa26ab4eb25135c7648
bigcode/the-stack
train
f866611c6fe4b08f904a9c33
train
function
def climbStairs(N): if not N: return 1 steps = [0] * (N+1) steps[0] = steps[1] = 1 for i in range(2, N+1): steps[i] = steps[i-1] + steps[i-2] return steps[-1]
def climbStairs(N):
if not N: return 1 steps = [0] * (N+1) steps[0] = steps[1] = 1 for i in range(2, N+1): steps[i] = steps[i-1] + steps[i-2] return steps[-1]
[1, 1], [2] Input 2: A = 3 Output 2: 3 Explanation 2: [1 1 1], [1 2], [2 1] ''' # @param N : integer # @return an integer def climbStairs(N):
64
64
75
6
57
loghmanb/daily-coding-problem
amazon_stairs.py
Python
climbStairs
climbStairs
41
48
41
41
a436a09e880e073fbec3304fe3a7369447cec663
bigcode/the-stack
train
561df0bdc9c0fcbe9b874687
train
function
def get_metadata(path, tags, rls_data=None): """ Get metadata pertaining to a release from various metadata sources. Have the user decide which sources to use, and then combine their information. """ click.secho(f"\nChecking metadata...", fg="cyan", bold=True) searchstrs = make_searchstrs(rls_da...
def get_metadata(path, tags, rls_data=None):
""" Get metadata pertaining to a release from various metadata sources. Have the user decide which sources to use, and then combine their information. """ click.secho(f"\nChecking metadata...", fg="cyan", bold=True) searchstrs = make_searchstrs(rls_data["artists"], rls_data["title"]) kwargs ...
from salmon.search import SEARCHSOURCES, run_metasearch from salmon.tagger.combine import combine_metadatas from salmon.tagger.sources import METASOURCES from salmon.tagger.sources.base import generate_artists loop = asyncio.get_event_loop() def get_metadata(path, tags, rls_data=None):
64
64
193
12
52
Junkbite/smoked-salmon
salmon/tagger/metadata.py
Python
get_metadata
get_metadata
18
36
18
18
c67bcd90ee157acdde44a4c048f917339ae34695
bigcode/the-stack
train
349bc5f6503e296751c66d21
train
function
def clean_metadata(metadata): for disc, tracks in metadata["tracks"].items(): for num, track in tracks.items(): for artist, importance in copy(track["artists"]): guest_artists = { re_strip(a) for a, i in track["artists"] ...
def clean_metadata(metadata):
for disc, tracks in metadata["tracks"].items(): for num, track in tracks.items(): for artist, importance in copy(track["artists"]): guest_artists = { re_strip(a) for a, i in track["artists"] if i in {"guest", "remixer"} ...
(): artists = [] for artist, importance in track["artists"]: if ( "various artists" not in artist.lower() or artist.lower().strip() != "various" ): artists.append((artist, importance)) track["...
64
64
179
5
58
Junkbite/smoked-salmon
salmon/tagger/metadata.py
Python
clean_metadata
clean_metadata
186
205
186
186
c1160aa16a24c1d570a590823d6405c03539af5c
bigcode/the-stack
train
6a74c9a76896ede6b9f2757e
train
function
def _select_choice(choices, rls_data): """ Allow the user to select a metadata choice. Then, if the metadata came from a scraper, run the scrape(s) and return combined metadata. """ while True: if choices: res = click.prompt( click.style( "\nWh...
def _select_choice(choices, rls_data):
""" Allow the user to select a metadata choice. Then, if the metadata came from a scraper, run the scrape(s) and return combined metadata. """ while True: if choices: res = click.prompt( click.style( "\nWhich metadata results would you like to ...
_found.remove(source) results = dict(islice(releases.items(), config.SEARCH_LIMIT)) for rls_id, release in results.items(): choices[choice_id] = (source, rls_id) url = SEARCHSOURCES[source].Searcher.format_url(rls_id) click.secho(f"> {choice_id:02d...
132
132
442
11
120
Junkbite/smoked-salmon
salmon/tagger/metadata.py
Python
_select_choice
_select_choice
66
123
66
66
47578d415bca7955663e66fd299d9f730e2cdc2f
bigcode/the-stack
train
4486fc8957601dbe64f77659
train
function
def _print_search_results(results, rls_data=None): """Print the results from the metadata source.""" if rls_data: _print_metadata(rls_data, metadata_name="Previous") choices = {} choice_id = 1 not_found = list(SEARCHSOURCES.keys()) for source, releases in results.items(): if rel...
def _print_search_results(results, rls_data=None):
"""Print the results from the metadata source.""" if rls_data: _print_metadata(rls_data, metadata_name="Previous") choices = {} choice_id = 1 not_found = list(SEARCHSOURCES.keys()) for source, releases in results.items(): if releases: click.secho(f"\nResults for {sou...
filter=False, track_count=len(tags), **kwargs ) choices = _print_search_results(search_results, rls_data) metadata = _select_choice(choices, rls_data) remove_various_artists(metadata["tracks"]) return metadata def _print_search_results(results, rls_data=None):
66
66
220
12
53
Junkbite/smoked-salmon
salmon/tagger/metadata.py
Python
_print_search_results
_print_search_results
39
63
39
39
565e375413412bd4502e80bb62f6c64d2e42403a
bigcode/the-stack
train
14fc7a9472d0b40a6887f573
train
function
def _print_metadata(metadata, metadata_name="Pending"): """Print the metadata that is a part of the new metadata.""" click.secho(f"\n{metadata_name} metadata:", fg="yellow", bold=True) click.echo( f"> TRACK COUNT : {sum(len(d.values()) for d in metadata['tracks'].values())}" ) click.echo("...
def _print_metadata(metadata, metadata_name="Pending"):
"""Print the metadata that is a part of the new metadata.""" click.secho(f"\n{metadata_name} metadata:", fg="yellow", bold=True) click.echo( f"> TRACK COUNT : {sum(len(d.values()) for d in metadata['tracks'].values())}" ) click.echo("> ARTISTS:") for artist in metadata["artists"]: ...
"], str): metadata_dict["genres"] = [metadata_dict["genres"]] return metadata_dict except (TypeError, json.decoder.JSONDecodeError): click.confirm( click.style( "Metadata is not a valid JSON file, retry?", fg="magenta", bold=True ...
85
85
286
11
74
Junkbite/smoked-salmon
salmon/tagger/metadata.py
Python
_print_metadata
_print_metadata
149
170
149
149
879dcc34ebcf7994efffe323ff95f3a5c73dda28
bigcode/the-stack
train
e3d9c1f261c7811da60ae465
train
function
def _get_manual_metadata(rls_data): """ Use the metadata built from the file tags as a base, then allow the user to edit that dictionary. """ metadata = json.dumps(rls_data, indent=2) while True: try: metadata = click.edit(metadata, extension=".json") or metadata ...
def _get_manual_metadata(rls_data):
""" Use the metadata built from the file tags as a base, then allow the user to edit that dictionary. """ metadata = json.dumps(rls_data, indent=2) while True: try: metadata = click.edit(metadata, extension=".json") or metadata metadata_dict = json.loads(metadata)...
m) for s, m in zip(sources, metadatas) if m), base=rls_data ) meta = clean_metadata(meta) meta["artists"], meta["tracks"] = generate_artists(meta["tracks"]) return meta def _get_manual_metadata(rls_data):
64
64
162
10
53
Junkbite/smoked-salmon
salmon/tagger/metadata.py
Python
_get_manual_metadata
_get_manual_metadata
126
146
126
126
c6e69aa08317ea1647f8b6d51ea42cf1181467ae
bigcode/the-stack
train
74fe6b64fa86fae843945120
train
function
def remove_various_artists(tracks): for dnum, disc in tracks.items(): for tnum, track in disc.items(): artists = [] for artist, importance in track["artists"]: if ( "various artists" not in artist.lower() or artist.lower().strip...
def remove_various_artists(tracks):
for dnum, disc in tracks.items(): for tnum, track in disc.items(): artists = [] for artist, importance in track["artists"]: if ( "various artists" not in artist.lower() or artist.lower().strip() != "various" ): ...
.echo(f"> RELEASE TYPE : {metadata['rls_type']}") click.echo(f"> COMMENT : {metadata['comment']}") click.echo(f"> URLS:") for url in metadata["urls"]: click.echo(f">>> {url}") def remove_various_artists(tracks):
63
64
87
9
54
Junkbite/smoked-salmon
salmon/tagger/metadata.py
Python
remove_various_artists
remove_various_artists
173
183
173
173
fdeb5ba1ee4586f86dc22a7ebf9907899afbb97d
bigcode/the-stack
train
cd953280a9dea7fb14862149
train
function
def run_latency_per_round(train_loader, test_loader, comm_matrix, num_rounds, epochs, num_clients, latency_nodes, latency_rounds, net='net', optimizer='sgd', lr=0.1): """ Runs a decentralized optimization algorithm for the given learning rate for a number of rounds, over some network. Some nodes sen...
def run_latency_per_round(train_loader, test_loader, comm_matrix, num_rounds, epochs, num_clients, latency_nodes, latency_rounds, net='net', optimizer='sgd', lr=0.1):
""" Runs a decentralized optimization algorithm for the given learning rate for a number of rounds, over some network. Some nodes send their weights with a one-rounds latency, only during specific rounds. Outputs the accuracies and returns them. Params: train_loader (array): the list of all...
_nodes) if (r > 0): diffuse_params_latency(old_client_models, old_comm_matrix, np.setdiff1d(np.array(range(num_clients)), latency_nodes)) print("old topo: {}, new topo: {}".format(old_topo, topo)) average_models(global_model, client_models) test_loss, acc = evaluate(global_m...
190
190
634
46
143
giordano-lucas/DeAI
simulator/simulator-topologies-fault-tolerance/latency/latency.py
Python
run_latency_per_round
run_latency_per_round
113
168
113
114
58551f8f6e8fd03c1b256e87a3edd1acdb75e53b
bigcode/the-stack
train
de80cd75d1e4eab4477b9a9d
train
function
def run_latency_changing_topo(train_loader, test_loader, num_rounds, epochs, num_clients, latency_nodes, net='net', optimizer='sgd', lr=0.1): """ Runs a decentralized optimization algorithm for the given learning rate for a number of rounds, over some network. Some nodes send their weights with a on...
def run_latency_changing_topo(train_loader, test_loader, num_rounds, epochs, num_clients, latency_nodes, net='net', optimizer='sgd', lr=0.1):
""" Runs a decentralized optimization algorithm for the given learning rate for a number of rounds, over some network. Some nodes send their weights with a one-rounds latency, for the entire execution. The network topology evolves over time. Outputs the accuracies and returns them. Params: ...
train_loader[i], epoch=epochs) # diffuse params diffuse_params_latency(client_models, comm_matrix, latency_nodes) if (r > 0): diffuse_params_latency(old_client_models, comm_matrix, np.setdiff1d(np.array(range(num_clients)), latency_nodes)) average_models(global_model, clie...
190
190
635
41
148
giordano-lucas/DeAI
simulator/simulator-topologies-fault-tolerance/latency/latency.py
Python
run_latency_changing_topo
run_latency_changing_topo
56
111
56
57
294c0a959ed5c4d9592a81c3f091b4f1ca1872cf
bigcode/the-stack
train
72ee503dec7de5b97cab34fc
train
function
def run_latency(train_loader, test_loader, comm_matrix, num_rounds, epochs, num_clients, latency_nodes, net='net', optimizer='sgd', lr=0.1): """ Runs a decentralized optimization algorithm for the given learning rate for a number of rounds, over some network. Some nodes send their weights with a one...
def run_latency(train_loader, test_loader, comm_matrix, num_rounds, epochs, num_clients, latency_nodes, net='net', optimizer='sgd', lr=0.1):
""" Runs a decentralized optimization algorithm for the given learning rate for a number of rounds, over some network. Some nodes send their weights with a one-rounds latency, for the entire execution. Outputs the accuracies and returns them. Params: train_loader (array): the list of all tr...
import numpy as np import torch import sys sys.path.append('..') from utils import model_init, optimizer_init, client_update, diffuse_params, average_models, evaluate, create_mixing_matrix def run_latency(train_loader, test_loader, comm_matrix, num_rounds, epochs, num_clients, latency_nodes, net='net', optimize...
82
163
545
40
41
giordano-lucas/DeAI
simulator/simulator-topologies-fault-tolerance/latency/latency.py
Python
run_latency
run_latency
7
54
7
8
94f3527afd812c533538612b54a77c8e38393cb4
bigcode/the-stack
train
8b67fe58f83fd68070976067
train
function
def run_latency_per_round_changing_topo(train_loader, test_loader, num_rounds, epochs, num_clients, latency_nodes, latency_rounds, net='net', optimizer='sgd', lr=0.1): """ Runs a decentralized optimization algorithm for the given learning rate for a number of rounds, over some network. Some nodes se...
def run_latency_per_round_changing_topo(train_loader, test_loader, num_rounds, epochs, num_clients, latency_nodes, latency_rounds, net='net', optimizer='sgd', lr=0.1):
""" Runs a decentralized optimization algorithm for the given learning rate for a number of rounds, over some network. Some nodes send their weights with a one-rounds latency, only during specific rounds. Outputs the accuracies and returns them. Params: train_loader (array): the list of all...
_rounds + 1): diffuse_params(client_models, comm_matrix) diffuse_params_latency(old_client_models, comm_matrix, np.setdiff1d(np.array(range(num_clients)), latency_nodes)) print("round {}, delay recovery".format(r)) else: diffuse_params(client_models, comm_matrix) ...
210
210
701
47
162
giordano-lucas/DeAI
simulator/simulator-topologies-fault-tolerance/latency/latency.py
Python
run_latency_per_round_changing_topo
run_latency_per_round_changing_topo
171
232
171
172
5f7fbaca536b82de74d78b40d589833e49d7028c
bigcode/the-stack
train
90ca8bc4304f9903a9765a7c
train
function
def nodes_latency(num_nodes, num_delay): """ Chooses a number of nodes among the set of clients. The chosen ones now have latency, i.e. their weights are transmitted with some delay. Params: num_nodes (int): the number of clients num_delay (int): the number of latency nodes to choose Returns: ...
def nodes_latency(num_nodes, num_delay):
""" Chooses a number of nodes among the set of clients. The chosen ones now have latency, i.e. their weights are transmitted with some delay. Params: num_nodes (int): the number of clients num_delay (int): the number of latency nodes to choose Returns: lat_nodes (array): the list of latenc...
_dict( { key: torch.stack( [weights[j]*client_state_dicts[j][key] for j in working_neigh], dim=0, ).sum(0) / weights.sum() for key in keys } ) def nodes_latency(num_nodes, num_delay):
64
64
147
9
55
giordano-lucas/DeAI
simulator/simulator-topologies-fault-tolerance/latency/latency.py
Python
nodes_latency
nodes_latency
261
280
261
261
5cebbeae3704fe02ca4a645c0fc1531909d9f673
bigcode/the-stack
train
c0429a4b88e905bd55782790
train
function
def diffuse_params_latency(client_models, communication_matrix, latency_nodes): """ Diffuses the client models to their neighbours except if the node has latency. Such a node doesn't diffuse its weights now. Params: client_models (array): the list of all the client neural networks commu...
def diffuse_params_latency(client_models, communication_matrix, latency_nodes):
""" Diffuses the client models to their neighbours except if the node has latency. Such a node doesn't diffuse its weights now. Params: client_models (array): the list of all the client neural networks communication_matrix (numpy.array): the weighted matrix defining the links between cl...
print('average train loss %0.3g | test loss %0.3g | test acc: %0.3f' % (loss / num_clients, test_loss, acc)) accs.append(acc) return global_model, client_models, accs def diffuse_params_latency(client_models, communication_matrix, latency_nodes):
70
70
234
13
56
giordano-lucas/DeAI
simulator/simulator-topologies-fault-tolerance/latency/latency.py
Python
diffuse_params_latency
diffuse_params_latency
234
259
234
234
db8ff5ea9b32e99b650cbec0808067fb91d769a2
bigcode/the-stack
train
6b72a25145ec502b6d7d66c4
train
class
class GLibScheduler(object): """ Used for stting up deferred jobs. """ def schedule_at(self, delay, callback, *args): """ Schedule a function at a given delay. """ GLib.timeout_add_seconds(delay, callback, *args)
class GLibScheduler(object):
""" Used for stting up deferred jobs. """ def schedule_at(self, delay, callback, *args): """ Schedule a function at a given delay. """ GLib.timeout_add_seconds(delay, callback, *args)
init("Partner") def show_notification(self, message, timeout=10): """ Show notification. """ from gi.repository.Notify import Notification n = Notification.new(message, None, None) n.set_timeout(timeout * 1000) n.show() class GLibScheduler(object...
64
64
58
6
58
aragaer/partner
partner/__init__.py
Python
GLibScheduler
GLibScheduler
58
67
58
58
9e41dfada7591d17bc0dcc81b3b7cd2b0af3fc3f
bigcode/the-stack
train
5341bc7c9728dcddb161c9fd
train
class
class PartnerService(object): """ Main service for the class. """ schedule = {'Ping': 300} def __init__(self, notifier=None, scheduler=None, schedule=None): if notifier is None: notifier = NotifyNotifier() self.notifier = notifier if scheduler is None: ...
class PartnerService(object):
""" Main service for the class. """ schedule = {'Ping': 300} def __init__(self, notifier=None, scheduler=None, schedule=None): if notifier is None: notifier = NotifyNotifier() self.notifier = notifier if scheduler is None: scheduler = GLibSchedul...
#!/usr/bin/env python # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 from gi.repository import GLib class PartnerService(object):
37
64
177
5
31
aragaer/partner
partner/__init__.py
Python
PartnerService
PartnerService
7
35
7
7
82486560fdd013473ac62e6e22a8f01f105c99d5
bigcode/the-stack
train
711e832de67a74dd7045b223
train
class
class NotifyNotifier(object): """ Uses gi.repository to show notifications. """ def __init__(self): from gi.repository.Notify import init init("Partner") def show_notification(self, message, timeout=10): """ Show notification. """ from gi.rep...
class NotifyNotifier(object):
""" Uses gi.repository to show notifications. """ def __init__(self): from gi.repository.Notify import init init("Partner") def show_notification(self, message, timeout=10): """ Show notification. """ from gi.repository.Notify import Notifica...
ifier.show_notification("Hello") def show_notification(self, message): """ Say something to the lone developer. """ self.notifier.show_notification(message) if message in self.schedule: self.scheduler.schedule_at(self.schedule[message], ...
64
64
90
5
59
aragaer/partner
partner/__init__.py
Python
NotifyNotifier
NotifyNotifier
38
55
38
38
d15d20e16230b86e70aabd4a4db5b4dc28b3aaef
bigcode/the-stack
train
6dc13ceb01dd4674badd0fb0
train
class
class SignMongoDB(object): def __init__(self, username: str): self.client = MongoClient("mongodb://localhost:27017/") database = self.client["signweb"] self.collection = database["users"] self.username = username if not self.collection.find_one({"username": username}): ...
class SignMongoDB(object):
def __init__(self, username: str): self.client = MongoClient("mongodb://localhost:27017/") database = self.client["signweb"] self.collection = database["users"] self.username = username if not self.collection.find_one({"username": username}): self.collection.inser...
from pymongo import MongoClient class SignMongoDB(object):
13
142
474
6
6
silentonz725/chaoxing_auto_sign
api/db_handler.py
Python
SignMongoDB
SignMongoDB
4
50
4
5
34b1fcb7afb9d807f5c0a9792ea8bf544ee34de1
bigcode/the-stack
train
c57eb158b0bca5e6411f2622
train
function
def check_nbextension(files, user=False, prefix=None, nbextensions_dir=None): """Check whether nbextension files have been installed Returns True if all files are found, False if any are missing. Parameters ---------- files : list(paths) a list of relative paths within nbextensions. ...
def check_nbextension(files, user=False, prefix=None, nbextensions_dir=None):
"""Check whether nbextension files have been installed Returns True if all files are found, False if any are missing. Parameters ---------- files : list(paths) a list of relative paths within nbextensions. user : bool [default: False] Whether to check the user's .ipython/n...
= pjoin(prefix, 'share', 'jupyter', 'nbextensions') elif nbextensions_dir: nbext = nbextensions_dir else: nbext = pjoin(SYSTEM_JUPYTER_PATH[0], 'nbextensions') return nbext def check_nbextension(files, user=False, prefix=None, nbextensions_dir=None):
75
75
251
17
57
wangyum/anaconda
pkgs/notebook-4.1.0-py27_1/lib/python2.7/site-packages/notebook/nbextensions.py
Python
check_nbextension
check_nbextension
79
107
79
79
3e69b301018143937eec574654a8ed37a6d727c5
bigcode/the-stack
train
ab0b7e622a3fc4a45755513e
train
function
def _should_copy(src, dest, verbose=1): """should a file be copied?""" if not os.path.exists(dest): return True if os.stat(src).st_mtime - os.stat(dest).st_mtime > 1e-6: # we add a fudge factor to work around a bug in python 2.x # that was fixed in python 3.x: http://bugs.python.org/...
def _should_copy(src, dest, verbose=1):
"""should a file be copied?""" if not os.path.exists(dest): return True if os.stat(src).st_mtime - os.stat(dest).st_mtime > 1e-6: # we add a fudge factor to work around a bug in python 2.x # that was fixed in python 3.x: http://bugs.python.org/issue12904 if verbose >= 2: ...
utils.path import ensure_dir_exists from ipython_genutils.py3compat import string_types, cast_unicode_py2 from ipython_genutils.tempdir import TemporaryDirectory from ._version import __version__ class ArgumentConflict(ValueError): pass def _should_copy(src, dest, verbose=1):
64
64
142
12
51
wangyum/anaconda
pkgs/notebook-4.1.0-py27_1/lib/python2.7/site-packages/notebook/nbextensions.py
Python
_should_copy
_should_copy
33
45
33
33
2b1fa091ecc26726e5053c268f72f14c39899a41
bigcode/the-stack
train
3e9f55cb55698f235d5f1966
train
class
class NBExtensionApp(JupyterApp): name = "jupyter nbextension" version = __version__ description = "Work with Jupyter notebook extensions" subcommands = dict( install=(InstallNBExtensionApp, """Install notebook extensions""" ), enable=(EnableNBExtensionApp, "Enable a...
class NBExtensionApp(JupyterApp):
name = "jupyter nbextension" version = __version__ description = "Work with Jupyter notebook extensions" subcommands = dict( install=(InstallNBExtensionApp, """Install notebook extensions""" ), enable=(EnableNBExtensionApp, "Enable a notebook extension"), dis...
}}) def start(self): if not self.extra_args: sys.exit('No extensions specified') elif len(self.extra_args) > 1: sys.exit('Please specify one extension at a time') self.disable_nbextension(self.extra_args[0]) class NBExtensionApp(JupyterApp):
64
64
168
8
56
wangyum/anaconda
pkgs/notebook-4.1.0-py27_1/lib/python2.7/site-packages/notebook/nbextensions.py
Python
NBExtensionApp
NBExtensionApp
391
410
391
391
8f8883daf20e25045cb5ce5b5a7c71510f549842
bigcode/the-stack
train