code stringlengths 281 23.7M |
|---|
def check_binary():
binary = which(OVERLAP_EXEC)
if (not binary):
logger.error('"%s" native module not found', OVERLAP_EXEC)
return False
try:
devnull = open(os.devnull, 'w')
subprocess.check_call([OVERLAP_EXEC, '--help'], stderr=devnull)
except subprocess.CalledProcessEr... |
class RichText(models.Model):
text = CleansedRichTextField(_('text'), config_name='richtext-plugin')
class Meta():
abstract = True
verbose_name = _('rich text')
verbose_name_plural = _('rich texts')
def __str__(self):
return Truncator(strip_tags(self.text)).words(10, truncate... |
def observation_spaces_to_in_shapes(observation_spaces: Dict[(Union[(int, str)], gym.spaces.Dict)]) -> Dict[(Union[(int, str)], Dict[(str, Sequence[int])])]:
in_shapes = dict()
for (obs_key, obs_dict) in observation_spaces.items():
in_shapes[obs_key] = dict()
assert isinstance(obs_dict, gym.spac... |
('cuda.perm102_bmm_rrr_bias.gen_function')
def gen_function(func_attrs, exec_cond_template, dim_info_dict):
bmm_problem_info = _get_strided_problem_info(func_attrs)
problem_args = bmm_common.PROBLEM_ARGS_TEMPLATE.render(mm_info=bmm_problem_info)
problem_args_cutlass_3x = bmm_common.PROBLEM_ARGS_TEMPLATE_CUT... |
.unit
def test_find_uncategorized_dataset_fields_missing_field() -> None:
test_resource = {'bar': ['4', '5']}
test_resource_dataset = _dataset.create_db_dataset('ds', test_resource)
existing_dataset = Dataset(name='ds', fides_key='ds', collections=[DatasetCollection(name='bar', fields=[DatasetField(name=4, ... |
def main(args=None):
if (args is None):
args = sys.argv[1:]
if (len(args) < 2):
print('usage: merge_woff_metadata.py METADATA.xml INPUT.woff [OUTPUT.woff]', file=sys.stderr)
return 1
metadata_file = args[0]
with open(metadata_file, 'rb') as f:
metadata = f.read()
infi... |
.parametrize(('input_data', 'expected_output'), [({'parameter': {'output': 0}}, '0'), ({'parameter': {'output': b64encode(b'').decode()}}, ''), ({'parameter': {'output': b64encode(b'foobar').decode()}}, 'foobar'), ({'parameter': {'output': 'no_b64'}}, 'decoding error: no_b64')])
def test_decode_output_values(input_data... |
class OptionSeriesColumnrangeSonificationDefaultinstrumentoptionsMappingLowpassFrequency(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(s... |
class TestScaffoldConnectionFailsWhenConnectionAlreadyExists():
def setup_class(cls):
cls.runner = CliRunner()
cls.agent_name = 'myagent'
cls.resource_name = 'myresource'
cls.cwd = os.getcwd()
cls.t = tempfile.mkdtemp()
dir_path = Path('packages')
tmp_dir = (c... |
def clone_to_tmp_dir(app):
tmp_dir = Path('tmp')
tmp_dir.mkdir(exist_ok=True)
tmp_dir = (tmp_dir / 'importer')
if tmp_dir.exists():
shutil.rmtree(str(tmp_dir), onerror=handle_retree_error_on_windows)
vcs = common.getvcs(app.RepoType, app.Repo, tmp_dir)
vcs.gotorevision(options.rev)
r... |
def extractWuxiaHeroes(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('Blood Hourglass' in item['title']):
return buildReleaseMessageWithType(item, 'Blood Hourglass', vol, chp... |
def decrypt_data(xref, cfunc, xref_args):
print(('%s: ' % hex(int(xref))), end='')
args = convert_args_to_long(xref_args)
if args:
try:
key = idaapi.get_many_bytes(args[2], (args[3] if (idc.Dword(args[3]) == ) else idc.Dword(args[3])))
data = idaapi.get_many_bytes(args[0], (a... |
class ModelDockerDeleter(ErsiliaBase):
def __init__(self, config_json=None):
ErsiliaBase.__init__(self, config_json=config_json, credentials_json=None)
def delete(self, model_id):
if is_inside_docker():
return
self.logger.info('Removing docker images and stopping containers r... |
def delete(item_id):
json_data = downloadUtils.download_url((('{server}/emby/Users/{userid}/Items/' + item_id) + '?format=json'))
item = json.loads(json_data)
item_id = item.get('Id')
item_name = item.get('Name', '')
series_name = item.get('SeriesName', '')
ep_number = item.get('IndexNumber', (-... |
class FragmentNode(template.Node):
def __init__(self, nodelist, request, identifier, mode='append'):
self.nodelist = nodelist
self.request_var = template.Variable(request)
self.identifier_var = template.Variable(identifier)
self.mode = mode
def render(self, context):
requ... |
def output_stats(out_stream: TextIO, name: str, run_id: str, metrics: Dict[(str, Any)], config: Dict[(str, Any)]):
for (pass_name, metric) in metrics.items():
logger.info(f'pass: {pass_name}')
for (metric_name, records) in metric.items():
total = 0
avg = 0
if reco... |
def test_recurse_check_structure_extrasubitem():
sample = dict(string='Foobar', list=['Foo', 'Bar'], dict={'foo': 'Bar'}, none=None, true=True, false=False)
to_check = dict(string='Foobar', list=['Foo', 'Bar', 'Bas'], dict={'foo': 'Bar', 'Bar': 'Foo'}, none=None, true=True, false=False)
with pytest.raises(V... |
.parametrize('filename', files_formats.keys())
def test_file_c_handle(testpath, filename):
any_xtgeo_file = xtgeo._XTGeoFile((testpath / filename))
handle_count = any_xtgeo_file._cfhandlecount
c_handle_1 = any_xtgeo_file.get_cfhandle()
assert ((handle_count + 1) == any_xtgeo_file._cfhandlecount)
c_h... |
def _gamestats():
fpage_account_limit = 4
recent_users = AccountDB.objects.get_recently_connected_accounts()
nplyrs_conn_recent = (len(recent_users) or 'none')
nplyrs = (AccountDB.objects.num_total_accounts() or 'none')
nplyrs_reg_recent = (len(AccountDB.objects.get_recently_created_accounts()) or '... |
def is_taxadb_up_to_date(dbfile=DEFAULT_TAXADB):
db = sqlite3.connect(dbfile)
try:
version = db.execute('SELECT version FROM stats;').fetchone()[0]
except (sqlite3.OperationalError, ValueError, IndexError, TypeError):
version = None
db.close()
return (version == DB_VERSION) |
def process_image(img, output, name, amount, space, cvd_approach, fit):
with Image.open(img) as im:
if ((im.format == 'PNG') and (name == 'opacity')):
if (im.mode not in ('RGBA',)):
im = im.convert('RGBA')
pixels = im.load()
start = time.perf_counter_ns()
... |
class Commen_Thread(QThread):
def __init__(self, action, *args):
super(QThread, self).__init__()
self.action = action
self.args = args
def run(self):
print('start_thread params:{}'.format(self.args))
if self.args:
print(self.args)
if (len(self.args... |
class OptionPlotoptionsColumnrangeSonificationContexttracksPointgrouping(Options):
def algorithm(self):
return self._config_get('minmax')
def algorithm(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: boo... |
class OverallTotals(models.Model):
id = models.AutoField(primary_key=True)
create_date = models.DateTimeField(auto_now_add=True, blank=True, null=True)
update_date = models.DateTimeField(auto_now=True, null=True)
fiscal_year = models.IntegerField(blank=True, null=True)
total_budget_authority = model... |
def tokenize_autotype(autotype):
while autotype:
opening_idx = (- 1)
for char in '{+^%~':
idx = autotype.find(char)
if ((idx != (- 1)) and ((opening_idx == (- 1)) or (idx < opening_idx))):
opening_idx = idx
if (opening_idx == (- 1)):
(yield... |
def remove_geojson_entry(zone_key: ZoneKey):
geo_json_path = (ROOT_PATH / 'web/geo/world.geojson')
with JsonFilePatcher(geo_json_path, indent=None) as f:
new_features = [f for f in f.content['features'] if (f['properties']['zoneName'] != zone_key)]
f.content['features'] = new_features
run_sh... |
class OptionSeriesVariablepieSonificationContexttracksMappingNoteduration(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 Command(BaseCommand):
help = 'Configures your project for deployment to the specified platform.'
def __init__(self):
self.suppressed_base_arguments.update(['--version', '-v', '--settings', '--pythonpath', '--traceback', '--no-color', '--force-color'])
self.requires_system_checks = []
... |
def extractReiWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if (item['tags'] != ['Tak Berkategori']):
return False
chp_prefixes = [('The villager Who Grew Up Dri... |
class Flashbots(Module):
signed_txs: List[HexBytes]
response: Union[(FlashbotsBundleResponse, FlashbotsPrivateTransactionResponse)]
def sign_bundle(self, bundled_transactions: List[Union[(FlashbotsBundleTx, FlashbotsBundleRawTx, FlashbotsBundleDictTx)]]) -> List[HexBytes]:
nonces: Dict[(HexStr, Nonc... |
class Asset(Task, CodeMixin):
__auto_name__ = False
__strictly_typed__ = True
__tablename__ = 'Assets'
__mapper_args__ = {'polymorphic_identity': 'Asset'}
asset_id = Column('id', Integer, ForeignKey('Tasks.id'), primary_key=True)
def __init__(self, code, **kwargs):
kwargs['code'] = code
... |
class OptionPlotoptionsLollipopDragdropGuideboxDefault(Options):
def className(self):
return self._config_get('highcharts-drag-box-default')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('rgba(0, 0, 0, 0.1)')
def color(... |
def extractReaderslistpodcastWordpressCom(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,... |
class RelationshipBuilder(object):
def __init__(self, versioning_manager, model, property_):
self.manager = versioning_manager
self.property = property_
self.model = model
def one_to_many_subquery(self, obj):
tx_column = option(obj, 'transaction_column_name')
remote_alias... |
class AttendeeViewSet(EventUserModelViewSet):
queryset = Attendee.objects.all()
serializer_class = AttendeeSerializer
filter_fields = ('event_user__event__event_slug', 'is_installing', 'email_confirmed', 'event__event_slug')
ordering_fields = ('created_at', 'updated_at', 'registration_date')
def get... |
def extractHktranslationsWordpressCom(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_... |
class SearchableSnapshotsStats(TelemetryDevice):
internal = False
serverless_status = serverless.Status.Blocked
command = 'searchable-snapshots-stats'
human_name = 'Searchable Snapshots Stats'
help = 'Regularly samples searchable snapshots stats'
def __init__(self, telemetry_params, clients, met... |
def add_images(qc_page, qc_dir, image_list, scene_file, wb_logging='WARNING', add_titles=False, title_formatter=None):
for image in image_list:
if add_titles:
if image.subject_title:
image_title = image.subject_title
if title_formatter:
image_t... |
class OptionSeriesErrorbarStatesInactive(Options):
def animation(self) -> 'OptionSeriesErrorbarStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesErrorbarStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
... |
def filter_firewall_central_snat_map_data(json):
option_list = ['comments', 'dst_addr', 'dst_addr6', 'dst_port', 'dstintf', 'nat', 'nat_ippool', 'nat_ippool6', 'nat_port', 'nat46', 'nat64', 'orig_addr', 'orig_addr6', 'orig_port', 'policyid', 'protocol', 'srcintf', 'status', 'type', 'uuid']
json = remove_invalid... |
class JsConsole():
def __init__(self, page: primitives.PageModel=None):
self.page = page
def debugger(self):
return JsObject.JsKeyword('debugger')
def clear(self):
return JsFncs.JsFunction('console.clear()')
def log(self, data: Union[(str, primitives.JsDataModel)], js_conv_func: ... |
def _safe_DIE_linkage_name(die, default=None):
if ('DW_AT_linkage_name' in die.attributes):
return bytes2str(die.attributes['DW_AT_linkage_name'].value)
elif ('DW_AT_name' in die.attributes):
return bytes2str(die.attributes['DW_AT_name'].value)
else:
return default |
def blms(x, d, N=4, L=4, mu=0.1):
nIters = (min(len(x), len(d)) // L)
u = np.zeros(((L + N) - 1))
w = np.zeros(N)
e = np.zeros((nIters * L))
for n in range(nIters):
u[:(- L)] = u[L:]
u[(- L):] = x[(n * L):((n + 1) * L)]
d_n = d[(n * L):((n + 1) * L)]
A = hankel(u[:L],... |
(((memory_usage is None) or (MAGICK_VERSION_INFO <= (6, 6, 9, 7))), reason='memory_usage is unavailable, or untestable')
def test_memory_leak():
'
minimum = 1.0
with Color('NONE') as nil_color:
minimum = ctypes.sizeof(nil_color.raw)
consumes = memory_usage((color_memory_leak, (), {}))
assert... |
class _ASPPModule(nn.Module):
def __init__(self, inplanes, planes, kernel_size, padding, dilation, BatchNorm):
super(_ASPPModule, self).__init__()
self.atrous_conv = nn.Conv2d(inplanes, planes, kernel_size=kernel_size, stride=1, padding=padding, dilation=dilation, bias=False)
self.bn = Batch... |
class Errors(commands.Cog):
def __init__(self, bot):
self.bot = bot
.listener()
async def on_command_error(self, inter, error):
if isinstance(error, commands.NotOwner):
(await inter.send(self.bot.response.get('not-owner', guild_id=inter.guild.id)))
elif isinstance(error, ... |
class CursorProxy(wrapt.ObjectProxy):
provider_name = None
DML_QUERIES = ('INSERT', 'DELETE', 'UPDATE')
def __init__(self, wrapped, destination_info=None) -> None:
super(CursorProxy, self).__init__(wrapped)
self._self_destination_info = (destination_info or {})
def callproc(self, procnam... |
class OptionSeriesColumnrangeSonificationContexttracksMappingPitch(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('y')
def mapTo(self, text: str):
... |
.EventDecorator()
def find_sub_block(iset, ises, comm):
found = []
target_indices = iset.indices
candidates = OrderedDict(enumerate(ises))
with temp_internal_comm(comm) as icomm:
while True:
match = False
for (i, candidate) in list(candidates.items()):
can... |
class DIN99o(Lab):
BASE = 'xyz-d65'
NAME = 'din99o'
SERIALIZE = ('--din99o',)
WHITE = WHITES['2deg']['D65']
CHANNELS = (Channel('l', 0.0, 100.0), Channel('a', (- 55.0), 55.0, flags=FLG_MIRROR_PERCENT), Channel('b', (- 55.0), 55.0, flags=FLG_MIRROR_PERCENT))
def to_base(self, coords: Vector) -> V... |
def test_hamming_weight_model_raises_exception_when_given_non_bytes_array():
vm = scared.HammingWeight()
with pytest.raises(TypeError):
vm(1)
with pytest.raises(TypeError):
vm('barr')
with pytest.raises(ValueError):
vm(np.array(['foo', 'barr']))
with pytest.raises(ValueError)... |
def train(node_id, dataset_provider: Callable[([], tf.data.Dataset)], epochs=sys.maxsize):
model = tf.keras.Sequential([PrintLayer(node_id)])
loss = tf.keras.losses.MeanSquaredError()
model.compile(loss=loss)
try:
model.fit(dataset_provider(), epochs=epochs, verbose=2)
except Exception as e:... |
.slow
.skipif((not has_hf_transformers), reason='requires huggingface transformers')
.skipif((not has_torch_compile), reason='requires torch.compile')
.parametrize('torch_device', TORCH_DEVICES)
.parametrize('model', LLAMA_TEST_MODELS)
.parametrize('with_torch_sdp', [False, True])
def test_causal_lm_torch_compile(torch... |
def hash_fiat_element(element):
restriction = None
e = element
if isinstance(e, FIAT.DiscontinuousElement):
e = e._element
if isinstance(e, FIAT.RestrictedElement):
restriction = tuple(e._indices)
e = e._element
if (len(restriction) == e.space_dimension()):
re... |
class AIFlowRpcServerException(AIFlowException):
def __init__(self, error_msg, error_code=INTERNAL_ERROR, **kwargs):
try:
self.error_code = error_code
except (ValueError, TypeError):
self.error_code = INTERNAL_ERROR
self.error_msg = error_msg
self.json_kwargs ... |
class JavaUnitTest(object):
def __init__(self, java_class, file_name=None, test_class_name=None):
self.java_class = java_class
if (file_name is None):
self.data_file_name = 'of{version}/{name}.data'.format(version=java_class.version.dotless_version, name=java_class.c_name[3:])
el... |
('new')
('--plugin', '-p', type=click.STRING, help='Adds a new language to a plugin.')
('lang')
def new_translation(lang, plugin):
if plugin:
validate_plugin(plugin)
click.secho('[+] Adding new language {} for plugin {}...'.format(lang, plugin), fg='cyan')
add_plugin_translations(plugin, lan... |
def main():
module_spec = schema_to_module_spec(versioned_schema)
mkeyname = 'name'
fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path':... |
def _kl_div(reference_data: pd.Series, current_data: pd.Series, feature_type: ColumnType, threshold: float, n_bins: int=30) -> Tuple[(float, bool)]:
(reference_percents, current_percents) = get_binned_data(reference_data, current_data, feature_type, n_bins)
kl_div_value = stats.entropy(reference_percents, curre... |
def test_consent_request(db):
provided_identity_data = {'privacy_request_id': None, 'field_name': 'email', 'encrypted_value': {'value': ''}}
provided_identity = ProvidedIdentity.create(db, data=provided_identity_data)
consent_request_1 = {'provided_identity_id': provided_identity.id}
consent_1 = Consent... |
def test_collect_analysis_tags(backend_db, frontend_db):
tags1 = {'tag_a': {'color': 'success', 'value': 'tag a', 'propagate': True}, 'tag_b': {'color': 'warning', 'value': 'tag b', 'propagate': False}}
tags2 = {'tag_c': {'color': 'success', 'value': 'tag c', 'propagate': True}}
insert_test_fo(backend_db, '... |
('ecs_deploy.cli.get_client')
def test_update_task_exclusive_docker_labels(get_client, runner):
get_client.return_value = EcsTestClient('acces_key', 'secret_key')
result = runner.invoke(cli.update, (TASK_DEFINITION_ARN_1, '-d', 'webserver', 'new-label', 'new-value', '--exclusive-docker-labels'))
assert (res... |
class GTIN(models.Model):
class Meta():
verbose_name = 'Global Trade Item Number'
ampp = models.ForeignKey(db_column='appid', to='AMPP', on_delete=models.CASCADE, help_text='AMPP')
gtin = models.BigIntegerField(help_text='GTIN')
startdt = models.DateField(help_text='GTIN date')
enddt = model... |
()
('--duration', default=3, help='Run time in seconds.')
('--runtime_mode', default='async', help='Runtime mode: async or threaded.')
_of_runs_deco
_format_deco
def main(duration: int, runtime_mode: str, number_of_runs: int, output_format: str) -> Any:
parameters = {'Duration(seconds)': duration, 'Runtime mode': r... |
class EvpnNLRI(StringifyMixin, TypeDisp):
ROUTE_FAMILY = RF_L2_EVPN
_PACK_STR = '!BB'
_PACK_STR_SIZE = struct.calcsize(_PACK_STR)
ETHERNET_AUTO_DISCOVERY = 1
MAC_IP_ADVERTISEMENT = 2
INCLUSIVE_MULTICAST_ETHERNET_TAG = 3
ETHERNET_SEGMENT = 4
IP_PREFIX_ROUTE = 5
ROUTE_TYPE_NAME = None
... |
class OptionSeriesBellcurveSonificationTracksMappingPitch(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('y')
def mapTo(self, text: str):
self._c... |
def test_Market():
pf = build_portfolio(names=names_yf, pf_allocation=pf_allocation, start_date=start_date, end_date=end_date, data_api='yfinance', market_index='^GSPC')
assert isinstance(pf.market_index, Market)
assert (pf.market_index.name == '^GSPC')
assert (pf.beta is not None)
assert (pf.rsquar... |
def filter_firewall_vipgrp6_data(json):
option_list = ['color', 'comments', 'member', 'name', 'uuid']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)):
dictionary[attribute] = json[attribute]
... |
class CookieSessionPipe(SessionPipe):
def __init__(self, key, expire=3600, secure=False, samesite='Lax', domain=None, cookie_name=None, cookie_data=None, encryption_mode='modern', compression_level=0):
super().__init__(expire=expire, secure=secure, samesite=samesite, domain=domain, cookie_name=cookie_name, ... |
class PayrollManager(BaseManager):
def __init__(self, name, credentials, unit_price_4dps=False, user_agent=None):
from xero import __version__ as VERSION
self.credentials = credentials
self.name = name
self.base_url = (credentials.base_url + XERO_PAYROLL_URL)
self.extra_param... |
class OptionSeriesPyramid3dSonificationTracksMappingPlaydelay(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 extractSugoitranslationsWordpressCom(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, ... |
class MultiScaleImageFeatureExtractor(nn.Module):
def __init__(self, modelname: str='dino_vits16', freeze: bool=False, scale_factors: list=[1, (1 / 2), (1 / 3)]):
super().__init__()
self.freeze = freeze
self.scale_factors = scale_factors
if ('res' in modelname):
self._net... |
def split_item(item: Item, max_token_count: int) -> list[Item]:
if ((not item.content) or (len(str(item.content)) <= max_token_count)):
return [item]
else:
return [Item(content=Content(str(chunk)), author=item.author, created_at=CreatedAt(item.created_at), domain=Domain(item.domain), url=Url(ite... |
class Interaction(ABC):
def set_feature(self, feature: str, new_data: Any, indices: Any):
pass
def reset_feature(self, feature: str):
pass
def link(self, event_type: str, target: Any, feature: str, new_data: Any, callback: callable=None, bidirectional: bool=False):
if (event_type in ... |
('snakes.nets', depends=['snakes.plugins.labels'])
def extend(module):
class Transition(module.Transition):
def __init__(self, name, guard=None, **options):
mod = set(iterate(options.pop('modules', [])))
module.Transition.__init__(self, name, guard, **options)
self.module... |
class Distro(Base):
__tablename__ = 'distros'
name = sa.Column(sa.String(200), primary_key=True)
def __init__(self, name):
self.name = name
def __json__(self):
return dict(name=self.name)
def by_name(cls, session, name):
query = session.query(cls).filter((sa.func.lower(cls.na... |
class OptionSeriesBubbleDatalabelsTextpath(Options):
def attributes(self):
return self._config_get(None)
def attributes(self, value: Any):
self._config(value, js_type=False)
def enabled(self):
return self._config_get(False)
def enabled(self, flag: bool):
self._config(flag... |
class Z3Converter(BaseConverter):
def __init__(self):
self._context = Context()
def context(self) -> Context:
return self._context
def negate(self, expr: BoolRef) -> BoolRef:
return Not(expr)
def _convert_variable(self, variable: Variable, **kwargs) -> BitVecRef:
return B... |
class PublicCountryISOCodeSensor(BaseSensor):
name = 'publiccountryiso'
desc = _('Display your public country ISO code')
command = 'curl ifconfig.co/country-iso'
current_country_iso = ''
lasttime = 0
def get_value(self, sensor):
if ((self.current_country_iso == '') or (self.lasttime == 0... |
def exit_process(is_error=True, delayed=False):
from threading import Thread
import _thread
status = (1 if is_error else 0)
Thread(target=(lambda : (time.sleep(3), _thread.interrupt_main())), daemon=True).start()
Thread(target=(lambda : (time.sleep(6), os._exit(status))), daemon=True).start()
if... |
class OptionSeriesVennSonificationContexttracksMappingLowpassFrequency(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 StackableSettings(Settings):
absolute_params = {'angle': 60}
relative_params = {'height': 2.0, 'width': 4.0, 'holedistance': 1.0, 'bottom_stabilizers': 0.0}
def checkValues(self) -> None:
if (self.angle < 20):
raise ValueError("StackableSettings: 'angle' is too small. Use value >= ... |
class FrameStacker():
def __init__(self, num_frames: int):
self._num_frames = num_frames
self.reset()
def num_frames(self) -> int:
return self._num_frames
def reset(self):
self._stack = collections.deque(maxlen=self._num_frames)
def step(self, frame: np.ndarray) -> np.nda... |
.parametrize('box_size,log_level', [((1, 0.1, 0.1), 'WARNING'), ((0.1, 1, 0.1), 'WARNING'), ((0.1, 0.1, 1), 'WARNING')])
def test_sim_structure_extent(log_capture, box_size, log_level):
box = td.Structure(geometry=td.Box(size=box_size), medium=td.Medium(permittivity=2))
_ = td.HeatSimulation(size=(1, 1, 1), str... |
()
('paths', nargs=(- 1), type=click.Path(path_type=Path))
_command
def check(paths: List[Path]) -> int:
if (not paths):
raise click.ClickException('Provide some filenames')
return_code = 0
for result in usort_path(paths, write=False):
if result.error:
click.echo(f'Error sorting ... |
class InvoiceTest(QuickbooksTestCase):
def create_invoice(self, customer, request_id=None):
invoice = Invoice()
line = SalesItemLine()
line.LineNum = 1
line.Description = 'description'
line.Amount = 100
line.SalesItemLineDetail = SalesItemLineDetail()
item = I... |
def extractSolairemtlWordpressCom(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... |
.slow
def test_on_init(hound, repo, cve):
fixes = hound.get_rule_fixes(cve)
detect = False
if ((fixes == 'v2.6.12-rc2') or (fixes == '1da177e4c3f41524e886b7f1b8a0c1fc7321cac2')):
detect = True
repo.git.checkout('--force', 'v2.6.12-rc2')
try:
if detect:
assert hound.check_... |
class AnalysisPlugin(YaraBasePlugin):
NAME = 'software_components'
DESCRIPTION = 'identify software components'
MIME_BLACKLIST = MIME_BLACKLIST_NON_EXECUTABLE
VERSION = '0.4.2'
FILE = __file__
def process_object(self, file_object):
file_object = super().process_object(file_object)
... |
def graphs_test1():
cfg = ControlFlowGraph()
cfg.add_nodes_from((vertices := [BasicBlock(0, [Assignment(ListOperation([]), Call(imp_function_symbol('__x86.get_pc_thunk.bx'), [], Pointer(CustomType('void', 0), 32), 1))]), BasicBlock(1, [Phi(Variable('var_10', Integer(32, True), 2, False), [Constant(0, Integer(32... |
class TestGetSpecificSystemUserManages():
(scope='function')
def url(self, viewer_user, system) -> str:
return (V1_URL_PREFIX + f'/user/{viewer_user.id}/system-manager/{system.fides_key}')
def test_get_system_managed_by_user_not_authenticated(self, api_client: TestClient, url: str) -> None:
... |
class get_config_reply(message):
version = 6
type = 8
def __init__(self, xid=None, flags=None, miss_send_len=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (flags != None):
self.flags = flags
else:
self.flags =... |
class AbstractAgencyViewSet(AbstractSpendingByCategoryViewSet, metaclass=ABCMeta):
agency_type: AgencyType
def build_elasticsearch_result(self, response: dict) -> List[dict]:
agency_info_buckets = response.get('group_by_agg_key', {}).get('buckets', [])
code_list = [bucket.get('key') for bucket i... |
class StopOrNot(Struct):
CONST_SIZE = 21
def __init__(self, stop: bool):
super(StopOrNot, self).__init__('ospf.data.StopOrNot', (('stop_specific_1', 'I'), ('from_id_rev', '4s'), ('to_id_rev', '4s'), ('seq_number_rev', 'I'), ('stop_specific_2', '5s')))
self.header = None
self.as_dict = {'... |
def test_dt_output_shape(dummy_feats_and_labels, dummy_titanic):
(feats, labels) = dummy_feats_and_labels
dt = DecisionTree()
dt.fit(feats, labels)
pred = dt.predict(feats)
assert (pred.shape == (feats.shape[0],)), 'DecisionTree output should be same as training labels.'
(X_train, y_train, X_tes... |
def train(batch_size, model_path=None):
data_module = DepthCovDataModule(batch_size)
if (model_path is None):
model = NonstationaryGpModule()
else:
model = NonstationaryGpModule.load_from_checkpoint(model_path)
checkpoint_callback = ModelCheckpoint(monitor='loss_val', dirpath='./models/'... |
class SubBackendJITCython(SubBackendJIT):
def make_new_header(self, func, arg_types):
header = HeaderFunction(name=func.__name__, arguments=list(inspect.signature(func).parameters.keys()), imports='import cython\n\nimport numpy as np\ncimport numpy as np\n')
signatures = make_signatures_from_typehin... |
class OptionSeriesTreegraphSonificationContexttracksMappingLowpassResonance(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: st... |
def send_single_erasure_email(db: Session, subject_email: str, subject_name: str, batch_identities: List[str], test_mode: bool=False) -> None:
org_name = get_org_name(db)
dispatch_message(db=db, action_type=MessagingActionType.MESSAGE_ERASURE_REQUEST_FULFILLMENT, to_identity=Identity(email=subject_email), servi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.