code stringlengths 281 23.7M |
|---|
(base=RequestContextTask, bind=True, max_retries=5)
def send_event_invoice(self, event_id: int, send_notification: bool=True, force: bool=False):
this_month = this_month_date()
event_invoice = EventInvoice.query.filter_by(event_id=event_id).filter((EventInvoice.issued_at >= this_month)).first()
if ((not for... |
class Citator():
REFERENCES = {'ETE': u'Huerta-Cepas J, Serra F, Bork P. ETE 3: Reconstruction, analysis and\n visualization of phylogenomic data. Mol Biol Evol (2016) doi:\n 10.1093/molbev/msw046', 'phyml': u'Guindon S, Dufayard JF, Lefort V, Anisimova M, Hordijk W, Gascuel O.\n New algorithms... |
_postgres
def test_gis_select(db):
for model in [Geometry, Geography]:
row = model.new(point=geo.Point(1, 1), line=geo.Line((0, 0), (20, 80), (80, 80)), polygon=geo.Polygon((0, 0), (150, 0), (150, 10), (0, 10), (0, 0)), multipoint=geo.MultiPoint((1, 1), (2, 2)), multiline=geo.MultiLine(((1, 1), (2, 2), (3, ... |
class OptionSeriesSolidgaugeSonificationDefaultinstrumentoptionsMappingLowpassFrequency(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(se... |
def parse_base_args(parser):
parsed_args = parser.parse_args()
from etw import evntrace as et
level = {'critical': et.TRACE_LEVEL_CRITICAL, 'error': et.TRACE_LEVEL_ERROR, 'warning': et.TRACE_LEVEL_WARNING, 'information': et.TRACE_LEVEL_INFORMATION, 'verbose': et.TRACE_LEVEL_VERBOSE, 'reserved6': et.TRACE_LE... |
def extractLazyslothtranslationsWordpressCom(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, na... |
class WindowedKeysView(KeysView):
def __init__(self, mapping: WindowWrapperT, event: Optional[EventT]=None) -> None:
self._mapping = mapping
self.event = event
def __iter__(self) -> Iterator:
wrapper = cast(WindowWrapper, self._mapping)
for (key, _) in wrapper._items(self.event):... |
def test_get_integration_params_channel_logic():
alert = DBT_TEST_ALERT_MOCK
integration = get_slack_integration_mock(slack_token='mock', slack_channel_name='from_conf')
assert (json.dumps(integration._get_integration_params(alert=alert)) == json.dumps({'channel': 'from_conf'}))
alert = DBT_TEST_ALERT_M... |
def retype_message(message):
if (type(message) == Message):
if message.topic.endswith('.copr.build.end'):
return BuildChrootEndedV1(body=message.body)
if message.topic.endswith('.copr.build.start'):
return BuildChrootStartedV1(body=message.body)
if message.topic.endsw... |
def describe_sh_flags(x):
s = ''
for flag in (SH_FLAGS.SHF_WRITE, SH_FLAGS.SHF_ALLOC, SH_FLAGS.SHF_EXECINSTR, SH_FLAGS.SHF_MERGE, SH_FLAGS.SHF_STRINGS, SH_FLAGS.SHF_INFO_LINK, SH_FLAGS.SHF_LINK_ORDER, SH_FLAGS.SHF_OS_NONCONFORMING, SH_FLAGS.SHF_GROUP, SH_FLAGS.SHF_TLS, SH_FLAGS.SHF_EXCLUDE):
s += (_DESC... |
class LicenseBaseInformationError(ErsiliaError):
def __init__(self):
self.message = 'Wrong license'
self.hints = "Listed licenses are: {}. If the model has a license not in this list, please open a PR on the 'license.txt' file in the Ersilia repository".format(', '.join(_read_default_fields('License... |
_exempt
def retrieve_workflow_by_experimentId(request):
if (len(request.body) == 0):
return HttpResponse('Nothing', content_type='application/json')
json_str = json.loads(request.body.decode('utf-8'))
response = experiment_service.get_workflow_by_experimentId(json_str)
return HttpResponse(respon... |
class EVENT_FILTER_EVENT_NAME(ct.Structure):
_fields_ = [('MatchAnyKeyword', ct.c_ulonglong), ('MatchAllKeyword', ct.c_ulonglong), ('Level', wt.CHAR), ('FilterIn', wt.BOOLEAN), ('NameCount', wt.USHORT), ('Names', (wt.CHAR * 0))]
def __init__(self, match_any, match_all, level, filter_in, names):
struct_s... |
class FidesCollectionKey(ConstrainedStr):
def validate(cls, value: str) -> str:
values = value.split('.')
if (len(values) == 2):
FidesKey.validate(values[0])
FidesKey.validate(values[1])
return value
raise ValueError("FidesCollection must be specified in t... |
class OptionSeriesSunburstSonificationContexttracksMappingGapbetweennotes(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 _merge_configs(*configs) -> Dict[(str, Any)]:
config = dict()
for subconfig in configs:
config.update(subconfig)
for section in ('plugins', 'exceptions'):
config[section] = dict()
for subconfig in configs:
config[section].update(subconfig.get(section, {}))
return ... |
class AITSplitter(splitter_base._SplitterBase):
def __init__(self, module: torch.fx.GraphModule, sample_input: Sequence[Any], operator_support: ops.OperatorSupportBase=None, settings: AITSplitterSettings=None):
if (not settings):
settings = AITSplitterSettings()
if (not operator_support)... |
def horizontal_mirror(art: str) -> str:
art_lines = art.split('\n')
ansi_escape_regex = '((\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[-~])'
output = ''
for line in art_lines:
chars_and_escape_codes = re.split(ansi_escape_regex, line)
reversed_string = ''
for code in chars_and_escape_codes[::(... |
class TestsRGBSerialize(util.ColorAssertsPyTest):
COLORS = [('rgb(255 0 0)', {}, 'rgb(255 0 0)'), ('rgb(255 0 0)', {'names': True}, 'red'), ('rgb(255 0 0)', {'hex': True}, '#ff0000'), ('rgb(255 0 0)', {'hex': True, 'compress': True}, '#f00'), ('rgb(255 0 0 / 0.53333)', {'hex': True}, '#ff000088'), ('rgb(255 0 0 / 0... |
def _delete(package_id):
(org, repo, version) = _split_id(package_id)
source_path = _get_data_folder().joinpath(f'packages/{org}/{repo}{version}')
if (not source_path.exists()):
raise FileNotFoundError(f"Package '{_format_pkg(org, repo, version)}' is not installed")
shutil.rmtree(source_path)
... |
_cache(maxsize=1024)
def normalize_int(value: IntConvertible) -> int:
if is_integer(value):
return cast(int, value)
elif is_bytes(value):
return big_endian_to_int(cast(bytes, value))
elif (is_hex(value) and is_0x_prefixed(value)):
value = cast(str, value)
if (len(value) == 2)... |
class TestLanguageAgnosticDocs(BaseTestMarkdownDocs):
DOC_PATH = Path(ROOT_DIR, 'docs', 'language-agnostic-definition.md')
def _proto_snippet_selector(cls, block: Dict) -> bool:
return ((block['type'] == 'block_code') and (block['info'].strip() == 'proto'))
def setup_class(cls):
super().setu... |
class ActionExpectsFieldErrorsDirective(ActionExpectsErrorsDirective):
def name(cls):
return 'expect_error_field'
def get_full_grammar(cls):
return ((((super(ActionExpectsFieldErrorsDirective, cls).get_full_grammar() + ',') + Literal('field')) + '=') + Word((alphanums + '-_.{}[]'))('field_name')... |
def extractWuxiaLovers(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())):
return None
if (item['title'].startswith('CGA Chapter') or item['title'].startswith('CGA: Chapter')):
return buil... |
def transform_name(name, from_char='_', to_char='-'):
name = name.strip()
name = re.sub('{}+'.format(re.escape(from_char)), to_char, name)
name = re.sub('^{c}|{c}$'.format(c=re.escape(to_char)), '', name)
if (not name):
raise ValueError('Invalid name "{}"'.format(name))
return name |
class ScalarField(Field):
def cast(self, value: Any) -> Optional[Any]:
if (not isinstance(value, QueryToken)):
return self.data_type_converter.to_value(value)
return value
def collect_matching(self, func: Callable[([Field], bool)]) -> Dict[(FieldPath, Field)]:
if func(self):
... |
class OptionPlotoptionsDumbbellSonificationDefaultinstrumentoptionsMappingTremoloDepth(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 verify_ping(fledge_url, north_catch_up_time):
get_url = '/fledge/ping'
ping_result = utils.get_request(fledge_url, get_url)
assert ('dataRead' in ping_result)
assert ('dataSent' in ping_result)
assert (0 < ping_result['dataRead']), 'South data NOT seen in ping header'
assert (ping_result['da... |
def health_check(client, **kwargs):
logger = logging.getLogger(__name__)
logger.debug('KWARGS= "%s"', kwargs)
klist = list(kwargs.keys())
if (not klist):
raise MissingArgument('Must provide at least one keyword argument')
hc_data = client.cluster.health()
response = True
for k in kli... |
def _prep_venv(name, venvsdir, on_exists, python, failfast):
venvroot = os.path.abspath(os.path.join(venvsdir, name))
(status, kind) = get_venv_status(rootdir)
if (status != 'missing'):
try:
(op, venvroot) = on_exists(venvroot, status, kind)
except Exception as exc:
o... |
('versions', cls=FandoghCommand)
('-i', '--image', 'image', prompt='Image name', help='The image name', default=(lambda : get_project_config().get('image.name')))
def versions(image):
if (not image):
image = get_project_config().get('image.name')
table = present((lambda : list_versions(image)), renderer... |
.lkc
def test_cves_metadata_fixes(hound, cve):
fixes = hound.get_rule_fixes(cve)
lkc_fixes = hound.get_cve_metadata(cve)['breaks']
if (fixes == 'v2.6.12-rc2'):
fixes = '1da177e4c3f41524e886b7f1b8a0c1fc7321cac2'
assert (fixes == lkc_fixes), '{} vs. {}'.format(fixes[0:12], lkc_fixes[0:12]) |
class Solution():
def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:
grid = {tuple([(x + 1), (y + 1)]) for (x, y) in mines}
dp = [[([0] * 4) for _ in range((N + 2))] for _ in range((N + 2))]
for (dx, dy, dr) in [((- 1), 0, 0), (1, 0, 1), (0, (- 1), 2), (0, 1, 3)]:
... |
class TestMinHashLSH(unittest.TestCase):
def test_init(self):
lsh = MinHashLSH(threshold=0.8)
self.assertTrue(lsh.is_empty())
(b1, r1) = (lsh.b, lsh.r)
lsh = MinHashLSH(threshold=0.8, weights=(0.2, 0.8))
(b2, r2) = (lsh.b, lsh.r)
self.assertTrue((b1 < b2))
sel... |
def load_jupyter_server_extension(nb_server_app):
web_app = nb_server_app.web_app
template_dirs = nb_server_app.config.get('JupyterLabTemplates', {}).get('template_dirs', [])
allowed_extensions = nb_server_app.config.get('JupyterLabTemplates', {}).get('allowed_extensions', ['*.ipynb'])
if nb_server_app.... |
def fortios_firewall_shaper(data, fos, check_mode):
fos.do_member_operation('firewall.shaper', 'per-ip-shaper')
if data['firewall_shaper_per_ip_shaper']:
resp = firewall_shaper_per_ip_shaper(data, fos, check_mode)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'firewall_shaper_pe... |
class MultiDictionary():
_d: Dict[(Any, Set[Any])]
def __init__(self) -> None:
self._d = {}
def add(self, key: Any, value: Any) -> None:
if (key not in self._d):
self._d[key] = {value}
else:
self._d[key].add(value)
def __getitem__(self, key: Any) -> Set[An... |
def addTextBox(fid, value, maxlength):
global TXBuffer
TXBuffer += "<input class='wide' type='text' name='"
TXBuffer += str(fid)
TXBuffer += "' id='"
TXBuffer += str(fid)
TXBuffer += "' maxlength="
TXBuffer += str(maxlength)
TXBuffer += " value='"
TXBuffer += str(value)
TXBuffer ... |
.integrationtest
def test_pipeline(instrument, elasticapm_client, redis_conn):
elasticapm_client.begin_transaction('transaction.test')
with capture_span('test_pipeline', 'test'):
pipeline = redis_conn.pipeline()
pipeline.rpush('mykey', 'a', 'b')
pipeline.expire('mykey', 1000)
pip... |
class TestPluginFileNameResolver():
def setup_class(cls):
cls.resolver = supplier.PluginFileNameResolver('test-plugin')
def test_resolve(self):
self.resolver.revision = 'abc123'
assert (self.resolver.file_name == 'test-plugin-abc123.zip')
def test_artifact_key(self):
assert (... |
class TlsSubscription(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
lazy_import()
... |
class OptionPlotoptionsHistogramSonificationDefaultinstrumentoptionsMappingVolume(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, te... |
class OptionSeriesHistogramSonificationTracksMappingFrequency(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):
se... |
def minimize_cem(fn: Callable, x0: jnp.ndarray, key: jnp.ndarray, args: Optional[Tuple]=(), *, bounds: Tuple[(jnp.ndarray, jnp.ndarray)], n_iterations: int, population_size: int, elite_fraction: float, alpha: float, fn_use_key: bool=False, return_mean_elites: bool=False) -> jnp.ndarray:
num_elites = int((population... |
class AgentDialogue(GymDialogue):
def __init__(self, dialogue_label: DialogueLabel, self_address: Address, role: BaseDialogue.Role, message_class: Type[GymMessage]) -> None:
GymDialogue.__init__(self, dialogue_label=dialogue_label, self_address=self_address, role=role, message_class=message_class) |
def subscription_note_notify(subscription):
domain = Site.objects.get_current().domain
admin_path = urlresolvers.reverse('subscription_manage_detail', args=(subscription.location.slug, subscription.id))
text_content = ('Howdy,\n\nA new note has been added to a subscription for %s %s. \n\nManage this subscri... |
(urls.RULE_TARGET_DETAIL, status_code=HTTP_204_NO_CONTENT, dependencies=[Security(verify_oauth_client, scopes=[scope_registry.RULE_DELETE])])
def delete_rule_target(*, policy_key: FidesKey, rule_key: FidesKey, rule_target_key: FidesKey, db: Session=Depends(deps.get_db)) -> None:
policy = get_policy_or_error(db, pol... |
class TestSpotifyAudiobook():
.xfail(reason='API inconsistencies.')
def test_audiobook_without_market_raises(self, app_client):
app_client.audiobook(audiobook_id)
def test_audiobook_with_US_market(self, app_client):
book = app_client.audiobook(audiobook_id, market='US')
assert (book.... |
def test_multiple_subdomains_3d(mesh_3d):
DG = VectorFunctionSpace(mesh_3d, 'DG', 1)
n = FacetNormal(mesh_3d)
u = TestFunction(DG)
(x, y, z) = SpatialCoordinate(mesh_3d)
f = project(as_vector([x, y, z]), DG)
ds_sd = ds(1)
for i in range(2, 7):
ds_sd += ds(i)
form = (inner(n, (((f... |
class Book(db.Model):
__tablename__ = 'books'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
book_title = db.Column(db.String(128), unique=True, nullable=False)
secret_content = db.Column(db.String(128), nullable=False)
user_id = db.Column(db.Integer, ForeignKey('users.id'))
us... |
class PyfaceFont(TraitType):
default_value_type = DefaultValue.callable_and_args
parser = None
def __init__(self, value=None, *, parser=simple_parser, **metadata):
self.parser = parser
if (value is not None):
try:
font = self.validate(None, None, value)
... |
def check_for_employee(emp_name, emp_code, center):
err_msg = ''
filters = {}
if emp_name:
filters['employee_name'] = emp_name
if emp_code:
filters['zenoti_employee_code'] = emp_code
if (not filters):
err_msg = _('Details for Employee missing')
return err_msg
if (... |
def test_complex_fields():
assert (not SIM.complex_fields)
bound_spec = td.BoundarySpec(x=td.Boundary(plus=td.PECBoundary(), minus=td.PMCBoundary()), y=td.Boundary(plus=td.BlochBoundary(bloch_vec=1.0), minus=td.BlochBoundary(bloch_vec=1.0)), z=td.Boundary(plus=td.Periodic(), minus=td.Periodic()))
S2 = SIM_F... |
class BottleneckBlock(CNNBlockBase):
def __init__(self, in_channels, out_channels, *, bottleneck_channels, stride=1, num_groups=1, norm='BN', stride_in_1x1=False, dilation=1):
super().__init__(in_channels, out_channels, stride)
if (in_channels != out_channels):
self.shortcut = nn.Conv2dB... |
.compilertest
def test_hr_error_2():
yaml = '\n---\napiVersion: getambassador.io/v3alpha1\nkind: Mapping\nmetadata:\n name: mapping-1\n namespace: default\nspec:\n hostname: "*"\n prefix: /\n service: svc1\n host_redirect: true\n---\napiVersion: getambassador.io/v3alpha1\nkind: Mapping\nmetadata:\... |
class ProtocolVersion(enum.IntEnum):
VERSION_1 = 1
VERSION_2 = 2
VERSION_3 = 3
def prefix(self):
return (b'pysoa-redis/%d//' % self.value)
def extract_version(message_data):
match = PROTOCOL_VERSION_RE.match(message_data)
if match:
return (ProtocolVersion(int(matc... |
class JITTest(unittest.TestCase):
def test_function_transformation_1(self) -> None:
self.maxDiff = None
self.assertTrue(norm.is_random_variable)
bmgast = _bm_function_to_bmg_ast(f, 'f_helper')
observed = astor.to_source(bmgast)
expected = "\ndef f_helper(bmg):\n import ope... |
class User(SoftDeletionModel):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
_email = db.Column(CIText, unique=True, nullable=False)
_password = db.Column(db.String(128), nullable=False)
facebook_id = db.Column(db.BigInteger, unique=True, nullable=True, nam... |
class petsc_LU(KSP_Preconditioner):
def __init__(self, L, prefix=None):
self.PCType = 'lu'
self.L = L
self._initializePC(prefix)
self.pc.setFromOptions()
def _initializePC(self, prefix):
self.pc = p4pyPETSc.PC().create()
self.pc.setOptionsPrefix(prefix)
se... |
.scheduler()
.integration_test
.usefixtures('copy_poly_case', 'try_queue_and_scheduler', 'monkeypatch')
def test_failing_job_cli_error_message():
with open('poly_eval.py', mode='a', encoding='utf-8') as poly_script:
poly_script.writelines([" raise RuntimeError('Argh')"])
args = Mock()
args.config... |
def tri_occ(pos, ind, val, num):
ceof = np.zeros((512, 512, (num * 2)), dtype=np.float32)
mask = np.zeros((512, 512), dtype=np.bool_)
ktmp = np.zeros(num, dtype=np.float32)
for k in range(1, num, 1):
ktmp[k] = (k * np.pi)
prepre = 0
for i in range(len(pos)):
xx = (pos[i] // 512)
... |
class ChannelRedis(Channel):
def __init__(self, redis: Redis, channel_in: str, channel_out: str):
self._queue_in = MessageQueue(redis, channel_in)
self._queue_out = MessageQueue(redis, channel_out)
def send_message(self, message: Any):
self._queue_out.push(message)
def recv_message(s... |
def group_gemm_instance(op_def: str, func_attrs: Dict[(str, Any)], for_profiler: bool, cutlass_3x: bool=False):
op_def = update_alignments_in_group_gemm_instance(op_def, func_attrs, for_profiler)
tmp = op_def.replace('DefaultGemmUniversal', 'DefaultGemmGrouped')
tmp = tmp.replace('false,', '')
tmp = re.... |
class Post(Base):
__tablename__ = 'post'
id = Column(Integer, primary_key=True)
titulo = Column(String)
conteudo = Column(String)
autor_id = Column(Integer, ForeignKey('pessoa.id'))
autor = relationship('Pessoa', backref='post')
def __repr__(self):
return f'Post({self.titulo})' |
def extractWwwFishytranslationCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Op Waifus', 'Being Able to Edit Skills in Another World, I Gained OP Waifus', 'translated'), (... |
class Web3ModuleTest():
def test_web3_client_version(self, w3: Web3) -> None:
client_version = w3.client_version
self._check_web3_client_version(client_version)
def _check_web3_client_version(self, client_version: str) -> NoReturn:
raise NotImplementedError('Must be implemented by subcla... |
def extractSadstranslatesPage(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, tl_type) in... |
class LogFile():
def __init__(self, path):
self._path = path
def timestamp(self):
dstr = self.filename().split('_')[3]
return datetime.datetime(*map(int, [dstr[:4], dstr[4:6], dstr[6:8], dstr[9:11], dstr[11:13]])).replace(tzinfo=pytz.utc)
def filename(self):
return os.path.sp... |
.parametrize('value,expected', (('', False), ('0x', True), ('0X', True), ('abcdef', True), ('ABCDEF', True), ('AbCdEf', True), ('0xabcdef', True), ('0xABCDEF', True), ('0xAbCdEf', True), ('12345', True), ('0x12345', True), ('123456xx', False), ('0x123456xx', False), ('0\x80', False)))
def test_is_hex(value, expected):
... |
def graphs_with_cast_dereference_assignments():
x = vars('x', 2)
ptr = vars('ptr', 1, type=Pointer(int32))
in_n0 = BasicBlock(0, [_assign(x[0], _cast(int64, _deref(_add(ptr[0], _mul(x[1], Constant(4)))))), _call('func_modifying_pointer', [], [ptr[0]]), _ret(x[0])])
in_cfg = ControlFlowGraph()
in_cfg... |
class PhiDependencyResolver():
def __init__(self, phi_functions: Dict[(BasicBlock, List[Phi])]):
self._phi_functions_of = phi_functions
def resolve(self) -> None:
for (basic_block, phi_instructions) in self._phi_functions_of.items():
dependency_graph = PhiDependencyGraph(phi_instruct... |
class InitalizeTests(unittest.TestCase):
('anitya.db.meta.create_engine')
('anitya.db.meta.Session')
def test_initialize(self, mock_session, mock_create_engine):
config = {'DB_URL': 'postgresql://postgres:/mydb'}
engine = meta.initialize(config)
mock_create_engine.assert_called_once_... |
def parse_args():
parser = argparse.ArgumentParser(description='Create images from a text prompt.')
parser.add_argument('--attention-slicing', action='store_true', help='Use less memory at the expense of inference speed')
parser.add_argument('--device', type=str, nargs='?', default='cuda', help='The cpu or ... |
.django_db
def test_new_award_count_specific_award_type(client, monkeypatch, new_award_data, helpers, elasticsearch_award_index):
setup_elasticsearch_test(monkeypatch, elasticsearch_award_index)
resp = client.get(url.format(code='123', filter='?fiscal_year=2020&award_type_codes=[A,B]'))
assert (resp.status_... |
class CustomField(BaseObject):
def __init__(self, api=None, id=None, value=None, **kwargs):
self.api = api
self.id = id
self.value = value
for (key, value) in kwargs.items():
setattr(self, key, value)
for key in self.to_dict():
if (getattr(self, key) i... |
class ListUsersPage():
def __init__(self, download, page_token, max_results):
self._download = download
self._max_results = max_results
self._current = download(page_token, max_results)
def users(self):
return [ExportedUserRecord(user) for user in self._current.get('users', [])]
... |
class OptionSeriesScatterClusterDatalabels(Options):
def align(self):
return self._config_get('center')
def align(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type... |
.parametrize('matrix', [matrix])
.parametrize('outFileName', [outfile])
.parametrize('chromosomes', ['chrX', 'chr3R'])
.parametrize('action', ['keep', 'remove', 'mask'])
.parametrize('regions', [bed_file, None])
def test_trivial_run(matrix, outFileName, chromosomes, action, regions):
args = '--matrix {} --outFileNa... |
class MyComboBox(QComboBox):
remove_item_signal = Signal(str)
def __init__(self, parent=None):
QComboBox.__init__(self, parent=parent)
copy_action = QAction('Copy all', self, statusTip='', triggered=self._on_copy)
self.addAction(copy_action)
paste_action = QAction('Paste && repla... |
def test_mesh_fs_gced():
from firedrake.functionspacedata import FunctionSpaceData
gc.collect()
gc.collect()
nmesh = howmany((MeshTopology, MeshGeometry))
nfs = howmany(FunctionSpaceData)
for i in range(10):
m = UnitIntervalMesh(5)
for fs in ['CG', 'DG']:
V = Function... |
def test_quoting_of_filenames():
with requests_mock.mock(case_sensitive=True) as m:
client = FoundryRestClient()
needs_quotation = 'prod2_api_v2_reports_query?#2022-06-27T22_24_18.528205Z.json'
needs_no_quotation = 'All 123 - BLUB Extract_new (Export 2021-12-21 18_25)-.140314.csv'
m.... |
def test_convert_to_flyte_state():
assert (convert_to_flyte_state('FAILED') == RETRYABLE_FAILURE)
assert (convert_to_flyte_state('TIMEDOUT') == RETRYABLE_FAILURE)
assert (convert_to_flyte_state('CANCELED') == RETRYABLE_FAILURE)
assert (convert_to_flyte_state('DONE') == SUCCEEDED)
assert (convert_to_... |
class LiveVideoTargeting(AbstractObject):
def __init__(self, api=None):
super(LiveVideoTargeting, self).__init__()
self._isLiveVideoTargeting = True
self._api = api
class Field(AbstractObject.Field):
age_max = 'age_max'
age_min = 'age_min'
excluded_countries = 'ex... |
_required
def is_registrar(view, view_args, view_kwargs, *args, **kwargs):
user = current_user
event_id = kwargs['event_id']
if user.is_staff:
return view(*view_args, **view_kwargs)
if (user.is_registrar(event_id) or user.has_event_access(event_id)):
return view(*view_args, **view_kwargs... |
class StaticStorageBackend(AbstractStateBackend):
def get_value(self):
filename = settings.MAINTENANCE_MODE_STATE_FILE_NAME
if staticfiles_storage.exists(filename):
with staticfiles_storage.open(filename, 'r') as statefile:
return self.from_str_to_bool_value(statefile.rea... |
class TestLedgerApiHandler(ERC1155ClientTestCase):
is_agent_to_agent_messages = False
def test_setup(self):
assert (self.ledger_api_handler.setup() is None)
self.assert_quantity_in_outbox(0)
def test_handle_unidentified_dialogue(self):
incorrect_dialogue_reference = ('', '')
... |
_ns.route('/reschedule_build_chroot/', methods=['POST', 'PUT'])
_authenticated
def reschedule_build_chroot():
response = {}
build_id = flask.request.json.get('build_id')
task_id = flask.request.json.get('task_id')
chroot = flask.request.json.get('chroot')
try:
build = ComplexLogic.get_build(... |
class TestSuperFencesCustomLegacyArithmatexPreview(util.MdCase):
extension = ['pymdownx.superfences']
extension_configs = {'pymdownx.superfences': {'custom_fences': [{'name': 'math', 'class': 'arithmatex', 'format': arithmatex.fence_mathjax_preview_format}]}}
def test_legacy_arithmatex_preview(self):
... |
.parametrize('widget_class,kwargs', parameters)
def test_widget_init_config(manager_nospawn, minimal_conf_noscreen, widget_class, kwargs):
if (widget_class in exclusive_backend):
if (exclusive_backend[widget_class] != manager_nospawn.backend.name):
pytest.skip('Unsupported backend')
widget =... |
class BucketData(object):
def __init__(self):
self.data_list = []
self.label_list = []
self.label_list_plain = []
self.comment_list = []
def append(self, datum, label, label_plain, comment):
self.data_list.append(datum)
self.label_list.append(label)
self.l... |
def test_get_messages_with_round(conversation_with_messages):
last_round_messages = conversation_with_messages.get_messages_with_round(1)
assert (len(last_round_messages) == 2)
assert (last_round_messages[0].content == 'How are you?')
assert (last_round_messages[1].content == "I'm good, thanks")
las... |
def test_int():
c = Config('testconfig', foo=(1, int, ''), bar=('1', int, ''))
assert (c.foo == 1)
assert (c.bar == 1)
c.foo = 12.1
assert (c.foo == 12)
c.foo = '7'
assert (c.foo == 7)
c.foo = '-23'
assert (c.foo == (- 23))
for val in ([], None, '1e2', '12.1', 'a'):
with ... |
def is_sim_folder_ok(sim_folder):
if (not os.path.exists(sim_folder)):
logging.error((('The provided DispaSET simulation environment folder (' + sim_folder) + ') does not exist'))
return False
if (not os.path.exists(os.path.join(sim_folder, u'Inputs.gdx'))):
logging.error((('There is no ... |
def extractYummytlsWordpressCom(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, tl_type) ... |
((detect_target().name() == 'rocm'), 'Not supported by ROCM.')
class GroupGEMMRcrTestCase(unittest.TestCase):
([param(False, 'group_gemm_rcr_run_once', 'float16'), param(True, 'group_gemm_rcr_run_twice', 'float16'), param(False, 'group_gemm_rcr_run_once_fp32', 'float32'), param(False, 'group_gemm_rcr_run_once_bf16'... |
class OptionNavigationAnnotationsoptionsControlpointoptionsStyle(Options):
def cursor(self):
return self._config_get('pointer')
def cursor(self, text: str):
self._config(text, js_type=False)
def fill(self):
return self._config_get('#ffffff')
def fill(self, text: str):
sel... |
.integration()
def test_two_instances(random_file, fsspec_write_test_folder):
random_file = random_file.get()
fs = FoundryFileSystem(dataset=fsspec_write_test_folder[0], branch='master')
fs_other_instance = FoundryFileSystem(dataset=fsspec_write_test_folder[0], branch='master', skip_instance_cache=True)
... |
class PluginAgent(ConversableAgent):
DEFAULT_SYSTEM_MESSAGE = '\n You are a useful artificial intelligence tool agent assistant.\n You have been assigned the following list of tools, please select the most appropriate tool to complete the task based on the current user\'s goals:\n {tool_list}\n ... |
def email(entry, option_key='Email Address', **kwargs):
if (not entry):
raise ValueError(_('Email address field empty!'))
valid = validate_email_address(entry)
if (not valid):
raise ValueError(_("That isn't a valid {option_key}!").format(option_key=option_key))
return entry |
class OptionSeriesColumnrangeMarkerStates(Options):
def hover(self) -> 'OptionSeriesColumnrangeMarkerStatesHover':
return self._config_sub_data('hover', OptionSeriesColumnrangeMarkerStatesHover)
def normal(self) -> 'OptionSeriesColumnrangeMarkerStatesNormal':
return self._config_sub_data('normal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.