code stringlengths 281 23.7M |
|---|
(IDataWrapper)
class DataWrapper(MDataWrapper):
toolkit_data = Instance(DataObjectComposite, args=(), allow_none=False)
def mimetypes(self):
return {wx_format.GetId() for wx_format in self.toolkit_data.GetAllFormats()}
def get_mimedata(self, mimetype):
wx_format = DataFormat(mimetype)
... |
class UserMessages(mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
queryset = UserMessage.objects.all()
serializer_class = UserMessageSerializer
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
authentication_classes = [JSONWebTokenAuthenticat... |
class Lights():
LIGHTS_N = 3
def __init__(self):
self.basis = (([0] * 3) * self.LIGHTS_N)
self.basis[0] = 2
self.basis[3] = 1
self.basis[4] = 1
self.basis[7] = 2
self.colors = (([0] * 3) * self.LIGHTS_N)
self.dev = LED_COLOR(num_led=self.LIGHTS_N)
... |
class VegaEmbedded():
def __init__(self, ui):
self.page = ui.page
self.chartFamily = 'Vega'
def plot(self, record=None, y=None, x=None, kind='line', profile=None, width=(100, '%'), height=(330, 'px'), options=None, html_code=None):
line_chart = graph.GraphVega.VegaEmdedCharts(self.page, ... |
class IAMGateway(AWSGateway):
def __init__(self, region: str, access_key_id: Optional[str]=None, access_key_data: Optional[str]=None, config: Optional[Dict[(str, Any)]]=None) -> None:
super().__init__(region, access_key_id, access_key_data, config)
self.client = boto3.client('iam', region_name=self.... |
.parametrize('argset', primal_subj_argsets())
def test_replace_subject_primal(primal_form, argset):
new_subj = argset.new_subj
idxs = argset.idxs
error = argset.error
if (error is None):
old_subj = primal_form.form.coefficients()[0]
new_form = primal_form.label_map((lambda t: t.has_label... |
class OptionPlotoptionsAreasplinerangeSonificationDefaultinstrumentoptionsMappingPitch(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... |
class SeqMotifFace(Face):
def __init__(self, seq=None, motifs=None, seqtype='aa', gap_format='line', seq_format='[]', width=None, height=None, fgcolor='black', bgcolor='#bcc3d0', gapcolor='gray', gap_linewidth=0.2, max_fsize=12, ftype='sans-serif', padding_x=0, padding_y=0):
if ((not motifs) and (not seq)):... |
def tex_ComplexZeroMultiplicity(head, args, **kwargs):
assert (len(args) == 2)
assert (args[1].head() == For)
(f, forarg) = args
(var, point) = forarg.args()
f = f.latex(**kwargs)
var = var.latex(**kwargs)
point = point.latex(**kwargs)
return ('\\mathop{\\operatorname{ord}}\\limits_{%s=%... |
class PDU(univ.Sequence):
componentType = namedtype.NamedTypes(namedtype.NamedType('request-id', rfc1902.Integer32()), namedtype.NamedType('error-status', errorStatus), namedtype.NamedType('error-index', univ.Integer().subtype(subtypeSpec=constraint.ValueRangeConstraint(0, max_bindings))), namedtype.NamedType('vari... |
def change():
global mb, data, data_id
_mybuddy = mb
print(_mybuddy)
for m in range(1, 3):
for i in range(1, 7):
for j in range(len(data_id)):
_mybuddy.set_servo_data(m, i, data_id[j], data[j])
time.sleep(0.1)
_data = _mybuddy.get_servo... |
(Live)
class LiveAdmin(admin.ModelAdmin):
list_display = ('number', 'title', 'get_guest', 'like', 'unlike', 'like_frequence')
search_fields = ('title', 'guest__first_name')
def get_guest(self, obj):
if obj.guest:
return obj.guest.get_full_name()
get_guest.short_description = 'Convida... |
class bsn_gentable_error(bsn_base_error):
version = 6
type = 1
err_type = 65535
subtype = 2
experimenter = 6035143
def __init__(self, xid=None, error_code=None, table_id=None, err_msg=None, data=None):
if (xid != None):
self.xid = xid
else:
self.xid = None... |
class NotificationSerializerGet(serializers.ModelSerializer):
from_user = serializers.SerializerMethodField('_get_from_user')
to_user = serializers.SerializerMethodField('_get_to_user')
dataset = serializers.SerializerMethodField('_get_dataset')
ml_model = serializers.SerializerMethodField('_get_ml_mode... |
class TestDateField(FieldValues):
valid_inputs = {'2001-01-01': datetime.date(2001, 1, 1), datetime.date(2001, 1, 1): datetime.date(2001, 1, 1)}
invalid_inputs = {'abc': ['Date has wrong format. Use one of these formats instead: YYYY-MM-DD.'], '2001-99-99': ['Date has wrong format. Use one of these formats inst... |
class TupleDecoder(BaseDecoder):
decoders = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.decoders = tuple(((HeadTailDecoder(tail_decoder=d) if getattr(d, 'is_dynamic', False) else d) for d in self.decoders))
self.is_dynamic = any((getattr(d, 'is_dynamic', False) for... |
class ProductionMix(Mix):
_corrected_negative_values: set = PrivateAttr(set())
biomass: (float | None) = None
coal: (float | None) = None
gas: (float | None) = None
geothermal: (float | None) = None
hydro: (float | None) = None
nuclear: (float | None) = None
oil: (float | None) = None
... |
def test_deferred_message_build_regular(mocker: Any) -> None:
message = DeferredMessage(MyMessage, 'unittest_args', kwargs_field='unittest_kwargs')
built = message.build_message()
assert (not hasattr(message, '_args'))
assert (not hasattr(message, '_kwargs'))
assert isinstance(built, MyMessage)
... |
def _build_model_operator(is_stream: bool=False, dag_name: str='llm_model_dag') -> BaseOperator:
from dbgpt.model.cluster import WorkerManagerFactory
from dbgpt.core.awel import JoinOperator
from dbgpt.model.operator.model_operator import ModelCacheBranchOperator, CachedModelStreamOperator, CachedModelOpera... |
def test_complex_example():
ubq = UpdateByQuery()
ubq = ubq.query('match', title='python').query((~ Q('match', title='ruby'))).filter((Q('term', category='meetup') | Q('term', category='conference'))).script(source='ctx._source.likes += params.f', lang='painless', params={'f': 3})
ubq.query.minimum_should_m... |
_or_str('.json')
def wavefunction_from_json(text):
data = json.loads(text)
mol = data['Molecule']
charge = mol['Charge']
mult = mol['Multiplicity']
atoms = list()
coords = list()
for atom in mol['Atoms']:
atom_label = atom['ElementLabel']
atom_coords = atom['Coords']
... |
def lazy_import():
from fastly.model.logging_common_response import LoggingCommonResponse
from fastly.model.logging_loggly_additional import LoggingLogglyAdditional
from fastly.model.service_id_and_version_string import ServiceIdAndVersionString
from fastly.model.timestamps import Timestamps
globals... |
('/telemetry/accept_telemetry_consent', methods=['POST'])
def accept_telemetry_consent():
with session_scope() as session:
try:
telemetry_user = get_telemetry_user(session)
data = request.get_json()
if (('consent' in data) and isinstance(data['consent'], bool) and data.ge... |
class OBJECT_OT_RemoveNamespace(bpy.types.Operator):
bl_idname = 'mixamo.remove_namespace'
bl_label = ''
bl_description = 'Removes all namespaces of selection (for single Convert)'
def execute(self, context):
mixamo = context.scene.mixamo
if (not bpy.context.object):
self.rep... |
class CommonSubexpressionElimination(PipelineStage):
name = 'common-subexpression-elimination'
options = {'threshold': 'The amount of occurrences a expression must reach to be eliminated.', 'intra': 'When set to yes, also search for duplicates in the same instruction.', 'string_threshold': 'The amount of occurr... |
class OptionPlotoptionsLineSonification(Options):
def contextTracks(self) -> 'OptionPlotoptionsLineSonificationContexttracks':
return self._config_sub_data('contextTracks', OptionPlotoptionsLineSonificationContexttracks)
def defaultInstrumentOptions(self) -> 'OptionPlotoptionsLineSonificationDefaultinst... |
class BaseBlockHeadersValidator(ValidatorAPI[Tuple[(BlockHeaderAPI, ...)]]):
block_number_or_hash: BlockIdentifier
max_headers: int
skip: int
reverse: bool
def __init__(self, block_number_or_hash: BlockIdentifier, max_headers: int, skip: int, reverse: bool) -> None:
self.block_number_or_hash... |
class OptionSeriesColumnpyramidStatesInactive(Options):
def animation(self) -> 'OptionSeriesColumnpyramidStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesColumnpyramidStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, fl... |
class TraitTypesTest(unittest.TestCase):
def test_traits_shared_transient(self):
class LazyProperty(TraitType):
default_value_type = DefaultValue.constant
def get(self, obj, name):
return 1729
self.assertFalse(Float().transient)
LazyProperty().as_ctrai... |
class OptionSeriesParetoSonificationContexttracksMappingTime(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):
sel... |
def fetch_production(zone_key: str='US-HI-OA', session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> dict:
r = (session or Session())
if (target_datetime is None):
request_dt = arrow.now('Pacific/Honolulu')
res = r.get((BASE_URL + 'limit=... |
class CallShotMode(BaseMode):
name = Mode.call_shot
keymap = {Action.quit: False, Action.call_shot: True, Action.next: False}
def __init__(self):
super().__init__()
self.head_raise = 0
self.trans_ball = None
self.ball_highlight = None
self.picking = None
def enter... |
class Cutting2DCoreEnvironment(CoreEnv):
def __init__(self, max_pieces_in_inventory: int, raw_piece_size: (int, int), static_demand: (int, int), reward_aggregator: RewardAggregatorInterface):
super().__init__()
self.max_pieces_in_inventory = max_pieces_in_inventory
self.raw_piece_size = tupl... |
def test_operations_with_constants_with_combinations():
v = [(- 256), (- 64), (- 16), (- 4.75), (- 3.75), (- 3.25), (- 1), (- 0.75), (- 0.125), 0.0, 0.125, 0.75, 1, 1.5, 3.75, 4.0, 8.0, 32, 128]
for i in range(len(v)):
for j in range(len(v)):
(vx, vy) = (v[i], v[j])
x = Fxp(vx, T... |
def extractRestingbitchfacetranslationsBlogspotCom(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 (tagna... |
def get_group_features(dp, waiters, to_user=True):
ofp = dp.ofproto
type_convert = {ofp.OFPGT_ALL: 'ALL', ofp.OFPGT_SELECT: 'SELECT', ofp.OFPGT_INDIRECT: 'INDIRECT', ofp.OFPGT_FF: 'FF'}
cap_convert = {ofp.OFPGFC_SELECT_WEIGHT: 'SELECT_WEIGHT', ofp.OFPGFC_SELECT_LIVENESS: 'SELECT_LIVENESS', ofp.OFPGFC_CHAINI... |
def test_gzip_not_in_accept_encoding(test_client_factory):
def homepage(request):
return PlainTextResponse(('x' * 4000), status_code=200)
app = Starlette(routes=[Route('/', endpoint=homepage)], middleware=[Middleware(GZipMiddleware)])
client = test_client_factory(app)
response = client.get('/', ... |
.parametrize('elasticapm_client', [{'collect_local_variables': 'errors'}, {'collect_local_variables': 'transactions'}, {'collect_local_variables': 'all'}, {'collect_local_variables': 'something'}], indirect=True)
def test_collect_local_variables_errors(elasticapm_client):
mode = elasticapm_client.config.collect_loc... |
class OptionSeriesPyramidSonificationContexttracksMappingTime(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 test_setup_ensemble_smoother(poly_case, storage):
args = Namespace(realizations='0-4,7,8', current_case='default', target_case='test_case')
model = model_factory._setup_ensemble_smoother(poly_case, storage, args, UUID(int=0), MagicMock())
assert isinstance(model, EnsembleSmoother)
assert (model.simu... |
def extractDandanmeintranslationsWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Feng Mang', 'Feng Mang', 'translated'), ('Blood Contract', 'Blood Contract', 'tran... |
.skip_missing_tokenizer()
('llama_recipes.finetuning.train')
('llama_recipes.finetuning.LlamaTokenizer')
('llama_recipes.finetuning.LlamaForCausalLM.from_pretrained')
('llama_recipes.finetuning.optim.AdamW')
('llama_recipes.finetuning.StepLR')
def test_custom_dataset(step_lr, optimizer, get_model, tokenizer, train, moc... |
class TLSHandler(TLSCipherSuiteChecker):
def __init__(self, host, port):
super().__init__(host)
self.target = host.target
self.port = port
self._versions = ('tls1', 'tls1_1', 'tls1_2')
self._base_script = '{} 10 openssl s_client -connect {}:{} '.format(TIMEOUT, self.target, s... |
def request_pzem4_device(sport, saddress, ttimeout=3):
global pzem_devices
sport = str(sport)
try:
saddress = int(saddress)
except:
saddress = 1
for i in range(len(pzem_devices)):
try:
if ((str(pzem_devices[i].port) == sport) and (int(pzem_devices[i].address) == s... |
def test_broadcast_const(some_thr, dtype_to_broadcast):
dtype = dtypes.align(dtype_to_broadcast)
const = get_test_array(1, dtype)[0]
output_ref = numpy.empty((1000,), dtype)
output_ref[:] = const
output_dev = some_thr.empty_like(output_ref)
test = get_test_computation(output_dev)
bc = tr.bro... |
class TestHandleActivityTaskEvents(TestCase):
def setUp(self) -> None:
self.decider: ReplayDecider = Mock()
self.decider.handle_activity_task_closed = MagicMock(return_value=True)
self.context = DecisionContext(decider=self.decider)
self.future: Future = Future()
self.context... |
def _create_and_process_transaction(configuration: Configuration, row_values: List[Any], current_table_type: EntrySetType, internal_id: int, artificial_internal_id: int, unfiltered_transaction_sets: Dict[(EntrySetType, TransactionSet)], artificial_transaction_list: List[AbstractTransaction]) -> None:
transaction: A... |
def vacuum_tables():
table_names = ['submission_attributes', 'appropriation_account_balances', 'financial_accounts_by_program_activity_object_class', 'financial_accounts_by_awards']
for table_name in table_names:
with OneLineTimer(f'Vacuum {table_name}') as t:
execute_dml_sql(f'vacuum (full,... |
def test_merge_apis_duplicate_apis():
required_apis = [{'api': 'API1', 'reason': 'Reason 1'}, {'api': 'API2', 'reason': 'Reason 2'}, {'api': 'API1', 'reason': 'Reason 3'}, {'api': 'API2', 'reason': 'Reason 4'}]
expected_output = [{'api': 'API1', 'reason': 'Reason 1 Reason 3'}, {'api': 'API2', 'reason': 'Reason ... |
class KademliaRoutingTable():
def __init__(self, center_node_id: NodeID, bucket_size: int) -> None:
self.logger = get_logger('p2p.kademlia.KademliaRoutingTable')
self.center_node_id = center_node_id
self.bucket_size = bucket_size
self.buckets: Tuple[(Deque[NodeID], ...)] = tuple((col... |
class SyncWebsocketDuplexer():
def __init__(self, uri: str, health_check_uri: str, cert: Union[(str, bytes, None)], token: Optional[str]) -> None:
self._uri = uri
self._hc_uri = health_check_uri
self._token = token
self._extra_headers = Headers()
if (token is not None):
... |
def on_ui_tabs():
with gr.Blocks() as batchlinks:
with gr.Row():
with gr.Column(scale=2):
introduction = gr.Markdown(introductiontext)
with gr.Column(scale=1):
with gr.Row():
uistretcher = gr.Checkbox(value=False, label='Stretch UI'... |
def validate_allowed_fields(file_name, section, config, allowed_fields):
for field in config.options(section):
if (not allowed_fields.get(field)):
raise Exception(("manifest file %s section '%s' contains unknown field '%s'" % (file_name, section, field)))
for field in allowed_fields:
... |
class Shortener(BaseShortener):
api_url = '
def short(self, url):
url = self.clean_url(url)
shorten_url = f'{self.api_url}shorten'
response = self._get(shorten_url, params={'url': url})
if (not response.ok):
raise ShorteningErrorException(response.content)
ret... |
class flash_attention(Operator):
def __init__(self, batch_size, dropout, max_seq_len, causal) -> None:
super().__init__()
assert (dropout == 0)
self._attrs['op'] = 'flash_attention'
self._attrs['has_profiler'] = False
self._attrs['batch_size'] = batch_size
self._attrs... |
class SpanFinder(TrainablePipe):
def __init__(self, nlp: Language, model: Model[(Iterable[Doc], Floats2d)], name: str='span_finder', *, threshold: float=0.5, max_length: int=0, min_length: int=0, scorer: Optional[Callable]=partial(span_finder_score, predicted_key=DEFAULT_PREDICTED_KEY, training_key=DEFAULT_TRAINING... |
def main():
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'}, 'json_generic': {'required': False, 'type': 'dict', 'default': None, 'options': {'dictbody': {... |
def extractOmnicorporationWordpressCom(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 parse_save(filename) -> Dict[(str, Any)]:
logger.info(f'Reading save file {filename}.')
start = time.time()
parsed = rust_parser.parse_save_file(str(filename.absolute()))
if (not isinstance(parsed, dict)):
raise ValueError(f'Could not parse {filename}')
dt = (time.time() - start)
log... |
class PanToolTestCase(EnableTestAssistant, unittest.TestCase):
def test_restrict_to_data_with_empty_source(self):
plot_data = ArrayPlotData()
plot = Plot(plot_data)
arr = np.arange(4.0)
plot_data.set_data('x', arr)
plot_data.set_data('y', arr)
plot_data.set_data('z', ... |
class RealGitHubEndpoint(ghstack.github.GitHubEndpoint):
graphql_endpoint: str = '
rest_endpoint: str = '
www_endpoint: str = '
oauth_token: Optional[str]
proxy: Optional[str]
verify: Optional[str]
cert: Optional[Union[(str, Tuple[(str, str)])]]
def __init__(self, oauth_token: Optional[s... |
def _build_storage_service(config: Dict[(str, Any)]) -> StorageService:
config_dependency: Optional[Dict[(str, Any)]] = config.get('dependency')
if ((not config_dependency) or ('StorageService' not in config_dependency)):
raise KeyError('StorageService is absent in the config.')
storage_svc_config: ... |
class OptionPlotoptionsHeatmapSonificationDefaultspeechoptionsMappingPlaydelay(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 OptionSonificationGlobaltracksActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num: float):
self._... |
class OFPBucketCounter(StringifyMixin):
def __init__(self, packet_count, byte_count):
super(OFPBucketCounter, self).__init__()
self.packet_count = packet_count
self.byte_count = byte_count
def parser(cls, buf, offset):
(packet, byte) = struct.unpack_from(ofproto.OFP_BUCKET_COUNTE... |
def filter_firewall_internet_service_owner_data(json):
option_list = ['id', 'name']
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]
return dictiona... |
def get_content(paper):
title = paper['title']
summary = paper['summary']
summary = summary.replace('\n', ' ').replace(',', ' ').rstrip('\r\n')
title = title.replace('\n', ' ').replace(',', ' ').rstrip('\r\n')
url = paper['arxiv_url']
content = ((title + ',') + summary)
return content |
class TracingTestSampling(AmbassadorTest):
def init(self):
self.target = HTTP()
self.zipkin = Zipkin()
def config(self) -> Generator[(Union[(str, Tuple[(Node, str)])], None, None)]:
(yield (self.target, self.format('\n---\napiVersion: getambassador.io/v3alpha1\nkind: Mapping\nname: trac... |
class TestAffiliationAddressTeiTrainingDataGenerator():
def test_should_include_layout_document_text_in_tei_output(self):
training_data_generator = get_tei_training_data_generator()
layout_document = LayoutDocument.for_blocks([LayoutBlock.for_text(TEXT_1)])
xml_root = training_data_generator... |
def test_capture_serverless_sns(event_sns, context, elasticapm_client):
os.environ['AWS_LAMBDA_FUNCTION_NAME'] = 'test_func'
_serverless
def test_func(event, context):
with capture_span('test_span'):
time.sleep(0.01)
return
test_func(event_sns, context)
assert (len(elasti... |
def test_integration(tmpdir):
os.environ['_DORA_TEST_TMPDIR'] = str(tmpdir)
with pytest.raises(sp.SubprocessError):
run_cmd(['info', '--', 'a=32'])
run_cmd(['info'])
run_cmd(['run'])
run_cmd(['grid', 'test', '--dry_run', '--init', '--no_monitor'])
run_cmd(['info', '--', '--a=32'])
ru... |
(scope='module')
def geth_process(geth_binary, datadir, genesis_file, geth_command_arguments):
init_datadir_command = (geth_binary, '--datadir', str(datadir), 'init', str(genesis_file))
subprocess.check_output(init_datadir_command, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
proc = subprocess.Popen(geth_... |
def record_charging():
Charging.record_charging(car, 'InProgress', date0, 50, latitude, longitude, 'FR', 'slow', 20, 60, .1)
Charging.record_charging(car, 'InProgress', date1, 75, latitude, longitude, 'FR', 'slow', 20, 60, .1)
Charging.record_charging(car, 'InProgress', date2, 85, latitude, longitude, 'FR',... |
def schemaless_reader(fo: IO, writer_schema: Schema, reader_schema: Optional[Schema]=None, return_record_name: bool=False, return_record_name_override: bool=False, handle_unicode_errors: str='strict', return_named_type: bool=False, return_named_type_override: bool=False) -> AvroMessage:
if (writer_schema == reader_... |
def exact_match(kineto_et_ops, kineto_ac2g_s_ops, kineto_ac2g_f_ops, kineto_cpu_launcher_ops, kineto_gpu_ops, et_nodes):
kineto_op_per_thread = {}
process_end_time = (- 1)
for i in range(len(kineto_et_ops)):
op = kineto_et_ops[i]
if (op['tid'] not in kineto_op_per_thread):
kineto... |
def test_get_key_from_data_method_invalid_key() -> None:
with pytest.raises(FidesValidationError) as exc:
get_key_from_data({'key': 'test*key', 'name': 'config name'}, 'StorageConfig')
assert (str(exc.value) == "FidesKeys must only contain alphanumeric characters, '.', '_', '<', '>' or '-'. Value provid... |
def session_fixation(url, method, headers, body, scanid):
attack_result = {}
login_result = get_value('config.property', 'login', 'loginresult')
logout_result = get_value('config.property', 'logout', 'logoutresult')
if ((login_result == 'Y') and (logout_result == 'Y')):
(login_data, logout_data)... |
def test_ttcompile_otf_compile_default(tmpdir):
inttx = os.path.join('Tests', 'ttx', 'data', 'TestOTF.ttx')
outotf = tmpdir.join('TestOTF.ttx')
default_options = ttx.Options([], 1)
ttx.ttCompile(inttx, str(outotf), default_options)
assert outotf.check(file=True)
ttf = TTFont(str(outotf))
exp... |
def test_workflows_merge(monkeypatch, tmpdir):
expected_result = {'wf_job1': '/dummy/path/wf_job1', 'wf_job2': '/dummy/path/wf_job2', 'some_func': str((tmpdir / 'SOME_FUNC'))}
tempfile_mock = Mock(return_value=tmpdir)
monkeypatch.setattr(tempfile, 'mkdtemp', tempfile_mock)
pm = ErtPluginManager(plugins=... |
class AZlyrics(Requester):
def __init__(self, search_engine='', accuracy=0.6, proxies={}):
self.title = ''
self.artist = ''
self.search_engine = search_engine
self.accuracy = accuracy
if (not (0 < accuracy <= 1)):
self.accuracy = 0.6
self.proxies = proxies... |
class TrialAction(UseCard):
def __init__(self, source, target, ft, card):
(self.source, self.target, self.ft, self.card) = (source, target, ft, card)
def apply_action(self):
g = self.game
c = self.card
ft = self.ft
g.players.exclude(self.source).reveal(c)
with Mig... |
class OptionSeriesErrorbarSonificationContexttracksMappingLowpassResonance(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 braintree_dataset_config(db: Session, braintree_connection_config: ConnectionConfig, braintree_dataset: Dict[(str, Any)]) -> Generator:
fides_key = braintree_dataset['fides_key']
braintree_connection_config.name = fides_key
braintree_connection_config.key = fides_key
braintree_connection_config.save... |
def _priSort(nodes: Union[(Tensor, List[Tensor])], pri_tensor_helper: PriTensorHelper) -> List[Tensor]:
nodes = _dfsSort(nodes)
in_degree = {}
for node in nodes:
in_degree[node] = 0
for src_op in node.src_ops():
in_degree[node] += len(set(src_op._attrs['inputs']))
queue = []
... |
class OptionSeriesTilemapEvents(Options):
def afterAnimate(self):
return self._config_get(None)
def afterAnimate(self, value: Any):
self._config(value, js_type=False)
def checkboxClick(self):
return self._config_get(None)
def checkboxClick(self, value: Any):
self._config(... |
def to_pytorch_dataloader(dataset, **kwargs):
import torch
default_kwargs = dict(batch_size=128, num_workers=1, shuffle=True, pin_memory=True, collate_fn=None)
merged_kwargs = {k: v for (k, v) in default_kwargs.items()}
if kwargs:
merged_kwargs.update(kwargs)
return torch.utils.data.DataLoad... |
class UserConfig(DatClass):
id: int = field(default=None)
face_ai_recognition_status: int = field(default=None)
auto_generate_memory: int = field(default=None)
is_sfiia_entry_hidden: bool = field(default=None)
homepage_visibility: int = field(default=None)
folder_cover_enable: bool = field(defau... |
def extractXtrawhippedcreamBlog(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) ... |
def change_access_level_to_int(apps, schema_editor):
CollectionMember = apps.get_model('django_etebase', 'CollectionMember')
CollectionInvitation = apps.get_model('django_etebase', 'CollectionInvitation')
for member in CollectionMember.objects.all():
if (member.accessLevelOld == 'adm'):
... |
class Square():
def __init__(self, pieceStatus, color, piece, row, col):
self.pieceStatus = pieceStatus
self.color = color
self.piece = piece
self.row = row
self.col = col
self.des = False
self.option = 0
def __str__(self):
global a_block
g... |
class OptionPlotoptionsLollipopSonificationTracksMappingVolume(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 RoxUtils(object):
def __init__(self, project, readonly=False):
self._project = None
self._version = roxar.__version__
if (versionparse(self._version) < versionparse('1.5')):
raise RuntimeError('XTGeo >= 3.0 requires Roxar API >= 1.5')
self._roxexternal = True
... |
def extractMtlAsianovelCom(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 ta... |
def load_team(cfg, external):
if external:
car = None
plugins = []
else:
team_path = team.team_path(cfg)
car = team.load_car(team_path, cfg.opts('mechanic', 'car.names'), cfg.opts('mechanic', 'car.params'))
plugins = team.load_plugins(team_path, cfg.opts('mechanic', 'car.... |
class OptionPlotoptionsNetworkgraphMarker(Options):
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def enabledThreshold(self):
return self._config_get(2)
def enabledThreshold(self, num: float):
self._confi... |
class OptionSeriesHeatmapSonificationDefaultspeechoptionsMappingRate(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 nutils_hash(TestCase):
class custom():
def __nutils_hash__(self):
return b''
def f(self):
pass
def test_ellipsis(self):
self.assertEqual(nutils.types.nutils_hash(...).hex(), '0c8bce06e451e4d5c49f60da0abf2ccbadf80600')
def test_None(self):
self.as... |
def install_all_plugins(sources, develop=False):
print('Installing all Flyte plugins in {} mode'.format(('development' if develop else 'normal')))
wd = os.getcwd()
for (k, v) in sources.items():
try:
os.chdir(os.path.join(wd, v))
if develop:
pip.main(['install... |
def calculate_bounding_box(points: Sequence[Dict], max_width, max_height):
return {'x': (min(points, key=(lambda x: x['x']))['x'] / max_width), 'y': (max(points, key=(lambda x: x['y']))['y'] / max_height), 'width': ((max(points, key=(lambda x: x['x']))['x'] / max_width) - (min(points, key=(lambda x: x['x']))['x'] /... |
def nm_get_interfaces():
check_nm_imported()
active_interfaces = []
for active_con in nm_get_client().get_active_connections():
if active_con.get_vpn():
continue
try:
con = active_con.get_connection()
if (con.get_flags() & (NM.SettingsConnectionFlags.NM_GE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.