code stringlengths 281 23.7M |
|---|
class CreatePolicy(SchemaBase):
sub: str = Field(..., description='uuid / ')
path: str = Field(..., description='api ')
method: MethodType = Field(default=MethodType.GET, description='')
_validator('method')
def method_validator(cls, v):
if (not v.isupper()):
raise ValueError('')... |
class DevicePanel(panel.Panel):
__gsignals__ = {'append-items': (GObject.SignalFlags.RUN_LAST, None, (object, bool)), 'replace-items': (GObject.SignalFlags.RUN_LAST, None, (object,)), 'queue-items': (GObject.SignalFlags.RUN_LAST, None, (object,)), 'collection-tree-loaded': (GObject.SignalFlags.RUN_LAST, None, ())}
... |
def test_traversal_overriding():
provider1 = providers.Provider()
provider2 = providers.Provider()
provider3 = providers.DependenciesContainer(provider1=provider1, provider2=provider2)
provider = providers.DependenciesContainer()
provider.override(provider3)
all_providers = list(provider.travers... |
class Net2HTML(object):
def __init__(self, net, gv, abcd):
self.gv = gv
self.abcd = abcd
self.tree = Tree()
self.n2a = collections.defaultdict(set)
self.n2t = {}
snk = net.label('snakes')
self.count = collections.defaultdict(int)
for place in net.place... |
def test_wifiicon_deprecated_font_colour(caplog):
widget = qtile_extras.widget.network.WiFiIcon(font_colour='ffffff')
assert (caplog.record_tuples[0] == ('libqtile', logging.WARNING, 'The use of `font_colour` is deprecated. Please update your config to use `foreground` instead.'))
assert (widget.foreground ... |
class OptionSeriesBoxplotDragdropGuideboxDefault(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(self, ... |
class OptionPlotoptionsScatterSonificationTracksMappingTremoloDepth(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 get_auth_token(fb_auth_token, fb_user_id):
if ('error' in fb_auth_token):
return {'error': 'could not retrieve fb_auth_token'}
if ('error' in fb_user_id):
return {'error': 'could not retrieve fb_user_id'}
url = (config.host + '/v2/auth/login/facebook')
req = requests.post(url, header... |
def _test_special_outputs(check_tensor, check_all, test_name, capfd: pytest.CaptureFixture[str]):
X1 = Tensor(shape=[IntImm(1), IntImm(3)], dtype='float16', name='input0', is_input=True)
X2_op = ops.elementwise(FuncEnum.DIV)
X2 = X2_op(X1, 0.0)
X2._attrs['is_output'] = True
X2._attrs['name'] = 'outp... |
_models('spacy.Davinci.v2')
def openai_davinci_v2(config: Dict[(Any, Any)]=SimpleFrozenDict(max_tokens=500, temperature=_DEFAULT_TEMPERATURE), name: Literal['davinci']='davinci', strict: bool=OpenAI.DEFAULT_STRICT, max_tries: int=OpenAI.DEFAULT_MAX_TRIES, interval: float=OpenAI.DEFAULT_INTERVAL, max_request_time: float... |
def main():
logging.basicConfig(format=LOGGING_FORMAT)
parser = argparse.ArgumentParser(description=main.__doc__)
add_debug(parser)
add_app(parser)
add_env(parser)
add_region(parser)
args = parser.parse_args()
logging.getLogger(__package__.split('.')[0]).setLevel(args.debug)
assert c... |
class TestVariableDecode(unittest.TestCase):
def test_list_decode(self):
src = {'a-0': 'a', 'a-1': 'b', 'a-2': 'c'}
expect = {'a': ['a', 'b', 'c']}
self.assertEqual(expect, variable_decode(src))
def test_list_decode_non_int(self):
src = {'a-0': 'a', 'a-a': 'b', 'a-2': 'c'}
... |
(version=(1, 1, 5))
()
('-k', '--size', help='Plot size', type=int, default=32, show_default=True)
('--override-k', help='Force size smaller than 32', default=False, show_default=True, is_flag=True)
('-n', '--num', help='Number of plots or challenges', type=int, default=1, show_default=True)
('-b', '--buffer', help='Me... |
class FingerJointBase(ABC):
def calcFingers(self, length: float, bedBolts) -> tuple[(int, float)]:
(space, finger) = (self.settings.space, self.settings.finger)
fingers = int(((length - ((self.settings.surroundingspaces - 1) * space)) // (space + finger)))
if ((fingers == 0) and (length > (f... |
()
('type_', metavar='TYPE', type=click.Choice(list(faucet_apis_registry.supported_ids)), required=True)
('url', metavar='URL', type=str, required=False, default=None)
_option()
('--sync', is_flag=True, help='For waiting till the faucet has released the funds.')
_context
_aea_project
def generate_wealth(click_context: ... |
class OptionPlotoptionsStreamgraphTooltip(Options):
def clusterFormat(self):
return self._config_get('Clustered points: {point.clusterPointsAmount}')
def clusterFormat(self, text: str):
self._config(text, js_type=False)
def dateTimeLabelFormats(self) -> 'OptionPlotoptionsStreamgraphTooltipDa... |
class OptionYaxisDatetimelabelformats(Options):
def day(self) -> 'OptionYaxisDatetimelabelformatsDay':
return self._config_sub_data('day', OptionYaxisDatetimelabelformatsDay)
def hour(self) -> 'OptionYaxisDatetimelabelformatsHour':
return self._config_sub_data('hour', OptionYaxisDatetimelabelfor... |
class OptionSeriesSankeySonificationContexttracksMappingTremoloDepth(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):
... |
_s3
def test_download_log_files_and_skip_existing_files():
with tempfile.TemporaryDirectory() as dirpath:
given_a_bucket('some-bucket')
given_an_object('some-bucket', TEST_LOG_KEY, 'some-file-content')
given_an_object('some-bucket', TEST_LOG_KEY_EXISTING, 'some-file-content')
given_a... |
class OptionTheme(Options):
def mode(self):
return self._config_get()
def mode(self, value):
self._config(value)
def palette(self):
return self._config_get()
def palette(self, value):
self._config(value)
def monochrome(self) -> OptionMonochrome:
return self._c... |
def test_pwm_phase(pwm: PWMGenerator, la: LogicAnalyzer):
frequency = 10000.0
duty_cycle = 0.5
phase = 0.25
pwm.generate(['SQ1', 'SQ2'], frequency, duty_cycle, phase)
time.sleep(0.1)
interval = la.measure_interval(['LA1', 'LA2'], ['rising', 'rising'])
if (interval < 0):
interval += (... |
.parametrize('media_type', ['nope/json'])
def test_unknown_media_type(asgi, media_type):
client = _create_client_invalid_media(asgi, errors.HTTPUnsupportedMediaType)
headers = {'Content-Type': media_type}
assert (client.simulate_post('/', body=b'something', headers=headers).status_code == 200)
title_msg... |
class Solution():
def match(self, w1, w2):
return sum(((i == j) for (i, j) in zip(w1, w2)))
def findSecretWord(self, wordlist, master):
n = 0
while (n < 6):
count = collections.Counter((w1 for (w1, w2) in itertools.permutations(wordlist, 2) if (self.match(w1, w2) == 0)))
... |
class EnumTests(unittest.TestCase):
def test_empty(self):
src = 'enum foo {\n};\n'
ast = parser.parse(src)
self.assertEqual(ast, [['enum', 'foo', [], []]])
def test_one(self):
src = 'enum foo {\n BAR = 1\n};\n'
ast = parser.parse(src)
self.assertEqual(ast, [['e... |
def _get_deck(new_user_params: ExecutionParameters, ignore_jupyter: bool=False) -> typing.Union[(str, 'IPython.core.display.HTML')]:
deck_map = {deck.name: deck.html for deck in new_user_params.decks}
raw_html = get_deck_template().render(metadata=deck_map)
if ((not ignore_jupyter) and ipython_check()):
... |
class AuthenticationLog(SimpleEntity):
__auto_name__ = True
__tablename__ = 'AuthenticationLogs'
__mapper_args__ = {'polymorphic_identity': 'AuthenticationLog'}
log_id = Column('id', Integer, ForeignKey('SimpleEntities.id'), primary_key=True)
user_id = Column('uid', Integer, ForeignKey('Users.id'), ... |
class Signal(BaseSignal[VT]):
async def send(self, value: VT=None, *, key: Any=None, force: bool=False) -> None:
current_test = current_test_stack.top
if (current_test is None):
if (not force):
return
assert key
else:
key = (key if (key is ... |
class TabularEditor(Editor):
update = Event()
refresh = Event()
selected = Any()
multi_selected = List()
selected_row = Int((- 1))
multi_selected_rows = List(Int)
activated = Any()
activated_row = Int()
clicked = Instance('TabularEditorEvent')
dclicked = Instance('TabularEditorEv... |
def render_generate_module_repo_file(copr, name_release, module_nsv):
module = ModulesLogic.get_by_nsv_str(copr, module_nsv).one()
mock_chroot = coprs_logic.MockChrootsLogic.get_from_name(name_release, noarch=True).first()
url = os.path.join(copr.main_dir.repo_url, '')
repo_url = generate_repo_url(mock_... |
def _new_game(n_players: int, small_blind: int=50, big_blind: int=100, initial_chips: int=10000) -> Tuple[(ShortDeckPokerState, Pot)]:
pot = Pot()
players = [ShortDeckPokerPlayer(player_i=player_i, pot=pot, initial_chips=initial_chips) for player_i in range(n_players)]
state = ShortDeckPokerState(players=pl... |
('/adconfig')
def handle_adconfig(self):
global TXBuffer, navMenuIndex
TXBuffer = ''
navMenuIndex = 2
if rpieGlobals.wifiSetup:
return self.redirect('/setup')
if (not isLoggedIn(self.get, self.cookie)):
return self.redirect('/login')
sendHeadandTail('TmplStd', _HEAD)
if (self... |
def fasta_iterator(input_file):
with myopen(input_file) as f:
sequence = []
name = ''
begun = False
for line in f:
line = line.strip()
if line.startswith('>'):
if begun:
(yield Fasta(name, ''.join(sequence)))
... |
class OptionPlotoptionsScatter3dSonificationContexttracksMappingTime(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 LocalExecutedConditionalSection(ConditionalSection):
def __init__(self, name: str):
self._selected_case: Optional[Case] = None
super().__init__(name=name)
def start_branch(self, c: Case, last_case: bool=False) -> Case:
added_case = super().start_branch(c, last_case)
ctx = F... |
_default
class ImageAttachment(Attachment):
original_extension = attr.ib(None, type=Optional[str])
width = attr.ib(None, converter=_util.int_or_none, type=Optional[int])
height = attr.ib(None, converter=_util.int_or_none, type=Optional[int])
is_animated = attr.ib(None, type=Optional[bool])
previews ... |
def infer_conv_output_shape(input_shape: List[int], kernel_size: int, stride: int, padding: int) -> List[int]:
output_shape = []
for input_length in input_shape:
output_length = ((((input_length - kernel_size) + (2 * padding)) / stride) + 1)
if (not output_length.is_integer()):
raise... |
class OptionSeriesNetworkgraphSonificationDefaultinstrumentoptionsActivewhen(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(sel... |
class BMGNodesTest(unittest.TestCase):
def test_RealNode(self) -> None:
r42 = RealNode(42.0)
self.assertEqual(r42.value, 42.0)
self.assertEqual(size(r42), torch.Size([]))
self.assertEqual(support(r42), 'tensor(42.)')
def test_MultiplicationNode(self) -> None:
r2 = RealNod... |
class MagicIndex(object):
def find_magic_index(self, array):
if ((array is None) or (not array)):
return (- 1)
return self._find_magic_index(array, 0, (len(array) - 1))
def _find_magic_index(self, array, start, end):
if ((end < start) or (start < 0) or (end >= len(array))):
... |
class LoggingGenericCommon(ModelNormal):
allowed_values = {('message_type',): {'CLASSIC': 'classic', 'LOGGLY': 'loggly', 'LOGPLEX': 'logplex', 'BLANK': 'blank'}, ('compression_codec',): {'ZSTD': 'zstd', 'SNAPPY': 'snappy', 'GZIP': 'gzip'}}
validations = {}
_property
def additional_properties_type():
... |
class OptionPlotoptionsBarSonificationDefaultspeechoptionsMappingPlaydelay(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 OptionPlotoptionsErrorbarSonificationDefaultinstrumentoptionsMappingVolume(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, tex... |
class CollisionObj(object):
swagger_types = {'embedded': 'object', 'front': 'CollisionObjFront', 'id': 'str', 'lateral': 'CollisionObjFront', 'pedestrian': 'bool', 'rear': 'CollisionObjFront', 'roll_over': 'bool', 'updated_at': 'datetime'}
attribute_map = {'embedded': '_embedded', 'front': 'front', 'id': 'id', ... |
class TestPutDefaultStorageConfigSecretsS3():
(scope='function')
def url(self, storage_config_default) -> str:
return (V1_URL_PREFIX + STORAGE_DEFAULT_SECRETS).format(storage_type=StorageType.s3.value)
(scope='function')
def payload(self):
return {StorageSecrets.AWS_ACCESS_KEY_ID.value: ... |
class MultiSelect(HasPrivateTraits):
choices = List(Str)
selected = List(Str)
result = List(Str)
traits_view = View(HGroup(Item('selected', show_label=False, editor=StringListEditor(choices='choices')), Item('result', show_label=False, editor=StringListEditor(choices='selected'))), width=0.2, height=0.2... |
class ProviderInfo():
def __init__(self, name, guid, level=et.TRACE_LEVEL_INFORMATION, any_keywords=None, all_keywords=None, params=None):
self.name = name
self.guid = guid
self.level = level
if ((type(any_keywords) is list) or (any_keywords is None)):
self.any_bitmask = ... |
def extractKagerouscansWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('the film emperor asks for divorce every day', 'the film emperor asks for divorce every day',... |
class OptionSeriesVariablepieSonificationContexttracksMappingTremoloDepth(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)... |
.parametrize('n_gpus', [0])
def test_python_backend(n_gpus: int):
proc = run_common_setup_steps(n_gpus)
choices = enter_input(proc, '.*Choose your backend.*Enter your choice[^:]+: ?', '2')
assert ('[2] Python backend' in choices), 'Option 2 should be Python backend'
choices = enter_input(proc, '.*Models... |
('/feed-filters/feedid/<int:feedid>')
_required
def feedIdView(feedid):
feed = g.session.query(db.RssFeedEntry).filter((db.RssFeedEntry.id == feedid)).scalar()
if feed:
urls = [tmp.feed_url for tmp in feed.urls if tmp.feed_url]
if urls:
filter_state = content_views.get_filter_state_f... |
def processImportFile(tdenv, db, importPath, tableName):
tdenv.DEBUG0("Processing import file '{}' for table '{}'", str(importPath), tableName)
fkeySelectStr = '(SELECT {newValue} FROM {table} WHERE {stmt})'
uniquePfx = 'unq:'
uniqueLen = len(uniquePfx)
ignorePfx = '!'
with importPath.open('r', ... |
class _PreFMBuildMessage(_BuildChrootMessage):
body_schema = {'id': ' '$schema': ' 'description': 'Message sent by Copr build system', 'type': 'object', 'required': ['status', 'chroot', 'build', 'owner', 'copr', 'pkg', 'version', 'what', 'ip', 'who', 'user', 'pid'], 'properties': {'status': {'type': 'number', 'desc... |
def create_content_addressed_github_uri(uri: URI) -> URI:
if (not is_valid_api_github_uri(uri)):
raise CannotHandleURI(f"{uri} does not conform to Github's API 'url' scheme.")
response = requests.get(uri)
response.raise_for_status()
contents = json.loads(response.content)
if (contents['type'... |
class ToNumber(FunctionSignature):
name = 'number'
argument_types = [TypeHint.String, TypeHint.Numeric]
minimum_args = 1
return_value = TypeHint.Numeric
sometimes_null = True
def run(cls, source, base=None):
if is_string(source):
if ((len(source.split('.')) == 2) and (base in... |
.parametrize('call_args,call_kwargs', (((9, 7), {}), ((9,), {'b': 7}), (tuple(), {'a': 9, 'b': 7})))
def test_call_with_multiple_arguments(math_contract, call, call_args, call_kwargs):
result = call(contract=math_contract, contract_function='add', func_args=call_args, func_kwargs=call_kwargs)
assert (result == ... |
class IniHandler(BaseHandler):
def load(self, value):
config = KaptanIniParser()
config.read_file(StringIO(value))
return config.as_dict()
def dump(self, data, file_=None):
if (file_ is None):
raise NotImplementedError('Exporting .ini as string is not supported.')
... |
def find_uv_mesh(objects, insideModifiers=True):
for obj in objects:
if (obj and (obj.type == 'MESH')):
if (obj.data.shape_keys and (len(obj.data.shape_keys.key_blocks) == 2)):
if (('uv' in obj.data.shape_keys.key_blocks) and ('model' in obj.data.shape_keys.key_blocks)):
... |
def test_skill2skill_message():
with tempfile.TemporaryDirectory() as dir_name:
with cd(dir_name):
agent_name = 'MyAgent'
private_key_path = os.path.join(CUR_PATH, 'data', DEFAULT_PRIVATE_KEY_FILE)
builder = AEABuilder(registry_dir=Path(ROOT_DIR, 'packages'))
... |
class PrivateChat(Chat):
other: ChatMember
def __init__(self, *, channel: Optional[SlaveChannel]=None, middleware: Optional[Middleware]=None, module_name: str='', channel_emoji: str='', module_id: ModuleID=ModuleID(''), name: str='', alias: Optional[str]=None, id: ChatID=ChatID(''), uid: ChatID=ChatID(''), vend... |
class OptionSeriesBoxplotSonificationContexttracksMapping(Options):
def frequency(self) -> 'OptionSeriesBoxplotSonificationContexttracksMappingFrequency':
return self._config_sub_data('frequency', OptionSeriesBoxplotSonificationContexttracksMappingFrequency)
def gapBetweenNotes(self) -> 'OptionSeriesBox... |
class DrQTorso(hk.Module):
def __init__(self, activation: Callable[([jnp.ndarray], jnp.ndarray)]=jax.nn.relu, data_format: str='NHWC', name: str='drq_torso'):
super().__init__(name=name)
gain = ((2 ** 0.5) if (activation is jax.nn.relu) else 1.0)
def build_conv_layer(name: str, output_channe... |
class CommandTestCase(ApiTestBase):
fixtures = (ApiTestBase.fixtures + ['functional-measures-dont-edit'])
def setUpTestData(cls):
super(CommandTestCase, cls).setUpTestData()
max_measure_date = MeasureGlobal.objects.order_by('-month')[0].month
ImportLog.objects.create(current_at=max_measu... |
('cuda.masked_select.func_decl')
def gen_function_decl(func_attrs) -> str:
backend_spec = CUDASpec()
(x, mask) = func_attrs['inputs']
input_type = cuda_common.dtype_to_cuda_type(x._attrs['dtype'])
return FUNC_DECL_TEMPLATE.render(func_name=func_attrs['name'], input_type=input_type, index_type=backend_sp... |
def test_pycomponent_heritage():
C = MyPComponent2
assert (C.__name__ == C.JS.__name__)
assert (('PyComponent' in repr(C)) and ('PyComponent' in repr(C.JS)))
assert ((not ('proxy' in repr(C))) and ('proxy' in repr(C.JS)))
assert ((not ('JS' in repr(C))) and ('for JS' in repr(C.JS)))
mro = [MyPCo... |
def test_capture_four_rising_edges(la):
events = 100
(t1, t2) = la.capture(2, events, modes=['rising', 'four rising'])
expected = (((FREQUENCY ** (- 1)) * MICROSECONDS) * 3)
result = ((t2 - t1) - (t2 - t1)[0])
assert (np.arange(0, (expected * events), expected) == pytest.approx(result, abs=TWO_CLOCK... |
class PaginationCursorMeta(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
return {'next_cursor': (str,), 'lim... |
class IndexRange():
base: Optional[LoopIR.expr]
lo: Optional[int]
hi: Optional[int]
def get_bounds(self):
if (self.base is None):
lo = ('-inf' if (self.lo is None) else str(self.lo))
hi = ('inf' if (self.hi is None) else str(self.hi))
else:
lo = ('-inf... |
def get_port_desc(dp, waiters):
stats = dp.ofproto_parser.OFPFeaturesRequest(dp)
msgs = []
ofctl_utils.send_stats_request(dp, stats, waiters, msgs, LOG)
descs = []
for msg in msgs:
stats = msg.ports
for stat in stats.values():
d = {'port_no': UTIL.ofp_port_to_user(stat.po... |
def create_template_args(func_attrs: Dict[(str, Any)], indent: str=' ') -> Dict[(str, Any)]:
x = func_attrs['inputs'][0]
y = func_attrs['outputs'][0]
dst = y._attrs['name']
src = x._attrs['name']
func_name = func_attrs['name']
custom_libs = Target.current().get_custom_libs(os.path.dirname(__fil... |
class OptionPlotoptionsParetoMarkerStatesHover(Options):
def animation(self) -> 'OptionPlotoptionsParetoMarkerStatesHoverAnimation':
return self._config_sub_data('animation', OptionPlotoptionsParetoMarkerStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self,... |
class LondonTransactionBuilder(BerlinTransactionBuilder):
legacy_signed = LondonLegacyTransaction
legacy_unsigned = LondonUnsignedLegacyTransaction
typed_transaction = LondonTypedTransaction
def new_unsigned_dynamic_fee_transaction(cls, chain_id: int, nonce: int, max_priority_fee_per_gas: int, max_fee_p... |
class SelectDeviceForSinkPreference(widgets.ComboPreference, widgets.Conditional):
default = 'auto'
name = 'player/audiosink_device'
condition_preference_name = 'player/audiosink'
def __init__(self, preferences, widget):
self.is_enabled = False
widgets.ComboPreference.__init__(self, pref... |
class OptionPlotoptionsBoxplotSonificationDefaultinstrumentoptionsMappingGapbetweennotes(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... |
def _handle_data_and_model(new_config):
if ('data_config' in new_config):
new_config['data'] = new_config['data_config']
del new_config['data_config']
if ('model_config' in new_config):
new_config['model'] = new_config['model_config']
del new_config['model_config']
if ('local... |
def get_dependencies(contract_to_constructor, contract, dependencies):
if (contract in contract_to_constructor):
for arg in contract_to_constructor[contract]:
if ((type(arg) == str) and (ADDRESS_ARG_TAG in arg) and (arg not in dependencies)):
get_dependencies(contract_to_construc... |
class OptionPlotoptionsSeriesSonificationContexttracksMappingRate(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 test_prepare_transaction_replacement_without_nonce_sets_correct_nonce(w3):
current_transaction = SIMPLE_CURRENT_TRANSACTION
new_transaction = {'value': 1}
replacement_transaction = prepare_replacement_transaction(w3, current_transaction, new_transaction)
assert (replacement_transaction == {'value': ... |
def validate_observations_has_result(doc):
if (doc.ref_doctype == 'Sales Invoice'):
submittable = True
observations = frappe.db.get_all('Observation', {'sales_invoice': doc.docname, 'docstatus': ['!=', 2], 'has_component': False, 'status': ['!=', 'Cancelled']}, pluck='name')
for obs in obser... |
def placeholder_validator(value, **valid_placeholders):
placeholders = set(RE_PLACEHOLDER.findall(value))
if (not placeholders.issubset(valid_placeholders.keys())):
raise ValidationError(_('Invalid placeholders.'))
try:
return value.format(**valid_placeholders)
except (KeyError, ValueErr... |
def extractFoolishtranslationssWordpressCom(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, nam... |
class UserFollowGroupSchema(JSONAPISchema):
class Meta():
type_ = 'user-follow-group'
self_view = 'v1.user_follow_group_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
id = fields.Str(dump_only=True)
created_at = fields.DateTime(dump_only=True, timezone=True)
... |
class bsn_flow_idle(bsn_header):
version = 6
type = 4
experimenter = 6035143
subtype = 40
def __init__(self, xid=None, cookie=None, priority=None, table_id=None, match=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (cookie != None):
... |
def ml_start_workflow(data):
u = url('ml/workflow/execute')
j = '{"wf_unique_id": "4", "wf_body": {"nodes": [ { "task_name": "SelectDataset", "task_id": "flowchartNode1", "position": "left: 600px; top: 114px; color: rgb(0, 0, 0); background-color: rgb(255, 255, 255); line-height: 35px;", "inputs": [], "paramete... |
_os(*metadata.platforms)
def main():
common.log('PowerShell Suspicious Commands')
temp_script = Path('tmp.ps1').resolve()
with open(temp_script, 'w') as f:
f.write('whoami.exe\nexit\n')
powershell_commands = [['powershell.exe', '-ExecutionPol', 'Bypass', temp_script], ['powershell.exe', 'iex', '... |
def adapt_int_width(n, width, signed=True):
n = int(n)
if (width == 1):
result = n
elif (width == 2):
result = n
elif (width == 4):
result = (ctypes.c_int8(n).value if signed else ctypes.c_uint8(n).value)
elif (width == 8):
result = (ctypes.c_int8(n).value if signed e... |
class TestACESccToACES2056_1(util.ColorAssertsPyTest):
COLORS = [(f'color(--aces2065-1 {(2 ** (- 24))} {(2 ** (- 24))} {(2 ** (- 24))})', 'color(--acescc -0. -0. -0.)'), ('color(--aces2065-1 0.18 0.18 0.18)', 'color(--acescc 0.4135884 0.4135884 0.4135884)'), ('color(--aces2065-1 65504 65504 65504)', 'color(--acescc... |
('Events > Events under an Event Sub-topic > List All Events under an Event Sub-topic')
def evnt_sub_topic_event_get_list(transaction):
with stash['app'].app_context():
event_sub_topic = EventSubTopicFactory()
db.session.add(event_sub_topic)
event = EventFactoryBasic(event_sub_topic_id=1)
... |
def docs_get_section(docstring, section, output='extract', end=None):
outs = []
in_section = False
docstring_split = docstring.split('\n')
for (ind, line) in enumerate(docstring_split):
if ((section in line) and ('--' in docstring_split[(ind + 1)])):
in_section = True
if end:... |
def convert2dash(node):
dashes = []
offset = 0
style = node.style
if ('stroke-dasharray' in style):
if (style['stroke-dasharray'].find(',') > 0):
dashes = [float(dash) for dash in style['stroke-dasharray'].split(',')]
if ('stroke-dashoffset' in style):
offset = style['str... |
class MyInstallData(install_data.install_data):
def run(self):
install_data_command = self.get_finalized_command('install_data')
for project in list_doc_projects():
install_data_command.data_files.extend(list_docs_data_files(project))
build_tvtk_classes_zip()
tvtk_dir = '... |
class ForumModerationURLPatternsFactory(URLPatternsFactory):
app_namespace = 'forum_moderation'
topic_lock_view = get_class('forum_moderation.views', 'TopicLockView')
topic_unlock_view = get_class('forum_moderation.views', 'TopicUnlockView')
topic_delete_view = get_class('forum_moderation.views', 'Topic... |
def __read_toc_entry(fd, toc_entry_num):
CDROM_MSF = 2
FORMAT_cdrom_tocentry = 'BBBiB'
cdrom_tocentry = struct.pack(FORMAT_cdrom_tocentry, toc_entry_num, 0, CDROM_MSF, 0, 0)
CDROMREADTOCENTRY = 21254
cdrom_tocentry = fcntl.ioctl(fd, CDROMREADTOCENTRY, cdrom_tocentry)
(cdte_track, cdte_adr_ctrl, ... |
.parallel(nprocs=3)
def test_io_timestepping(element, tmpdir):
filename = os.path.join(str(tmpdir), 'test_io_timestepping_dump.h5')
filename = COMM_WORLD.bcast(filename, root=0)
mycolor = (COMM_WORLD.rank > (COMM_WORLD.size - 1))
comm = COMM_WORLD.Split(color=mycolor, key=COMM_WORLD.rank)
method = (... |
class TestCacheSystemStatusesForConsentReporting():
def test_cache_initial_status_and_identities_for_consent_reporting(self, db, privacy_request_with_consent_policy, connection_config, privacy_preference_history, privacy_preference_history_fr_provide_service_frontend_only):
privacy_preference_history.privac... |
def cache_action_required(cache_key: str, step: Optional[CurrentStep]=None, collection: Optional[CollectionAddress]=None, action_needed: Optional[List[ManualAction]]=None) -> None:
cache: FidesopsRedis = get_cache()
action_required: Optional[CheckpointActionRequired] = None
if step:
action_required ... |
def extractHololonovelsCom(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... |
_metaclass(abc.ABCMeta)
class chunk(stringify.StringifyMixin):
_PACK_STR = '!BBH'
_MIN_LEN = struct.calcsize(_PACK_STR)
def chunk_type(cls):
pass
def __init__(self, type_, length):
self._type = type_
self.length = length
def parser(cls, buf):
pass
def __len__(self... |
def test_update_versions_is_working_properly_case_5(create_test_data, create_pymel, create_maya_env):
data = create_test_data
pm = create_pymel
maya_env = create_maya_env
data['asset2_model_main_v002'].is_published = True
data['asset2_model_main_v003'].is_published = True
maya_env.open(data['ass... |
def main():
oj = (lambda *x: os.path.join(*x))
algorithm = 'particle_swarm_optimization'
passivbot_mode = 'neat_grid'
d0 = f'results_{algorithm}_{passivbot_mode}'
d0 = sys.argv[1]
if ('clock' in d0):
passivbot_mode = 'clock'
elif ('neat' in d0):
passivbot_mode = 'neat_grid'
... |
class Kor2EngDataModule(LightningDataModule):
name: str = 'kor2eng'
def __init__(self, config: dict, tokenizer: Tokenizer):
super().__init__()
self.config = config
self.tokenizer = tokenizer
self.kor2eng_train: Optional[List[Tuple[(str, str)]]] = None
self.kor2eng_val: Op... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.