code stringlengths 281 23.7M |
|---|
def _get_settable_columns(source: ETLObjectBase, destination: ETLWritableObjectBase):
settable_columns = [c for c in destination.columns if (((c in source.columns) or (c in destination.update_overrides)) and (c not in destination.key_columns))]
if (not settable_columns):
raise RuntimeError('No settable ... |
def msgCheck(message):
if (message.reply_to_message.content_type == 'text'):
msg_check = message.reply_to_message.text
elif ((message.reply_to_message.content_type == 'photo') or (message.reply_to_message.content_type == 'document')):
msg_check = message.reply_to_message.caption
return msg_c... |
class Application(BaseLogic):
name: str
connection: ConnectionAPI
_behaviors: Tuple[(BehaviorAPI, ...)] = ()
def add_child_behavior(self, behavior: BehaviorAPI) -> None:
self._behaviors += (behavior,)
async def apply(self, connection: ConnectionAPI) -> AsyncIterator[asyncio.Task[Any]]:
... |
def get_duration(duration_idx):
if (duration_idx == 0):
return Config.DURATION_ONCE
elif (duration_idx == 1):
return _constants.DURATION_30s
elif (duration_idx == 2):
return _constants.DURATION_5m
elif (duration_idx == 3):
return _constants.DURATION_15m
elif (duration... |
def CatchException(f):
(f)
def decorated(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT=(- 1)):
try:
(yield from f(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT))
except Exception as e:
from check_proxy import check_proxy
... |
def audit_systems(url: str, headers: Dict[(str, str)], include_keys: Optional[List]=None) -> None:
system_resources: Optional[Union[(List[FidesModel], List[Dict])]]
if include_keys:
system_resources = get_server_resources(url, 'system', include_keys, headers)
else:
system_resources = list_se... |
(expression='^Starting phase (\\d+)/4: (Forward Propagation into tmp files\\.\\.\\. (.+))?')
def phase_major(match: typing.Match[str], info: SpecificInfo) -> SpecificInfo:
major = int(match.group(1))
timestamp = match.group(3)
new_info = attr.evolve(info, phase=plotman.job.Phase(major=major, minor=0))
i... |
class HWB(base.HWB):
def to_string(self, parent: 'Color', *, alpha: Optional[bool]=None, precision: Optional[int]=None, fit: Union[(str, bool)]=True, none: bool=False, color: bool=False, **kwargs: Any) -> str:
return serialize.serialize_css(parent, func='hwb', alpha=alpha, precision=precision, fit=fit, none... |
class AMIClientListener(object):
methods = ['on_action', 'on_response', 'on_event', 'on_connect', 'on_disconnect', 'on_unknown']
def __init__(self, **kwargs):
for (k, v) in kwargs.items():
if (k not in self.methods):
raise TypeError(("'%s' is an invalid keyword argument for t... |
class OptionPlotoptionsWaterfallSonificationTracksMappingNoteduration(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 DictEventTestCase(unittest.TestCase):
def test_setitem(self):
cb = Callback(self, changed={'c': 'cherry'})
foo = MyClass(cb)
foo.d['c'] = 'coconut'
self.assertTrue(cb.called)
cb = Callback(self, added={'g': 'guava'})
bar = MyClass(cb)
bar.d['g'] = 'guava... |
def attention_ref(qkv, attn_mask, dropout_p, upcast=False, causal=False):
if (True or (causal and (attn_mask is not None))):
return attention_ref_math(qkv, attn_mask, dropout_p, upcast=upcast, causal=causal)
return attention_ref_sdpa(qkv, attn_mask, dropout_p, upcast=upcast, causal=causal) |
def test_circular_dependency_minimization(graph_circular_dependency, variable, copy_variable):
(nodes, _, cfg) = graph_circular_dependency
run_out_of_ssa(cfg, SSAOptions.minimization)
variable[0].is_aliased = True
variable[1].is_aliased = True
assert ((nodes[0].instructions == [Assignment(ListOperat... |
def extractYabaitranslationsBlogspotCom(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, t... |
class isIP(Validator):
message = 'Invalid IP address'
def __init__(self, min='0.0.0.0', max='255.255.255.255', invert=False, localhost=None, private=None, auto=None, ipv4=None, link_local=None, reserved=None, multicast=None, routable=None, to4=None, teredo=None, subnets=None, ipv6=None, message=None):
s... |
class TestGetreadsRegexpFunction(unittest.TestCase):
def setUp(self):
self.wd = tempfile.mkdtemp()
self.example_fastq_data = u':43:HL3LWBBXX:8:1101:21440:1121 1:N:0:CNATGT\nGCCNGACAGCAGAAAT\n+\nAAF#FJJJJJJJJJJJ\:43:HL3LWBBXX:8:1101:21460:1121 1:N:0:CNATGT\nGGGNGTCATTGATCAT\n+\nAAF#FJJJJJJJJJJJ\:43:H... |
def send_email(user, vulnerabilities):
template_file = os.path.abspath(sys.argv[2])
templateLoader = FileSystemLoader(searchpath='/')
templateEnv = Environment(loader=templateLoader)
template = templateEnv.get_template(template_file)
msg = MIMEText(template.render(vulnerabilities=vulnerabilities), _... |
class Grid(object):
def find_path(self, matrix):
if ((matrix is None) or (not matrix)):
return None
cache = {}
path = []
if self._find_path(matrix, (len(matrix) - 1), (len(matrix[0]) - 1), cache, path):
return path
else:
return None
def... |
def get_serializable_branch_node(entity_mapping: OrderedDict, settings: SerializationSettings, entity: FlyteLocalEntity, options: Optional[Options]=None) -> BranchNodeModel:
first = to_serializable_case(entity_mapping, settings, entity._ifelse_block.case, options)
other = to_serializable_cases(entity_mapping, s... |
_user.command()
_context
def execute(ctx):
error = MODULE.check_options()
if error:
return
password = click.prompt('[*] Enter a password for the new user. The input for this value is hidden', hide_input=True)
msg = f"Attempting to create new Okta user {MODULE_OPTIONS['login']['value']}"
LOGG... |
class OptionPlotoptionsGaugeSonificationTracksMappingPlaydelay(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):
s... |
class LiteEthUDPRX(LiteXModule):
def __init__(self, ip_address, dw=8):
self.sink = sink = stream.Endpoint(eth_ipv4_user_description(dw))
self.source = source = stream.Endpoint(eth_udp_user_description(dw))
self.depacketizer = depacketizer = LiteEthUDPDepacketizer(dw)
self.comb += [si... |
def list_file_parser(params):
return_val = []
if isfile(params.get('list')):
with open(params.get('list', 'r')) as f:
userfile_content = f.read().splitlines()
f.close()
for line in userfile_content:
return_val.append({'email': line.split(':')[0], 'pass... |
def parse_py_file(filepath):
line_err_map = {}
regex = re.compile('#[\\s]*E:[\\s]* (.*)')
with filepath.open(encoding='utf-8') as fp:
line_count = 0
lines = fp.readlines()
for line in lines:
line_count += 1
match = regex.search(line)
if match:
... |
class OptionPlotoptionsBulletSonificationContexttracksMappingHighpassResonance(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:... |
class FootnotePostTreeprocessor(Treeprocessor):
def __init__(self, footnotes):
self.footnotes = footnotes
def add_duplicates(self, li, duplicates):
for link in li.iter('a'):
if (link.attrib.get('class', '') == 'footnote-backref'):
(ref, rest) = link.attrib['href'].spl... |
class _AnimatedGIFEditor(Editor):
playing = Bool(True)
def init(self, parent):
self._animate = Animation(self.value)
self.control = GenericAnimationCtrl(parent, (- 1), self._animate)
self.control.SetUseWindowBackgroundColour()
self.sync_value(self.factory.playing, 'playing', 'fro... |
def generate_op_class(entity, draw=draw_stalker_entity_menu_item, idpostfix='', label=None):
idname = ('%s%s' % ((idname_template % (entity.entity_type, entity.id)), idpostfix))
return type(idname, (bpy.types.Menu,), {'bl_idname': idname, 'bl_label': (label if label else entity.name), 'stalker_entity_id': entit... |
class AzureStorage(object):
_fakedir = '.dir'
_copy_poll_interval_seconds = 1
_send_file_lookback = timedelta(minutes=15)
_send_file_validity = timedelta(hours=1)
separator = '/'
def __init__(self, container_name, connection_string):
if (not BlockBlobService):
raise ValueErro... |
.parallel(nprocs=2)
def test_input_ordering_missing_point():
m = UnitIntervalMesh(4)
points = np.asarray([[0.125], [0.375], [0.625], [5.0]])
data = np.asarray([1.0, 2.0, 3.0, 4.0])
vm = VertexOnlyMesh(m, points, missing_points_behaviour=None, redundant=True)
P0DG_input_ordering = FunctionSpace(vm.in... |
class OptionChartAreaBorder(Options):
def borderColor(self):
return self._config_get()
def borderColor(self, text: str):
self._config(text)
def borderWidth(self):
return self._config_get()
def borderWidth(self, num: int):
self._config(num)
def borderDash(self):
... |
class Instance(object):
__slots__ = ('_type', '_values', '_sizes')
def __init__(self, type_, values, sizes=None):
object.__setattr__(self, '_type', type_)
object.__setattr__(self, '_values', values)
object.__setattr__(self, '_sizes', sizes)
def __getattr__(self, attr):
try:
... |
class BotPlugin(BotPluginBase):
def get_configuration_template(self) -> Mapping:
return None
def check_configuration(self, configuration: Mapping) -> None:
recurse_check_structure(self.get_configuration_template(), configuration)
def configure(self, configuration: Mapping) -> None:
s... |
class Migration(migrations.Migration):
dependencies = [('manager', '0017_auto__1610')]
operations = [migrations.AddField(model_name='activity', name='num_vote_down', field=models.PositiveIntegerField(db_index=True, default=0)), migrations.AddField(model_name='activity', name='num_vote_up', field=models.Positive... |
class TestCheckListEditorSimpleDemo(unittest.TestCase):
def test_checklist_editor_simple_demo(self):
demo = runpy.run_path(DEMO_PATH)['demo']
tester = UITester()
with tester.create_ui(demo) as ui:
checklist = tester.find_by_id(ui, 'custom')
item3 = checklist.locate(In... |
class OptionSeriesSunburstSonificationDefaultspeechoptionsMappingPitch(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('undefined')
def mapTo(self, text: ... |
def _get_cls_name(config: Any, pop: bool=True) -> str:
if ('_target_' not in config):
raise InstantiationException('Input config does not have a `_target_` field')
if pop:
classname = config.pop('_target_')
else:
classname = config['_target_']
if (not isinstance(classname, str)):... |
class CategoryWithStringPk(TreeNodeModel):
treenode_display_field = 'name'
def get_random_string():
return ''.join((random.choice((string.letters + string.digits)) for n in range(64)))
id = models.CharField(primary_key=True, max_length=100, default=get_random_string, editable=False)
name = model... |
class VenvEnvironmentService(_BentoMLService):
def __init__(self, model_id, config_json=None, preferred_port=None, url=None):
_BentoMLService.__init__(self, model_id=model_id, config_json=config_json, preferred_port=preferred_port)
self.venv = SimpleVenv(self._model_path(model_id))
def __enter__... |
class DjangoModelPermissions(BasePermission):
perms_map = {'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': [], 'HEAD': ['%(app_label)s.view_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELE... |
class PublicKeyAccount():
def __init__(self, addr: str) -> None:
self.address = _resolve_address(addr)
def __repr__(self) -> str:
return f"<{type(self).__name__} '{self.address}'>"
def __hash__(self) -> int:
return hash(self.address)
def __str__(self) -> str:
return self.... |
class UseNote(models.Model):
created = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, null=True)
booking_deprecated = models.ForeignKey(Booking, blank=True, null=True, related_name='booking_notes')
use = models.ForeignKey(Use, blank=False, null=False, related_name='use_note... |
class OptionPlotoptionsStreamgraphSonificationDefaultinstrumentoptions(Options):
def activeWhen(self) -> 'OptionPlotoptionsStreamgraphSonificationDefaultinstrumentoptionsActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsStreamgraphSonificationDefaultinstrumentoptionsActivewhen)
de... |
class ReadWriteDbInterface(ReadOnlyDbInterface):
def __init__(self, connection: (DbConnection | None)=None):
super().__init__(connection=(connection or ReadWriteConnection()))
def get_read_write_session(self) -> Session:
session = self.connection.session_maker()
try:
(yield s... |
.flaky(reruns=1, condition=(arg_preload_port is not False))
class EsptoolTestCase():
def run_espsecure(self, args):
cmd = ([sys.executable, '-m', 'espsecure'] + args.split(' '))
print('\nExecuting {}...'.format(' '.join(cmd)))
try:
output = subprocess.check_output([str(s) for s i... |
class ServerSettings(SOASettings):
schema = dict({'transport': fields.ClassConfigurationSchema(base_class=BaseServerTransport), 'middleware': fields.List(fields.ClassConfigurationSchema(base_class=ServerMiddleware), description='The list of all `ServerMiddleware` objects that should be applied to requests processed... |
def extractClaudeyoungladyWordpressCom(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... |
def fortios_firewall(data, fos, check_mode):
fos.do_member_operation('firewall', 'policy64')
if data['firewall_policy64']:
resp = firewall_policy64(data, fos, check_mode)
else:
fos._module.fail_json(msg=('missing task body: %s' % 'firewall_policy64'))
if check_mode:
return resp
... |
def build_python(build, *, datadir=None, optlevel=0, prefix=None, force=False, verbose=False):
argv = [CPYTHON_SCRIPT, '--datadir', (datadir or '-'), '--build', (build or '-'), '--optlevel', (str(optlevel) if (optlevel is not None) else '-'), '--prefix', (prefix or '-')]
if force:
argv.append('--force')... |
class TestCase(unittest.TestCase):
def setUp(self) -> None:
testslide.mock_callable.register_assertion = (lambda assertion: self.addCleanup(assertion))
self.addCleanup(testslide.mock_callable.unpatch_all_callable_mocks)
self.addCleanup(testslide.mock_constructor.unpatch_all_constructor_mocks... |
def pql_temptable(expr: T.table, const: T.bool.as_nullable()=objects.null):
const = cast_to_python(const)
assert_type(expr.type, T.table, expr, 'temptable')
name = get_db().qualified_name(Id(unique_name('temp')))
with use_scope({'__unwind__': []}):
return new_table_from_expr(name, expr, const, T... |
class TestDate(unittest.TestCase):
def test_default(self):
obj = HasDateTraits()
self.assertEqual(obj.simple_date, None)
self.assertEqual(obj.epoch, UNIX_EPOCH)
self.assertEqual(obj.alternative_epoch, NT_EPOCH)
def test_assign_date(self):
test_date = datetime.date(1975, 2... |
class aggregate_stats_request(stats_request):
version = 3
type = 18
stats_type = 2
def __init__(self, xid=None, flags=None, table_id=None, out_port=None, out_group=None, cookie=None, cookie_mask=None, match=None):
if (xid != None):
self.xid = xid
else:
self.xid = ... |
def copy_extension_dir(extension: str, work_dir: str) -> None:
global config
extension_package_source_dir = os.path.join(config.source_dir, 'build/labextensions/', extension)
extension_package_dest_dir = os.path.join(work_dir, 'build/labextensions/', extension)
os.makedirs(os.path.dirname(extension_pack... |
def pattern_match(patterns, out):
assert (type(patterns) == dict)
assert (type(out) == bytearray)
matches = {}
for p in patterns.keys():
matches[p] = []
FOUND = out.find(patterns[p])
while (FOUND != (- 1)):
matches[p].append(FOUND)
FOUND = out.find(pattern... |
()
def raw_config_full():
return binascii.unhexlify('af006c0075006d006eccf006c0075006d006e0043006f0075006ebf006c0075006d006e004de9c0000759c0000779c0000879c0000799c0000749c00008c9c00008d9c0000e49c0000929c00007a9c0000849c0000839c0000939c0000889c0000949c0000959c0000969c0000979c0000989c0000769c0000789c0000809c0000819c0... |
def generate_download(download_job: DownloadJob, origination: Optional[str]=None):
json_request = json.loads(download_job.json_request)
columns = json_request.get('columns', None)
limit = json_request.get('limit', None)
piid = json_request.get('piid', None)
award_id = json_request.get('award_id')
... |
def multi_unscramble(coins, addrs):
coins = coins[:]
ks = [coins.count(c) for c in addrs]
pos = 0
at = 0
while (pos < len(coins)):
if (coins[pos] in addrs):
coins[pos] = addrs[at]
ks[at] -= 1
if (ks[at] == 0):
at += 1
pos += 1
r... |
def test_custom_render_body():
class CustomResponse(falcon.asgi.Response):
async def render_body(self):
body = (await super().render_body())
if (not self.content_type.startswith('text/plain')):
return body
if (not body.endswith(b'\n')):
ret... |
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.')
def test_wf1_with_sql_with_patch():
import pandas as pd
sql = SQLTask('my-query', query_template="SELECT * FROM hive.city.fact_airport_sessions WHERE ds = '{{ .Inputs.ds }}' LIMIT 10", inputs=kwtypes(ds=datetime.datetime), outputs=kwtypes... |
def test_foreign_city(client, awards_and_transactions):
resp = client.get('/api/v2/awards/13/')
assert (resp.status_code == status.HTTP_200_OK)
assert (json.loads(resp.content.decode('utf-8'))['recipient']['location'] == {'address_line1': '123 main st', 'address_line2': None, 'address_line3': None, 'foreign... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--port', '-p', help='Port to run the API webserver on', type=int, default=8000)
parser.add_argument('--prom_addr', '-a', help='Prometheus address connected to Poseidon, i.e. "prometheus:9090"', default='prometheus:9090')
args = parser.p... |
class TradeEnv(object):
defaults = {'debug': 0, 'detail': 0, 'quiet': 0, 'color': False, 'dataDir': (os.environ.get('TD_DATA') or os.path.join(os.getcwd(), 'data')), 'csvDir': (os.environ.get('TD_CSV') or os.environ.get('TD_DATA') or os.path.join(os.getcwd(), 'data')), 'tmpDir': (os.environ.get('TD_TMP') or os.path... |
(scope='function')
def jira_create_erasure_data(jira_connection_config: ConnectionConfig, jira_erasure_identity_email: str) -> None:
jira_secrets = jira_connection_config.secrets
base_url = f"
body = {'name': 'Ethyca Test Erasure', 'emailAddress': jira_erasure_identity_email}
users_response = requests.p... |
class TestIgPgTgSerialize(util.ColorAssertsPyTest):
COLORS = [('color(--igpgtg 0.75 0.1 -0.1 / 0.5)', {}, 'color(--igpgtg 0.75 0.1 -0.1 / 0.5)'), ('color(--igpgtg 0.75 0.1 -0.1)', {'alpha': True}, 'color(--igpgtg 0.75 0.1 -0.1 / 1)'), ('color(--igpgtg 0.75 0.1 -0.1 / 0.5)', {'alpha': False}, 'color(--igpgtg 0.75 0.... |
.slow
.skipif((not GPU_TESTS_ENABLED), reason='requires GPU')
def test_generate_sample(falcon_generator):
prompts = ['What is spaCy?\n', 'What is spaCy?\n']
torch.manual_seed(0)
assert (falcon_generator(prompts, config=SampleGeneratorConfig(top_k=10)) == ["spaCy is a Python package for natural language proc... |
def get_audio_player(duration: float, filename: str, pkg: typing.Optional[str]=None, start_at: float=BEGINNING) -> Stimulus:
return QtStimulus(start_at=start_at, duration=duration, qt_type='QMediaPlayerWithMediaContent', callbacks=[('setMedia', Deferred('player.getMediaContent', get_filepath(filename, pkg)))]) |
.skip(reason='CI runner needs more GPU memory')
.gpu
.skipif((not has_torch_cuda_gpu), reason='needs GPU & CUDA')
def test_init_from_config():
orig_config = Config().from_str(_NLP_CONFIG)
nlp = spacy.util.load_model_from_config(orig_config, auto_fill=True)
assert (nlp.pipe_names == ['llm'])
torch.cuda.e... |
def _click_to_tree(ctx: click.Context, node: Union[(click.Command, click.MultiCommand)], ancestors: list=None):
if (ancestors is None):
ancestors = []
res_childs = []
res = OrderedDict()
res['is_group'] = isinstance(node, click.core.MultiCommand)
if res['is_group']:
children = [node.... |
def panel(ui):
ui.info.bind_context()
content = ui._groups
nr_groups = len(content)
if (nr_groups == 0):
panel = None
if (nr_groups == 1):
panel = _GroupPanel(content[0], ui).control
elif (nr_groups > 1):
panel = QtGui.QTabWidget()
_fill_panel(panel, content, ui)
... |
class PhoneActivationProfileForm(forms.Form):
phone_token = forms.CharField(label=_('Phone activation code'), max_length=24, required=True, widget=forms.TextInput(attrs={'required': 'required', 'class': 'input-transparent', 'maxlength': '16', 'placeholder': _('Phone activation code')}))
def __init__(self, token... |
def extractYametteTranslations(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, ... |
.parametrize('url', [FIGSHAREURL, ZENODOURL, DATAVERSEURL], ids=['figshare', 'zenodo', 'dataverse'])
def test_doi_downloader(url):
with TemporaryDirectory() as local_store:
downloader = DOIDownloader()
outfile = os.path.join(local_store, 'tiny-data.txt')
downloader((url + 'tiny-data.txt'), o... |
def extractWatonbarBlogspotCom(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) i... |
class Behavior(BehaviorAPI):
_applied_to: ConnectionAPI = None
def __init__(self, qualifier: QualifierFn, logic: LogicAPI) -> None:
self.qualifier = qualifier
self.logic = logic
def should_apply_to(self, connection: 'ConnectionAPI') -> bool:
return self.qualifier(connection, self.log... |
def test_usm_pretty_sec():
instance = usm.USMSecurityParameters(b'engine-id', 123, 234, b'username', b'auth', b'priv')
result = instance.pretty()
assert isinstance(result, str)
assert ('engine-id' in result)
assert ('123' in result)
assert ('234' in result)
assert ('username' in result)
... |
class ActionExpectsNotPresentDirective(ActionDirective):
def name(cls):
return 'expect_not_present'
def get_full_grammar(cls):
return ((((((super(ActionExpectsNotPresentDirective, cls).get_full_grammar() + Literal('expect not present')) + ':') + Literal('attribute value')) + ':') + VarNameGramma... |
def main() -> None:
import argparse
parser = argparse.ArgumentParser(description='Measuring the Compute Kernel Performance Using PyTorch')
parser.add_argument('--warmups', type=int, default=10, help='warmup times')
parser.add_argument('--steps', type=int, default=100, help='repeat times')
parser.add... |
((detect_target().name() == 'rocm'), 'Not supported by ROCM.')
class SizeGetItemTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(SizeGetItemTestCase, self).__init__(*args, **kwargs)
self._test_id = 0
def _test_size_op(self, batch_size=(1, 3), X_shape=(16, 32, 64), Y_shape=... |
class TestBoundingBoxDistanceGraphicMatcher():
def test_should_return_empty_list_with_empty_list_of_graphics(self):
result = BoundingBoxDistanceGraphicMatcher().get_graphic_matches(semantic_graphic_list=[], candidate_semantic_content_list=[SemanticMixedContentWrapper()])
assert (not result)
def ... |
_parameters()
(name='None', selector_filter=FiltersSchema(), should_raise=False)
(name='report filter1', selector_filter=FiltersSchema(selector='invocation_id:mock_invocation_id'), should_raise=False)
(name='report filter2', selector_filter=FiltersSchema(selector='invocation_time:mock_invocation_time'), should_raise=Fa... |
((not HAS_PY_INOTIFY), 'This can only run if PyInotify is installed')
class TestPyInotifyReloader(unittest.TestCase):
def test_code_changed(self):
from multiprocessing.pool import ThreadPool
codec = codecs.lookup('utf8')
with tempfile.NamedTemporaryFile('wb') as tmp_file1, tempfile.NamedTemp... |
.parametrize('data', CLASSIFICATION_DATASETS.keys())
.parametrize('model', CLASSIFICATION_MODELS.keys())
.parametrize('method', METHODS)
def test_trees_sklearn_classifier_predict(data, model, method):
(X, y) = CLASSIFICATION_DATASETS[data]
estimator = CLASSIFICATION_MODELS[model]
estimator.fit(X, y)
cmo... |
def main():
torch.manual_seed(0)
img_size = [192, 256]
dataset_dir = '/path_to/tum/rgbd_dataset_freiburg3_long_office_household/'
dataset = TumOdometryDataset(dataset_dir, img_size)
with open('./config/open3d_viz.yml', 'r') as file:
viz_cfg = yaml.safe_load(file)
with open('./config/tum.... |
def get_selected_camera():
for obj in pm.ls(sl=1, type=pm.nt.Transform):
if isinstance(obj, pm.nt.Transform):
for shape in obj.listRelatives(s=True):
if isinstance(shape, pm.nt.Camera):
return shape
elif isinstance(obj, pm.nt.Camera):
retur... |
def parse_json(web_json: dict, logger: Logger, zone_key: ZoneKey) -> dict[(str, Any)]:
if (set(JSON_QUERY_TO_SRC.values()) != set(web_json.keys())):
logger.error(msg=f'Fetched keys from source {web_json.keys()} do not match expected keys {JSON_QUERY_TO_SRC.values()}.', extra={'zone_key': zone_key, 'parser':... |
def setup_to_pass():
with open('/etc/dconf/profile/gdm', 'w') as f:
f.writelines(['user-db:user\n', 'system-db:gdm\n', 'file-db:/usr/share/gdm/greeter-dconf-defaults\n'])
with open('/etc/dconf/db/gdm.d/01-banner-message', 'w') as f:
f.writelines(['[org/gnome/login-screen]\n', 'banner-message-ena... |
def test_pyscf_bas():
basis_str = '\n # Comment1\n He S\n 13.6267000 0.1752300\n 1.9993500 0.8934830\n 0.3829930 0.0000000\n He S\n 13.6267000 0.0000000\n 1.9993500 0.0000000\n 0.38299... |
class Xero():
OBJECT_LIST = ('Attachments', 'Accounts', 'BankTransactions', 'BankTransfers', 'BrandingThemes', 'BatchPayments', 'ContactGroups', 'Contacts', 'CreditNotes', 'Currencies', 'Employees', 'ExpenseClaims', 'Invoices', 'Items', 'Journals', 'ManualJournals', 'Organisations', 'Overpayments', 'PaymentServices... |
(scope='function')
def friendbuy_nextgen_connection_config(db: session, friendbuy_nextgen_config, friendbuy_nextgen_secrets) -> Generator:
fides_key = friendbuy_nextgen_config['fides_key']
connection_config = ConnectionConfig.create(db=db, data={'key': fides_key, 'name': fides_key, 'connection_type': Connection... |
class TestColumnValueMax(BaseFeatureDataQualityMetricsTest):
name: ClassVar = 'Max Value'
def get_stat(self, current: NumericCharacteristics):
return current.max
def get_condition_from_reference(self, reference: Optional[ColumnCharacteristics]) -> TestValueCondition:
if (reference is not Non... |
def train(context):
from dl_on_flink_tensorflow.tensorflow_context import TFContext
tf_context = TFContext(context)
cluster = tf_context.get_tf_cluster_config()
os.environ['TF_CONFIG'] = json.dumps({'cluster': cluster, 'task': {'type': tf_context.get_node_type(), 'index': tf_context.get_index()}})
l... |
def test_data_too_large(client):
resp = client.simulate_post('/submit', headers={'Content-Type': 'multipart/form-data; boundary=BOUNDARY'}, body=EXAMPLE3)
assert (resp.status_code == 400)
assert (resp.json == {'description': 'body part is too large', 'title': 'Malformed multipart/form-data request media'}) |
class VisDataOptions(DataAttrs):
def align(self, position: Union[(str, primitives.JsDataModel)]):
return self.attr('align', JsUtils.jsConvertData(position, None))
def queue_delay(self, n: Union[(int, primitives.JsDataModel)]=None):
if (n is None):
n = self.page.js.data.null
r... |
def dataset_config(db: Session, connection_config: ConnectionConfig, dataset: Dict[(str, Any)]) -> DatasetConfig:
fides_key = dataset['fides_key']
connection_config.name = fides_key
connection_config.key = fides_key
connection_config.save(db=db)
ctl_dataset = CtlDataset.create_from_dataset_dict(db, ... |
class PDSResponseDecryptor(BaseStantinkoDecryptor):
def __init__(self):
super(self.__class__, self).__init__()
self.param = None
def parse_response(self, response):
try:
data = base64.b64decode(response)
except TypeError as e:
self.errors.append(e)
... |
class OptionSeriesBulletSonificationDefaultspeechoptionsPointgrouping(Options):
def algorithm(self):
return self._config_get('last')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
... |
def path_put(out, path, value):
(slot, path_rest) = _path_get_next_path_element(path)
if (path_rest is None):
if (slot is None):
return
if isinstance(out, list):
assert isinstance(slot, int), path
_vivify_array(out, slot, dict)
out[slot] = value
el... |
class AITInterpreter(torch.fx.Interpreter):
def __init__(self, module: torch.fx.GraphModule, input_specs: List[Union[(TensorSpec, List[TensorSpec])]], workdir: str, name: str, dll_name: str='test.so', dynamic_profile_strategy=DynamicProfileStrategy.MAX, profile_devs=None, use_fp16_acc=True, dump_ait_dir: Optional[s... |
class WebServerValidator(metaclass=Singleton):
def __init__(self):
self.request_handler = RequestHandler()
def validate_target_webserver(self, host):
try:
self.request_handler.send('GET', timeout=20, url='{}://{}:{}'.format(host.protocol, host.target, host.port))
return T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.