code stringlengths 281 23.7M |
|---|
.django_db
def test_sort_order_values(client, create_idv_test_data):
_test_post(client, {'award_id': 1, 'order': 'desc'}, (None, None, 1, False, False, False, 5, 4, 3))
_test_post(client, {'award_id': 1, 'order': 'asc'}, (None, None, 1, False, False, False, 3, 4, 5))
_test_post(client, {'award_id': 1, 'orde... |
def _discover_coreutils_tests() -> List[Tuple[(pathlib.Path, str)]]:
with pathlib.Path('tests/coreutils/functions.txt').open('r', encoding='utf-8') as f:
funcs_contents = f.readlines()
files = []
for line in funcs_contents:
f = line.split()
path = pathlib.Path(f'tests/coreutils/binar... |
class MinerPayment(BaseModel):
block_number: int
transaction_hash: str
transaction_index: int
miner_address: str
coinbase_transfer: int
base_fee_per_gas: int
gas_price: int
gas_price_with_coinbase_transfer: int
gas_used: int
transaction_to_address: Optional[str]
transaction_f... |
class Uploadr():
token = None
perms = ''
TOKEN_FILE = os.path.join(IMAGE_DIR, '.flickrToken')
def __init__(self):
self.token = self.getCachedToken()
def signCall(self, data):
keys = data.keys()
keys.sort()
foo = ''
for a in keys:
foo += (a + data[a... |
class OptionSeriesPictorialSonificationDefaultspeechoptionsMappingRate(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class OptionPlotoptionsColumnSonificationTracksMappingFrequency(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class OptionPlotoptionsScatter3dPointEvents(Options):
def click(self):
return self._config_get(None)
def click(self, value: Any):
self._config(value, js_type=False)
def drag(self):
return self._config_get(None)
def drag(self, value: Any):
self._config(value, js_type=False... |
class serienRecTimerListScreen(serienRecBaseScreen, Screen, HelpableScreen):
def __init__(self, session):
serienRecBaseScreen.__init__(self, session)
Screen.__init__(self, session)
HelpableScreen.__init__(self)
self.skin = None
self.session = session
self.picload = eP... |
class PRNG():
def __init__(self, seed):
self.sha = sha256(seed)
self.pool = bytearray()
def get_bytes(self, n):
while (len(self.pool) < n):
self.pool.extend(self.sha)
self.sha = sha256(self.sha)
(result, self.pool) = (self.pool[:n], self.pool[n:])
... |
def bad_words_handler(bot, message):
if config.bad_words_toggle:
try:
if re.findall(config.regex_filter['bad_words'], msg_type(message)):
bot.reply_to(message, ' Watch your tongue...')
return bad_words_handler
except Exception as e:
pass |
class TestColumnVectorizer():
def models(self, Article):
pass
def Article(self, Base):
class Article(Base):
__tablename__ = 'textitem'
id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
name = sa.Column(HSTORE)
search_vector = sa.Colu... |
def extract_index_mapping_and_settings(client, index_pattern):
results = {}
logger = logging.getLogger(__name__)
response = client.indices.get(index=index_pattern, params={'expand_wildcards': 'all'})
for (index, details) in response.items():
(valid, reason) = is_valid(index, index_pattern)
... |
class OptionPlotoptionsCylinderSonificationDefaultinstrumentoptionsMappingTremoloSpeed(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(sel... |
def compute_interpolation_error(baseMesh, nref, space, degree):
mh = MeshHierarchy(baseMesh, nref)
dim = mh[0].geometric_dimension()
error = np.zeros(((nref + 1), 2))
for (i, mesh) in enumerate(mh):
if (dim == 2):
(x, y) = SpatialCoordinate(mesh)
elif (dim == 3):
... |
class LDAPGroups():
def group_names(username):
ldap_client = LDAP(app.config['LDAP_URL'], app.config['LDAP_SEARCH_STRING'])
groups = []
for group in ldap_client.get_user_groups(username):
group = group.decode('utf-8')
attrs = dict([tuple(x.split('=')) for x in group.s... |
class RuntimeImages(Schemaspace):
RUNTIME_IMAGES_SCHEMASPACE_ID = '119c9740-d73f-48c6-a97a-599d3acaf41d'
RUNTIMES_IMAGES_SCHEMASPACE_NAME = 'runtime-images'
RUNTIMES_IMAGES_SCHEMASPACE_DISPLAY_NAME = 'Runtime Images'
def __init__(self, *args, **kwargs):
super().__init__(schemaspace_id=RuntimeIma... |
def test_to_tjp_attribute_is_working_properly_for_multiple_work_hour_ranges():
wh = WorkingHours()
wh['mon'] = [[570, 720], [780, 1110]]
wh['tue'] = [[570, 720], [780, 1110]]
wh['wed'] = [[570, 720], [780, 1110]]
wh['thu'] = [[570, 720], [780, 1110]]
wh['fri'] = [[570, 720], [780, 1110]]
wh[... |
class XSensListener(object):
def listen(self, host='localhost', port=9763, timeout=2):
import struct
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(timeout)
s.bind((host, port))
while True:
data = s.recv(2048)
p... |
def collect(filter_fun):
if sys.path[0].endswith('/benchmarks'):
path = sys.path.pop(0)
correct = path.rsplit('/', 1)[0]
sys.path.insert(0, correct)
common_prefix = 'benchmark_'
result = []
for name in ('hub_timers', 'spawn'):
mod = importlib.import_module(('benchmarks.' ... |
class controller_status_prop(loxi.OFObject):
subtypes = {}
def __init__(self, type=None):
if (type != None):
self.type = type
else:
self.type = 0
return
def pack(self):
packed = []
packed.append(struct.pack('!H', self.type))
packed.appe... |
class Processor(Iface, TProcessor):
_onewayMethods = ('reinitialize', 'shutdown')
def __init__(self, handler, loop=None):
TProcessor.__init__(self)
self._handler = handler
self._loop = (loop or asyncio.get_event_loop())
self._processMap = {}
self._processMap['getName'] = ... |
class OptionColoraxisDataclasses(Options):
def color(self):
return self._config_get(None)
def color(self, text: str):
self._config(text, js_type=False)
def from_(self):
return self._config_get(None)
_.setter
def from_(self, num: float):
self._config(num, js_type=False... |
class PluginInterface_SmartFetch(object):
name = 'SmartWebRequest'
serialize = False
def __init__(self, settings=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = (settings if settings else {})
self.log = logging.getLogger(('Main.%s' % self.name))
self... |
def extractWinterleaftranslationWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Rebirth Merchant', 'Rebirth Merchant: Wonderful Space Hunting for Military', 'trans... |
('evennia.utils.gametime.gametime', new=Mock(return_value=.46))
class TestCustomGameTime(BaseEvenniaTest):
def tearDown(self):
if hasattr(self, 'timescript'):
self.timescript.stop()
def test_time_to_tuple(self):
self.assertEqual(custom_gametime.time_to_tuple(10000, 34, 2, 4, 6, 1), (... |
(SAAS_CONNECTOR_FROM_TEMPLATE, dependencies=[Security(verify_oauth_client, scopes=[SAAS_CONNECTION_INSTANTIATE])], response_model=SaasConnectionTemplateResponse)
def instantiate_connection_from_template(saas_connector_type: str, template_values: SaasConnectionTemplateValues, db: Session=Depends(deps.get_db)) -> SaasCon... |
class DefRefNode(nodes.Element):
def __init__(self, kind, source_doc, text):
(text, target) = parse_target_from_text(text)
super().__init__(ref_kind=kind, ref_source_doc=source_doc, ref_text=text, ref_target=id_from_text(target))
def astext(self):
return self['ref_text'] |
class NetworkManager():
interfaces_file_name = '/etc/network/interfaces'
resolvconf_file_name = '/etc/resolv.conf'
dhcpcd_file_name = '/etc/dhcpcd.conf'
def __init__(self):
self.wpaconfig = ''
self.WifiSSID = ''
self.WifiKey = ''
self.WifiSSID2 = ''
self.WifiKey2 ... |
class CustomCrypto(Crypto[EntityClass]):
def generate_private_key(cls) -> EntityClass:
pass
def load_private_key_from_path(cls, file_name: str, password: Optional[str]=None) -> Any:
pass
def public_key(self) -> str:
pass
def address(self) -> str:
pass
def private_key(... |
class OptionSeriesSunburstStatesSelect(Options):
def animation(self) -> 'OptionSeriesSunburstStatesSelectAnimation':
return self._config_sub_data('animation', OptionSeriesSunburstStatesSelectAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
se... |
def test_user_enters_variables_and_iqr_imputation_on_left_tail(df_na):
imputer = EndTailImputer(imputation_method='iqr', tail='left', fold=1.5, variables=['Age', 'Marks'])
imputer.fit(df_na)
assert (imputer.imputer_dict_['Age'] == (- 6.5))
assert (np.round(imputer.imputer_dict_['Marks'], 3) == np.round(... |
def get_QRuuid(self):
url = ('%s/jslogin' % config.BASE_URL)
params = {'appid': 'wx782c26e4c19acffb', 'fun': 'new', 'redirect_uri': ' 'lang': 'zh_CN'}
headers = {'User-Agent': self.user_agent}
r = self.s.get(url, params=params, headers=headers)
regx = 'window.QRLogin.code = (\\d+); window.QRLogin.uu... |
class TestSecureDescriptor(Descriptor):
TEST_DESC_UUID = '-1234-5678-1234-56789abcdef6'
def __init__(self, bus, index, characteristic):
Descriptor.__init__(self, bus, index, self.TEST_DESC_UUID, ['secure-read', 'secure-write'], characteristic)
def ReadValue(self, options):
return [dbus.Byte(... |
def test_w3_ens_setter_sets_w3_object_reference_on_ens(w3):
ns = ENS.from_web3(w3)
w3.ens = ns
assert (ns == w3.ens)
assert (w3 == w3.ens.w3)
assert w3.strict_bytes_type_checking
assert w3.ens.strict_bytes_type_checking
assert w3.ens.w3.strict_bytes_type_checking
w3.strict_bytes_type_che... |
class Wrapper(ecmwfapi.ECMWFDataServer):
def __init__(self, dataset):
super().__init__()
self.dataset = dataset
def execute(self, request, target):
request = dict(**request)
request['dataset'] = self.dataset
request['target'] = target
print(request)
return... |
def keypaths(d, separator='.', indexes=False):
separator = (separator or '.')
if (not type_util.is_string(separator)):
raise ValueError('separator argument must be a (non-empty) string.')
kls = keylists(d, indexes=indexes)
kps = [separator.join([f'{key}' for key in kl]) for kl in kls]
kps.so... |
def test_num_mediums():
structures = []
grid_spec = td.GridSpec.auto(wavelength=1.0)
for i in range(MAX_NUM_MEDIUMS):
structures.append(td.Structure(geometry=td.Box(size=(1, 1, 1)), medium=td.Medium(permittivity=(i + 1))))
_ = td.Simulation(size=(5, 5, 5), grid_spec=grid_spec, structures=structu... |
def jumpi(computation: ComputationAPI) -> None:
(jump_dest, check_value) = computation.stack_pop_ints(2)
if check_value:
computation.code.program_counter = jump_dest
next_opcode = computation.code.peek()
if (next_opcode != JUMPDEST):
raise InvalidJumpDestination('Invalid Jump... |
class RegionRendererTest(TestCase):
def prepare(self):
p = Page.objects.create(page_type='standard')
RichText.objects.create(parent=p, region='main', ordering=10, text='<p>Hello</p>')
HTML.objects.create(parent=p, region='main', ordering=20, html='<br>')
HTML.objects.create(parent=p,... |
.flaky(reruns=MAX_FLAKY_RERUNS)
def test_run_with_install_deps():
runner = CliRunner()
agent_name = 'myagent'
cwd = os.getcwd()
t = tempfile.mkdtemp()
packages_src = os.path.join(ROOT_DIR, 'packages')
packages_dst = os.path.join(t, 'packages')
shutil.copytree(packages_src, packages_dst)
... |
def test_conversion_of_ai_standard_to_red_shift_material_refraction_properties(create_pymel, setup_scene):
pm = create_pymel
(ai_standard, ai_standard_sg) = pm.createSurfaceShader('aiStandard')
refraction_color = (1, 0.5, 0)
refraction_weight = 0.532
refraction_ior = 1.434
refraction_abbe = 29.9... |
class Arguments(argparse.ArgumentParser):
def __init__(self):
argparse.ArgumentParser.__init__(self, description=('Gnofract 4D %s' % VERSION), epilog='To generate an image non-interactively, use:\n gnofract4d -s myimage.png -q myfractal.fct', formatter_class=argparse.RawDescriptionHelpFormatter)
se... |
def test_not_devcontainer(cookies, tmp_path):
with run_within_dir(tmp_path):
result = cookies.bake(extra_context={'devcontainer': 'n'})
assert (result.exit_code == 0)
assert (not os.path.isfile(f'{result.project_path}/.devcontainer/devcontainer.json'))
assert (not os.path.isfile(f'{r... |
.router
.asyncio
class TestForgotPassword():
async def test_empty_body(self, test_app_client: user_manager: UserManagerMock):
response = (await test_app_client.post('/forgot-password', json={}))
assert (response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY)
assert (user_manager.forgo... |
def test_error_handler(flask_apm_client):
client = flask_apm_client.app.test_client()
response = client.get('/an-error/')
assert (response.status_code == 500)
assert (len(flask_apm_client.client.events[ERROR]) == 1)
event = flask_apm_client.client.events[ERROR][0]
assert ('exception' in event)
... |
def prepare_irfft_output(arr):
res = Type(dtypes.real_for(arr.dtype), (arr.shape[:(- 1)] + ((arr.shape[(- 1)] * 2),)))
return Transformation([Parameter('output', Annotation(res, 'o')), Parameter('input', Annotation(arr, 'i'))], '\n <%\n batch_idxs = " ".join((idx + ", ") for idx in idxs[:-1])\... |
def test_communication():
with LocalNode() as node:
multiplexer1 = Multiplexer([_make_local_connection('multiplexer1', 'multiplexer1_public_key', node)])
multiplexer2 = Multiplexer([_make_local_connection('multiplexer2', 'multiplexer1_public_key', node)])
multiplexer1.connect()
multi... |
def common_gen_profiler(func_attrs, workdir, profiler_filename, dim_info_dict, src_template, problem_args_template, problem_args_template_cutlass_3x=None, bias_ptr_arg=None, extra_code=''):
output_addr_calculator = common.DEFAULT_OUTPUT_ADDR_CALCULATOR.render(stride_dim='*b_dim0')
return common.gen_profiler(fun... |
def cbFun(errorIndication, errorStatus, errorIndex, varBindTable, **context):
if errorIndication:
print(errorIndication)
elif errorStatus:
print(('%s at %s' % (errorStatus.prettyPrint(), ((errorIndex and varBinds[(int(errorIndex) - 1)][0]) or '?'))))
else:
for varBindRow in varBindTa... |
def vocoder(model, mel):
if use_cuda:
model = model.cuda()
model.eval()
sequence = np.array(mel)
sequence = Variable(torch.from_numpy(sequence)).unsqueeze(0)
if use_cuda:
sequence = sequence.cuda()
waveform = model.forward_eval_sampling1(sequence)
return waveform |
def test_basics():
def t1(a: int) -> typing.NamedTuple('OutputsBC', t1_int_output=int, c=str):
return ((a + 2), 'world')
def t2(a: str, b: str) -> str:
return (b + a)
def my_wf(a: int, b: str) -> (int, str):
(x, y) = t1(a=a)
d = t2(a=y, b=b)
return (x, d)
wf_spec ... |
('model')
def check_out_of_space_uvs(progress_controller=None):
if (progress_controller is None):
progress_controller = ProgressControllerBase()
v = staging.get('version')
if (v and (Representation.repr_separator in v.take_name)):
progress_controller.complete()
return
all_meshes ... |
def submit_distances(argv, tdb, distances):
system = argv.origin
cmdr = argv.cmdr
mode = ('TEST' if argv.test else 'Live')
print()
print('System:', system)
print('Database:', mode)
print('Distances:')
for ref in distances:
print(' {}: {:.02f} ly'.format(ref['name'], ref['dist'])... |
class Strategy(GenericStrategy):
def __init__(self, **kwargs) -> None:
self._db_engine = db.create_engine('sqlite:///genericdb.db')
self._tbl = self.create_database_and_table()
self.insert_data()
super().__init__(**kwargs)
def collect_from_data_source(self) -> Dict[(str, str)]:
... |
('/', methods=['POST', 'GET'])
def infer_route():
global reqs, reload_lock, prj, classes, num_outputs
try:
xin = get_input(request)
if (xin is None):
return ("missing 'x' parameter", 400)
with reload_lock:
x = prj.logic.prepare_input(xin)
y = prj.model... |
def main():
descr = 'A script which processes Ragout\'s debug output and draws some fancy breakpoint graph pictures. It requires a contigs alignment on "true" reference in nucmer coords format. Also, Ragout should be run with --debug key to provide necessary output. Please note, that one should point to debug dir w... |
class PollForDecisionTaskResponse():
task_token: bytes = None
workflow_execution: WorkflowExecution = None
workflow_type: WorkflowType = None
previous_started_event_id: int = None
started_event_id: int = None
attempt: int = None
backlog_count_hint: int = None
history: History = None
... |
def as_numpy_func(ds, options=None):
if ((ds is None) or callable(ds)):
return ds
def _options(new):
o = {k: v for (k, v) in ds.get_options().items()}
if new:
o.update(new)
return o
options = _options(options)
to_numpy_kwargs = options.get('to_numpy_kwargs', {... |
class OptionSeriesSolidgaugeOnpointConnectoroptions(Options):
def dashstyle(self):
return self._config_get(None)
def dashstyle(self, text: str):
self._config(text, js_type=False)
def stroke(self):
return self._config_get(None)
def stroke(self, text: str):
self._config(tex... |
class RequirementType(Enum):
master_requirement = 1
initial_requirement = 2
design_decision = 3
requirement = 4
def as_string(self):
if (self.value == 1):
return 'requirement'
if (self.value == 2):
return 'requirement'
if (self.value == 3):
... |
class OptionSeriesColumnpyramidSonificationDefaultspeechoptionsMappingRate(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str... |
def set_subject_field(doc):
from frappe.utils.formatters import format_value
meta = frappe.get_meta(doc.doctype)
subject = ''
patient_history_fields = get_patient_history_fields(doc)
for entry in patient_history_fields:
fieldname = entry.get('fieldname')
if ((entry.get('fieldtype') =... |
class OptionPlotoptionsSankeySonificationTracksMappingTremoloDepth(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class OptionSeriesSunburstSonificationDefaultinstrumentoptionsMappingTime(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str)... |
class TracingOptions(ctypes.Union):
_anonymous_ = ('bit',)
_fields_ = [('bit', TracingOptions_bits), ('asByte', ctypes.c_uint8)]
def __init__(self, **kwargs) -> None:
super(TracingOptions, self).__init__()
for (k, v) in kwargs.items():
setattr(self, k, v)
def __eq__(self, oth... |
def add_eggs_on_path(working_set, path, on_error=None):
environment = pkg_resources.Environment(path)
(distributions, errors) = working_set.find_plugins(environment)
if (len(errors) > 0):
if on_error:
on_error(errors)
else:
raise RuntimeError(('Cannot find eggs %s' % ... |
class _RegexMatcher(_Matcher):
def __init__(self, tag, content, lower):
_Matcher.__init__(self, tag, content, lower)
self._re = re.compile(content)
def _matches(self, value):
if (not value):
return False
try:
return (self._re.search(value) is not None)
... |
def push_to_hub(self, *, repo_path_or_name: Optional[str]=None, repo_url: Optional[str]=None, commit_message: Optional[str]='Add model', organization: Optional[str]=None, private: bool=False, api_endpoint: Optional[str]=None, use_auth_token: Optional[Union[(bool, str)]]=None, git_user: Optional[str]=None, git_email: Op... |
def get_pdf_notes_ordered_by_size(order: str) -> List[SiacNote]:
conn = _get_connection()
res = conn.execute(f"select notes.* from notes join read on notes.id == read.nid where lower(notes.source) like '%.pdf' group by notes.id order by max(read.pagestotal) {order}").fetchall()
conn.close()
return _to_n... |
def _hashimoto(header_hash: bytes, nonce: bytes, dataset_size: int, fetch_dataset_item: Callable[([int], Tuple[(int, ...)])]) -> Dict[(str, bytes)]:
mix_hashes = (MIX_BYTES // HASH_BYTES)
nonce_le = bytes(reversed(nonce))
seed_hash = keccak_512((header_hash + nonce_le))
seed_head = from_le_bytes(seed_ha... |
def extractTongtongdaydreamsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, ... |
def test_load_images():
cfg = get_config_file(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'configs/images.config'))
imgs = Images.get_specified_images(cfg)
assert (imgs == {'abc': 'docker.io/abc', 'xyz': 'docker.io/xyz:latest'})
cfg = get_config_file(os.path.join(os.path.dirname(os.path.re... |
def test_celery_config_override() -> None:
config = get_config()
config.celery['event_queue_prefix'] = 'overridden_fides_worker'
config.celery['task_default_queue'] = 'overridden_fides'
celery_app = _create_celery(config=config)
assert (celery_app.conf['event_queue_prefix'] == 'overridden_fides_work... |
.skipif((MID_MEMORY > memory), reason='Travis has too less memory to run it.')
.parametrize('matrix', [matrix])
.parametrize('outFileName', [outfile_aggregate_plots])
.parametrize('BED', [BED])
.parametrize('mode', ['intra-chr'])
.parametrize('ran', ['50000:900000'])
.parametrize('BED2', [BED2])
.parametrize('numberOfB... |
class HistoryEvent(betterproto.Message):
event_id: int = betterproto.int64_field(1)
event_time: datetime = betterproto.message_field(2)
event_type: v1enums.EventType = betterproto.enum_field(3)
version: int = betterproto.int64_field(4)
task_id: int = betterproto.int64_field(5)
workflow_execution... |
def load_nifti(filename):
logger = logging.getLogger(__name__)
try:
nifti = nib.load(filename)
except:
logger.error('Cannot read {}'.format(filename))
sys.exit(1)
affine = nifti.get_affine()
header = nifti.get_header()
dims = list(nifti.shape)
if (len(dims) < 3):
... |
class ControlBox(Gtk.Box, providers.ProviderHandler):
__gsignals__ = {'show': 'override'}
def __init__(self):
Gtk.Box.__init__(self)
providers.ProviderHandler.__init__(self, 'minimode-controls')
self.__dirty = True
self.__controls = {}
event.add_ui_callback(self.on_option... |
class DefaultDataGenerator(DataGenerator):
def __init__(self, cache: bool=False):
super(DefaultDataGenerator, self).__init__()
self.cache = cache
self.prev_config = None
self.op_args = []
self.op_kwargs = {}
def _find_updates(self, config: Dict[(str, Any)]):
if (n... |
('cuda.gemm_rrr_bias.gen_function')
def gen_function(func_attrs, exec_cond_template, dim_info_dict):
input_addr_calculator = gemm_rrr.get_input_addr_calculator(func_attrs)
input_ndims = len(func_attrs['input_accessors'][0].original_shapes)
weight_ndims = len(func_attrs['input_accessors'][1].original_shapes)... |
class TestValidationErrorCode():
.parametrize('use_list', (False, True))
def test_validationerror_code_with_msg(self, use_list):
class ExampleSerializer(serializers.Serializer):
password = serializers.CharField()
def validate_password(self, obj):
err = DjangoValid... |
def generic_activation_jit(op_name: Optional[str]=None) -> Handle:
def _generic_activation_jit(i: Any, outputs: List[Any]) -> Union[(typing.Counter[str], Number)]:
out_shape = get_shape(outputs[0])
ac_count = prod(out_shape)
if (op_name is None):
return ac_count
else:
... |
class TestJSONBoundField():
def test_as_form_fields(self):
class TestSerializer(serializers.Serializer):
json_field = serializers.JSONField()
data = QueryDict(mutable=True)
data.update({'json_field': '{"some": ["json"}'})
serializer = TestSerializer(data=data)
ass... |
def gen_function_call(func_attrs, backend_spec, indent=' '):
x = func_attrs['inputs'][0]
rois = func_attrs['inputs'][1]
xshape = x._attrs['shape']
y = func_attrs['outputs'][0]
yshape = y._attrs['shape']
return FUNC_CALL_TEMPLATE.render(func_name=func_attrs['name'], in_ptr=x._attrs['name'], rois... |
class CaseList(QWidget):
def __init__(self, config: ErtConfig, notifier: ErtNotifier, ensemble_size: int):
self.ert_config = config
self.ensemble_size = ensemble_size
self.notifier = notifier
QWidget.__init__(self)
layout = QVBoxLayout()
self._list = QListWidget(self)... |
class OptionPlotoptionsTreegraphOnpointPosition(Options):
def offsetX(self):
return self._config_get(None)
def offsetX(self, num: float):
self._config(num, js_type=False)
def offsetY(self):
return self._config_get(None)
def offsetY(self, num: float):
self._config(num, js_... |
def _make_fpds_transaction(id, award_id, obligation, action_date, recipient_duns, recipient_name, recipient_hash, piid=None):
baker.make('search.TransactionSearch', transaction_id=id, is_fpds=True, award_id=award_id, federal_action_obligation=obligation, generated_pragmatic_obligation=obligation, action_date=action... |
def extract_with_context(lst, pred, before_context, after_context):
rval = []
start = 0
length = 0
while (start < len(lst)):
usedfirst = False
usedlast = False
while (((start + length) < len(lst)) and (length < (before_context + 1)) and (not pred(lst[(start + length)]))):
... |
class TestAggregator():
def test_zero_weights(self) -> None:
model = create_model_with_value(0)
ag = Aggregator(module=model, aggregation_type=AggregationType.AVERAGE)
weight = 1.0
steps = 5
for _ in range(steps):
delta = create_model_with_value(1.0)
a... |
def determine_template(mode: str):
render_mode = mode
try:
from IPython import get_ipython
is_colab = type(get_ipython()).__module__.startswith('google.colab')
except ImportError:
is_colab = False
if (mode == 'auto'):
if is_colab:
render_mode = 'inline'
... |
def import_local_module(project_dir, module_name):
if (not os.path.isdir(project_dir)):
raise FileNotFoundError(('Project dir does not exist: %s' % project_dir))
pathname_dir = os.path.join(project_dir, module_name)
pathname_file = (pathname_dir + '.py')
if os.path.isfile(pathname_file):
... |
class ws_listener(tcp_handler.tcp_handler):
def init_func(self, creator, listen, is_ipv6=False):
if is_ipv6:
fa = socket.AF_INET6
else:
fa = socket.AF_INET
s = socket.socket(fa, socket.SOCK_STREAM)
if is_ipv6:
s.setsockopt(socket.IPPROTO_IPV6, sock... |
def test_key_file_encryption_decryption(fetchai_private_key_file):
fetchai = FetchAICrypto(fetchai_private_key_file)
pk_data = Path(fetchai_private_key_file).read_text()
password = uuid4().hex
encrypted_data = fetchai.encrypt(password)
decrypted_data = fetchai.decrypt(encrypted_data, password)
a... |
class CmdHexdump(Cmd):
keywords = ['hexdump', 'hd']
description = 'Display a hexdump of a specified region in the memory.'
parser = argparse.ArgumentParser(prog=keywords[0], description=description, epilog=('Aliases: ' + ', '.join(keywords)))
parser.add_argument('--length', '-l', type=auto_int, default=... |
class TxBytPerQueue(base_tests.SimpleDataPlane):
def runTest(self):
logging.info('Running TxBytPerQueue test')
of_ports = config['port_map'].keys()
of_ports.sort()
self.assertTrue((len(of_ports) > 1), 'Not enough ports for test')
(queue_stats, p) = get_queuestats(self, ofp.OF... |
def test_gas_price_strategy_eth_gasstation():
gas_price_strategy = 'fast'
excepted_result = 10
callable_ = get_gas_price_strategy(gas_price_strategy, 'api_key')
with patch.object(requests, 'get', return_value=MagicMock(status_code=200, json=MagicMock(return_value={gas_price_strategy: excepted_result})))... |
class OptionPlotoptionsDependencywheelSonificationTracks(Options):
def activeWhen(self) -> 'OptionPlotoptionsDependencywheelSonificationTracksActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsDependencywheelSonificationTracksActivewhen)
def instrument(self):
return self._c... |
def render() -> None:
global TRIM_FRAME_START_SLIDER
global TRIM_FRAME_END_SLIDER
trim_frame_start_slider_args: Dict[(str, Any)] = {'label': wording.get('trim_frame_start_slider_label'), 'step': 1, 'minimum': 0, 'maximum': 100, 'visible': False}
trim_frame_end_slider_args: Dict[(str, Any)] = {'label': w... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('new_version', type=str)
args = parser.parse_args()
version = Version.parse(args.new_version)
assert (not version.dev)
print(f'Bumping to {version}')
if version.beta:
write_version('beta', version)
generate.ma... |
def spinner(text: str, logger: Logger, quiet=False, debug=False):
try:
logger.info(text)
if (not quiet):
print(text, end='... ', flush=True)
(yield)
if (not quiet):
print('Done', flush=True)
except Exception as exception:
exception_traceback = form... |
def generic_create(evm: Evm, endowment: U256, contract_address: Address, memory_start_position: U256, memory_size: U256, init_code_gas: Uint) -> None:
from ...vm.interpreter import MAX_CODE_SIZE, STACK_DEPTH_LIMIT, process_create_message
evm.accessed_addresses.add(contract_address)
create_message_gas = max_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.