code stringlengths 281 23.7M |
|---|
def _extract_around_indexes_returns_correct_array_with_mode_average(indexes, before, after, extended_indexes):
data = np.random.rand(100)
result = scared.signal_processing.extract_around_indexes(data, indexes, before, after, mode=scared.signal_processing.ExtractMode.AVERAGE)
expected = []
for i in index... |
class LoadCompanyCommitsAction(Action):
params = (Action.params + (ActionParam(name='company', short_name='c', type=str, required=True, description='Company name'),))
def name(cls) -> str:
return 'load-company-commits'
def help_text(cls) -> str:
return 'Load company repositories events commi... |
def basic_object_class_multiple_faba_with_loan_value_with_two_object_classes(award_count_sub_schedule, award_count_submission, defc_codes):
award1 = _loan_award(45)
award2 = _loan_award(87)
object_class1 = major_object_class_with_children('001', [1])
object_class2 = major_object_class_with_children('002... |
class PDFDocument():
security_handler_registry = {1: PDFStandardSecurityHandler, 2: PDFStandardSecurityHandler}
if (AES is not None):
security_handler_registry[4] = PDFStandardSecurityHandlerV4
if (SHA256 is not None):
security_handler_registry[5] = PDFStandardSecurityHandlerV5
d... |
class OptionPlotoptionsArcdiagramPointEvents(Options):
def click(self):
return self._config_get(None)
def click(self, value: Any):
self._config(value, js_type=False)
def drag(self):
return self._config_get(None)
def drag(self, value: Any):
self._config(value, js_type=Fals... |
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':... |
.xfail(raises=NotImplementedError, reason='Interpolation of UFL expressions into mixed functions not supported')
def test_mixed_function_interpolation(parentmesh, vertexcoords, tfs):
if (parentmesh.name == 'immersedsphere'):
vertexcoords = immersed_sphere_vertexcoords(parentmesh, vertexcoords)
(tfs_fam,... |
def construct_data_date_range(provided_filters: dict) -> str:
if ((provided_filters.get('fy') is not None) and (provided_filters.get('fy') > 2019)):
if (provided_filters.get('fy') == 2020):
string = f"FY{provided_filters.get('fy')}Q1"
else:
string = f"FY{provided_filters.get(... |
def create_cosmwasm_store_code_msg(contract_path: str, sender_address: Address) -> MsgStoreCode:
with open(contract_path, 'rb') as contract_file:
wasm_byte_code = gzip.compress(contract_file.read(), 9)
msg = MsgStoreCode(sender=str(sender_address), wasm_byte_code=wasm_byte_code)
return msg |
class Huber():
def __call__(self, y_pred: torch.Tensor, y_true: torch.Tensor, delta: float=1.0) -> torch.Tensor:
y_pred = convert_to_tensor(y_pred)
y_true = convert_to_tensor(y_true)
check_same_shape(y_pred, y_true)
abs_error = torch.abs((y_pred - y_true))
quadratic = torch.c... |
class OptionSeriesErrorbarAccessibility(Options):
def description(self):
return self._config_get(None)
def description(self, text: str):
self._config(text, js_type=False)
def descriptionFormat(self):
return self._config_get(None)
def descriptionFormat(self, text: str):
se... |
class SetIpv6DSCP_NonZeroECNandFlabel(BaseModifyPacketTest):
def runTest(self):
actions = [ofp.action.set_field(ofp.oxm.ip_dscp(1))]
pkt = simple_tcpv6_packet(ipv6_tc=17, ipv6_fl=10)
exp_pkt = simple_tcpv6_packet(ipv6_tc=5, ipv6_fl=10)
self.verify_modify(actions, pkt, exp_pkt) |
class TestColumnValueMedian(BaseFeatureDataQualityMetricsTest):
name: ClassVar = 'Median Value'
def get_stat(self, current: NumericCharacteristics):
return current.p50
def get_condition_from_reference(self, reference: Optional[ColumnCharacteristics]) -> TestValueCondition:
if (reference is n... |
class MySQLSchema(ConnectionConfigSecretsSchema):
host: str = Field(title='Host', description='The hostname or IP address of the server where the database is running.')
port: int = Field(3306, title='Port', description='The network port number on which the server is listening for incoming connections (default: ... |
class EnvironmentVarGuard(MutableMapping):
def __init__(self):
self._environ = os.environ
self._changed = {}
def __getitem__(self, envvar):
return self._environ[envvar]
def __setitem__(self, envvar, value):
if (envvar not in self._changed):
self._changed[envvar] =... |
def get_pins():
pins = pinutils.generate_pins(0, 31)
pinutils.findpin(pins, 'PD2', True)['functions']['ADC1_IN0'] = 0
pinutils.findpin(pins, 'PD3', True)['functions']['ADC1_IN1'] = 0
pinutils.findpin(pins, 'PD4', True)['functions']['ADC1_IN2'] = 0
pinutils.findpin(pins, 'PD5', True)['functions']['AD... |
def genotype(candidates, bam, type, options):
num_candidates = len(candidates)
for (nr, candidate) in enumerate(candidates):
if (((nr + 1) % 10000) == 0):
logging.info('Processed {0} of {1} candidates'.format((nr + 1), num_candidates))
if (candidate.score < options.minimum_score):
... |
def extractNekoyashiki(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('rakudai kishi no eiyuutan' in item['tags']):
return buildReleaseMessageWithType(item, 'Rakudai Kishi no ... |
class TestScheduler(unittest.TestCase):
def test_on_schedule_decorator(self):
schedule = '* * * * *'
tz = 'America/Los_Angeles'
example_func = Mock(__name__='example_func')
decorated_func = scheduler_fn.on_schedule(schedule='* * * * *', timezone=scheduler_fn.Timezone(tz))(example_fun... |
class HomeListing(AbstractCrudObject):
def __init__(self, fbid=None, parent_id=None, api=None):
self._isHomeListing = True
super(HomeListing, self).__init__(fbid, parent_id, api)
class Field(AbstractObject.Field):
ac_type = 'ac_type'
additional_fees_description = 'additional_fees... |
def create_solver(solver_parameters, *, pmat=None, appctx=None):
p = {}
if (solver_parameters is not None):
p.update(solver_parameters)
p.setdefault('snes_type', 'ksponly')
p.setdefault('ksp_rtol', 1e-07)
problem = NonlinearVariationalProblem(F, w, bcs=bcs, Jp=pmat)
solver = NonlinearVar... |
.skipcomplex
def test_p_independence_hdiv(mesh):
family = ('NCF' if (mesh.topological_dimension() == 3) else 'RTCF')
expected = [6, 6]
solvers = [fdmstar, facetstar]
for degree in range(3, 6):
element = FiniteElement(family, cell=mesh.ufl_cell(), degree=degree, variant='fdm')
V = Functio... |
def _create_plot_component():
numpts = 1000
x = sort(random(numpts))
y = random(numpts)
color = randint(0, 7, numpts)
pd = ArrayPlotData()
pd.set_data('index', x)
pd.set_data('value', y)
pd.set_data('color', color)
plot = Plot(pd)
plot.plot(('index', 'value', 'color'), type='cmap... |
def url_is_alive(url):
try:
req = request.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)')
req.get_method = (lambda : 'HEAD')
response = request.urlopen(req, timeout=10)
return True
except:
xbmc.log(msg=f... |
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':... |
.parametrize('input_features', [None, variables_arr, np.array(variables_arr), variables_str, np.array(variables_str), variables_user])
def test_with_pipe_and_skl_transformer_input_array(df_vartypes, input_features):
pipe = Pipeline([('imputer', SimpleImputer(strategy='constant')), ('transformer', MockTransformer())... |
def extractEndlessazureHomeBlog(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 tunl(alph1: float, alph2: float, U: float, strict: bool=False):
if strict:
alphs = np.array((alph1, alph2))
assert ((0.5 <= alphs).all() and (alphs <= 20).all() and (0 < U <= 16))
if (alphs >= 8).all():
assert (U <= 12)
if (alphs >= 16).all():
assert (U <=... |
class TestGetRuleTargets():
(scope='function')
def rule(self, policy: Policy) -> Rule:
return policy.get_rules_for_action(ActionType.access.value)[0]
(scope='function')
def rule_target(self, db, policy: Policy, rule: Rule) -> RuleTarget:
rule_targets: List[RuleTarget] = RuleTarget.filter... |
def _apply_response_formatters(method: RPCEndpoint, result_formatters: Formatters, error_formatters: Formatters, response: RPCResponse) -> RPCResponse:
def _format_response(response_type: Literal[('result', 'error', 'params')], method_response_formatter: Callable[(..., Any)]) -> RPCResponse:
appropriate_res... |
class MultisigAccount(DeterministicAccount):
def __init__(self, wallet: 'Wallet', row: AccountRow, keyinstance_rows: List[KeyInstanceRow], output_rows: List[TransactionOutputRow]) -> None:
self._multisig_keystore = cast(Multisig_KeyStore, wallet.get_keystore(cast(int, row.default_masterkey_id)))
sel... |
class GymDialogues(Model, BaseGymDialogues):
def __init__(self, **kwargs: Any) -> None:
Model.__init__(self, **kwargs)
def role_from_first_message(message: Message, receiver_address: Address) -> BaseDialogue.Role:
return BaseGymDialogue.Role.AGENT
BaseGymDialogues.__init__(self, ... |
class OptionPlotoptionsScatterStates(Options):
def hover(self) -> 'OptionPlotoptionsScatterStatesHover':
return self._config_sub_data('hover', OptionPlotoptionsScatterStatesHover)
def inactive(self) -> 'OptionPlotoptionsScatterStatesInactive':
return self._config_sub_data('inactive', OptionPloto... |
class LidEdge(FingerJointEdge):
char = 'l'
description = 'Edge for slide on lid (back)'
def __call__(self, length, bedBolts=None, bedBoltSettings=None, **kw):
hole_width = self.settings.hole_width
if (hole_width > 0):
super().__call__(((length - hole_width) / 2))
Groo... |
class RefundReceipt(DeleteMixin, QuickbooksManagedObject, QuickbooksTransactionEntity, LinkedTxnMixin):
class_dict = {'DepartmentRef': Ref, 'CurrencyRef': Ref, 'TxnTaxDetail': TxnTaxDetail, 'DepositToAccountRef': Ref, 'CustomerRef': Ref, 'BillAddr': Address, 'ShipAddr': Address, 'ClassRef': Ref, 'BillEmail': EmailA... |
class CoordinateSystemConverter():
def __init__(self, cs1_direction=['right', 'up', 'forward'], cs2_direction=['right', 'up', 'forward']):
(self.cs1_dir, self.cs1_axis, self.cs1_sign, self.cs1_system) = self._preprocessing(cs1_direction)
(self.cs2_dir, self.cs2_axis, self.cs2_sign, self.cs2_system) ... |
class Affine(Bijector):
def __init__(self, params_fn: Optional[flowtorch.Lazy]=None, *, shape: torch.Size, context_shape: Optional[torch.Size]=None, clamp_values: bool=False, log_scale_min_clip: float=(- 5.0), log_scale_max_clip: float=3.0, scale_fn: str='softplus') -> None:
super().__init__(params_fn, shap... |
def fetch_tokenizer(entity: str, ver: str) -> Tokenizer:
artifact = wandb.Api().artifact(f'{entity}/cleanformer/tokenizer:{ver}', type='other')
artifact_path = tokenizer_dir(ver)
json_path = (artifact_path / 'tokenizer.json')
artifact.download(root=str(artifact_path))
tokenizer = Tokenizer.from_file... |
class TestRecallScore(SimpleClassificationTestTopK):
name = 'Recall Score'
def get_value(self, result: DatasetClassificationQuality):
return result.recall
def get_description(self, value: Numeric) -> str:
return f'The Recall Score is {value:.3g}. The test threshold is {self.get_condition()}' |
class VanillaMultiheadAttention(Module):
def __init__(self, dim, batch_size=(- 1), seq_len=(- 1), num_heads=8, qkv_bias=False, attn_drop=0.0, proj_drop=0.0, has_residual=True, causal=False, attn_mask: Tensor=None, mask_seq=0):
super().__init__()
assert ((dim % num_heads) == 0), f'dim {dim} should be... |
def test_upass(testdir):
testdir.makepyfile("\n import pytest\n\n .xfail\n def test_unexpected_success():\n assert str(True) == 'True'\n ")
result = testdir.runpytest('-v')
result.stdout.fnmatch_lines(['test_upass.py::test_unexpected_success ... ok'])
assert (result.re... |
def test_extruded_mixed_fs_misses_cache():
m = UnitSquareMesh(1, 1)
e = ExtrudedMesh(m, 2, layer_height=1)
U0 = FiniteElement('DG', 'triangle', 0)
U1 = FiniteElement('CG', 'interval', 2)
V0 = TensorProductElement(U0, U1)
V1 = FunctionSpace(e, HDiv(V0))
U0 = FiniteElement('CG', 'triangle', 1)... |
()
('input_dir', type=click.Path(exists=True, file_okay=False))
('output_dir', type=click.Path(exists=False, file_okay=False))
('--recursive/--no-recursive', default=True, help='Search recursively')
('--overwrite/--no-overwrite', default=False, help='Overwrite existing files')
('--clean/--no-clean', default=False, help... |
class OptionSeriesWaterfallDataDragdropDraghandle(Options):
def className(self):
return self._config_get('highcharts-drag-handle')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('#fff')
def color(self, text: str):
... |
class TlsCertificatesResponseAllOf(ModelNormal):
allowed_values = {}
validations = {}
_property
def additional_properties_type():
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type)
_nullable = False
_property
def openapi_types():
lazy_... |
class UIWindow(HasPrivateTraits):
control = Instance(wx.Window)
size = Instance(wx.Size, ((- 1), (- 1)))
width = Property()
height = Property()
def __init__(self, parent, **traits):
super().__init__(**traits)
self.control = wx.Window(parent, (- 1), size=self.size, style=wx.FULL_REPAI... |
class HTML_Text_Extractor(HTMLParser):
def __init__(self):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs = True
self.text = ''
self.processing = False
def handle_starttag(self, tag, attrs):
if (tag == 'body'):
self.p... |
class FaucetUntaggedACLOutputMirrorTest(FaucetUntaggedTest):
CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "untagged"\n unicast_flood: False\nacls:\n 1:\n - rule:\n actions:\n allow: 1\n output:\n ports: [%(port_3)d]\n'
CON... |
def send_venue(token, chat_id, latitude, longitude, title, address, foursquare_id=None, foursquare_type=None, disable_notification=None, reply_to_message_id=None, reply_markup=None, timeout=None, allow_sending_without_reply=None, google_place_id=None, google_place_type=None, protect_content=None, message_thread_id=None... |
(scope='function')
def second_privacy_request_awaiting_consent_email_send(db: Session, consent_policy: Policy) -> PrivacyRequest:
privacy_request = _create_privacy_request_for_policy(db, consent_policy)
privacy_request.status = PrivacyRequestStatus.awaiting_email_send
privacy_request.save(db)
(yield pri... |
def get_number_of_unique_terms_for_accounts(filter_query: ES_Q, field: str, is_nested: bool=True) -> int:
search = AccountSearch().filter(filter_query)
cardinality_aggregation = A('cardinality', field=field, precision_threshold=11000)
if is_nested:
nested_agg = A('nested', path='financial_accounts_b... |
def main():
try:
html = get_instagram_html(INSTAGRAM_USERNAME)
if (os.environ.get('LAST_IMAGE_ID') == get_last_publication_url(html)):
print('Not new image to post in discord.')
else:
os.environ['LAST_IMAGE_ID'] = get_last_publication_url(html)
print('New ... |
def ModelFactory(name, RangeFactory):
class ModelWithRanges(HasTraits):
percentage = RangeFactory(0, 100)
open_closed = RangeFactory(0, 100, exclude_low=True)
closed_open = RangeFactory(0, 100, exclude_high=True)
open = RangeFactory(0, 100, exclude_low=True, exclude_high=True)
... |
class TestAusTasKi(unittest.TestCase):
def setUp(self):
self.session = Session()
self.adapter = Adapter()
self.session.mount(' self.adapter)
def test_parsing_payload(self):
filename = 'parsers/test/mocks/AU/AU_TAS_FI_payload1.json'
with open(filename) as f:
fa... |
def getdirinfo(cid):
pageitems = {'0': 25, '1': 50, '2': 100}
pageitem = pageitems[plugin.get_setting('pageitem')]
offset = 0
data = getfilelistdata(cid, offset, '0', '0', searchstr='0', nf='1')
dirinfo = {}
dirinfo['state'] = data['state']
if data['state']:
dirinfo['path'] = []
... |
def create_symbol_from_spim_symbol(segment: 'Segment', context_sym: spimdisasm.common.ContextSymbol) -> 'Symbol':
in_segment = False
sym_type = None
if (context_sym.type == spimdisasm.common.SymbolSpecialType.jumptable):
in_segment = True
sym_type = 'jtbl'
elif (context_sym.type == spimd... |
class LuaLexer(RegexLexer):
name = 'Lua'
aliases = ['lua']
filenames = ['*.lua', '*.wlua']
mimetypes = ['text/x-lua', 'application/x-lua']
tokens = {'root': [('#!(.*?)$', Comment.Preproc), default('base')], 'base': [('(?s)--\\[(=*)\\[.*?\\]\\1\\]', Comment.Multiline), ('--.*$', Comment.Single), ('(?... |
class OptionPlotoptionsPackedbubbleSonificationContexttracksActivewhen(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... |
class Solution():
def numberOfArithmeticSlices(self, A: List[int]) -> int:
ret = 0
prev = None
diff = None
clen = 0
for a in A:
if (prev is None):
prev = a
clen = 1
continue
if (diff is None):
... |
class A98RGBLinear(sRGB):
BASE = 'xyz-d65'
NAME = 'a98-rgb-linear'
SERIALIZE = ('--a98-rgb-linear',)
WHITE = WHITES['2deg']['D65']
def to_base(self, coords: Vector) -> Vector:
return lin_a98rgb_to_xyz(coords)
def from_base(self, coords: Vector) -> Vector:
return xyz_to_lin_a98rgb... |
class Wapiti(BaseScanner):
def init(self, argv):
self.wapiti_bin = None
self.wapiti_cmd = 'wapiti'
try:
(opts, args) = getopt.getopt(argv, 'hx:')
except getopt.GetoptError as err:
print(str(err))
self.exit(1)
for (o, v) in opts:
... |
class TestUnpackList(unittest.TestCase):
def test_simple(self):
def deserializer(reader):
(length,) = reader.peek('!B')
return reader.read(('!%ds' % length))[0]
reader = loxi.generic_util.OFReader(b'\x04abc\x03de\x02f\x01')
a = loxi.generic_util.unpack_list(reader, de... |
def test_database_urls_only_backfills_none_parts():
with mock.patch.dict(os.environ, {ENV_CODE_VAR: _UnitTestDbPartsNoneConfig.ENV_CODE, 'DATABASE_URL': 'postgres://dummy::12345/fresh_new_db_name', 'DATA_BROKER_DATABASE_URL': 'postgres://broker:-foobar:54321/fresh_new_db_name_broker'}, clear=True):
cfg = _U... |
def write_grid_property(name, grid, filename, file_format, shape, buffer):
arr = np.ndarray(shape=shape, buffer=buffer, dtype=buffer.dtype)
prop = xtgeo.GridProperty(ncol=shape[0], nrow=shape[1], nlay=shape[2], values=arr, grid=grid, name=name)
prop.to_file(filename, fformat=file_format)
return arr |
class Settings():
def __init__(self):
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_speed = 1.5
self.ship_limit = 3
self.bullet_speed = 2.5
self.bullet_width = 3
self.bullet_height = 15
self.bullet_... |
def get_available_plugin() -> List[str]:
skip = ['.isort.cfg']
skip.extend(test_alone_plugins)
ps = [{'dir_name': x, 'path': x} for x in sorted(os.listdir(os.path.join(BASE, 'plugins'))) if (x not in skip)]
plugins = [p['path'] for p in ps]
random.shuffle(plugins)
groups_of_plugins = [','.join(w... |
(no_gui_test_assistant, 'No GuiTestAssistant')
class TestGetColor(unittest.TestCase, GuiTestAssistant):
(no_modal_dialog_tester, 'ModalDialogTester unavailable')
def test_close(self):
tester = ModalDialogTester((lambda : get_color(None, 'rebeccapurple')))
tester.open_and_wait(when_opened=(lambda... |
class ERC20TransferFromBenchmark(BaseERC20Benchmark):
def __init__(self) -> None:
super().__init__()
def name(self) -> str:
return 'ERC20 TransferFrom'
def _setup_benchmark(self, chain: MiningChain) -> None:
self._next_nonce = None
(txn, callback) = self._deploy_simple_token(... |
class CustomDialog(QDialog):
INVALID_COLOR = QColor(255, 235, 235)
def __init__(self, title: str='Title', description: str='Description', parent: Optional[QWidget]=None) -> None:
QDialog.__init__(self, parent)
self._option_list: List[QWidget] = []
self.setModal(True)
self.setWind... |
def get_epoch_for_url(url, netloc=None):
if (not netloc):
netloc = urllib.parse.urlsplit(url).netloc
interval = get_interval_for_netloc(netloc)
assert netloc
if (interval == 0):
return (2 ** 30)
return common.util.rewalk_epoch.get_epoch_from_netloc_interval(netloc, interval) |
class ESP32H2BETA2StubLoader(ESP32H2BETA2ROM):
FLASH_WRITE_SIZE = 16384
STATUS_BYTES_LENGTH = 2
IS_STUB = True
def __init__(self, rom_loader):
self.secure_download_mode = rom_loader.secure_download_mode
self._port = rom_loader._port
self._trace_enabled = rom_loader._trace_enabled... |
.django_db(transaction=True)
def test_download_awards_with_all_prime_awards(client, _award_download_data):
download_generation.retrieve_db_string = Mock(return_value=get_database_dsn_string())
filters = {'agency': 'all', 'prime_award_types': list(award_type_mapping.keys()), 'date_type': 'action_date', 'date_ran... |
def add_MsgServicer_to_server(servicer, server):
rpc_method_handlers = {'Unjail': grpc.unary_unary_rpc_method_handler(servicer.Unjail, request_deserializer=cosmos_dot_slashing_dot_v1beta1_dot_tx__pb2.MsgUnjail.FromString, response_serializer=cosmos_dot_slashing_dot_v1beta1_dot_tx__pb2.MsgUnjailResponse.SerializeToS... |
def test_definitions_to_json_schema():
definitions = typesystem.Definitions()
artist = typesystem.Schema(fields={'name': typesystem.String(max_length=100)})
album = typesystem.Schema(fields={'title': typesystem.String(max_length=100), 'release_date': typesystem.Date(), 'artist': typesystem.Reference(to='Art... |
class Dealer():
def __init__(self, **deck_kwargs):
self.deck = Deck(**deck_kwargs)
def deal_card(self) -> Card:
return self.deck.pick(random=True)
def deal_private_cards(self, players: List[Player]):
for _ in range(2):
for player in players:
card: Card = s... |
def publish(message: 'base.BodhiMessage', force: bool=False):
if force:
_publish_with_retry(message)
return
session = Session()
if ('messages' not in session.info):
session.info['messages'] = []
session.info['messages'].append(message)
_log.debug('Queuing message %r for deliv... |
def test_right_to_left(mesh, DGDPC0, W):
velocity = as_vector(((- 1.0), 0.0, 0.0))
u0 = project(velocity, W)
xs = SpatialCoordinate(mesh)
inflowexpr = conditional(And((real(xs[1]) > 0.25), (real(xs[1]) < 0.75)), 1.0, 0.5)
inflow = Function(DGDPC0)
inflow.interpolate(inflowexpr)
n = FacetNorm... |
def to_string(x, quote_string=True):
if isinstance(x, string_types):
if quote_string:
return ("'%s'" % x)
else:
return ('%s' % x)
elif isinstance(x, bool):
return str(x).lower()
elif isinstance(x, (int, float)):
return str(x)
elif isinstance(x, Non... |
class thread_credits(threading.Thread):
def run(self):
global print_lock
global cursor_x, cursor_y
credit_x = 0
i = 0
length = len(credits)
last_credits = ['']
startTime = time.time()
for ch in credits:
currentTime = (startTime + ((174.0 / ... |
class LineEdit(QtWidgets.QLineEdit):
def __init__(self, *args, **kwargs):
super(LineEdit, self).__init__(*args, **kwargs)
self.setAcceptDrops(True)
def dragEnterEvent(self, e):
mime_data = e.mimeData()
if (mime_data.hasFormat('text/plain') or mime_data.hasUrls()):
e.a... |
def _set_invalid_error_string(source_node: NodeBase, pc_map: Dict) -> None:
try:
node = source_node.children(include_children=False, offset_limits=pc_map['offset'])[0]
except IndexError:
return
if (node.nodeType == 'IndexAccess'):
pc_map['dev'] = 'Index out of range'
elif (node.n... |
def getfqdn() -> str:
global fqdn
if (not fqdn):
fqdn = socket.getfqdn()
if (fqdn == 'localhost.localdomain'):
fqdn = socket.gethostname()
if (not fqdn):
fqdn = os.environ.get('HOSTNAME')
if (not fqdn):
fqdn = os.environ.get('HOST')
if ... |
def wait_for_node_initialization(is_initialized, backend, wait_time=0.3):
iter = 0
while True:
if (iter == 0):
sleep(0.1)
else:
sleep(wait_time)
iter += 1
not_init = []
for (name, flag) in is_initialized.items():
if (not flag):
... |
_dataclasses.dataclass(frozen=True)
class IntParam(Param[int]):
def value(self) -> int:
if (_os.environ.get(self.name) is not None):
return int(_os.environ[self.name])
if (self.default is not None):
return (self.default.value if isinstance(self.default, Expression) else self.... |
class Envs(FlyteIdlEntity):
def __init__(self, envs: Dict[(str, str)]):
self._envs = envs
def envs(self) -> Dict[(str, str)]:
return self._envs
def to_flyte_idl(self) -> _common_pb2.Envs:
return _common_pb2.Envs(values=[_literals_pb2.KeyValuePair(key=k, value=v) for (k, v) in self.en... |
class TestWebUIBuilds(CoprsTestCase):
('u1')
.usefixtures('f_users', 'f_users_api', 'f_mock_chroots', 'f_db')
def test_isolation_option_set(self):
chroot = 'fedora-rawhide-i386'
project = 'test'
self.web_ui.new_project(project, [chroot], isolation='simple')
route = '/coprs/{u... |
class RemoveTask(Task):
def __init__(self, block_id_to_remove=None, datetime_to_run=None, client=None, dic=None):
if client:
self.notion_client = client
if dic:
super().__init__(type='RemoveTask', dic=dic)
elif (block_id_to_remove and datetime_to_run):
sup... |
class Plugin(plugin.PluginProto):
PLUGIN_ID = 10
PLUGIN_NAME = 'Environment - BH1750 Lux sensor'
PLUGIN_VALUENAME1 = 'Lux'
def __init__(self, taskindex):
plugin.PluginProto.__init__(self, taskindex)
self.dtype = rpieGlobals.DEVICE_TYPE_I2C
self.vtype = rpieGlobals.SENSOR_TYPE_SIN... |
class OptionPlotoptionsPackedbubble(Options):
def accessibility(self) -> 'OptionPlotoptionsPackedbubbleAccessibility':
return self._config_sub_data('accessibility', OptionPlotoptionsPackedbubbleAccessibility)
def allowPointSelect(self):
return self._config_get(False)
def allowPointSelect(sel... |
.integration
class TestFidesConnectorIntegration():
def test_test_connection(self, test_fides_connector: FidesConnector):
assert (test_fides_connector.test_connection() == ConnectionTestStatus.succeeded)
.usefixtures('postgres_integration_db', 'postgres_example_test_dataset_config_read_access')
def ... |
(gridproperties())
def test_get_dataframe_filled(gridproperties):
gridproperties_list = list(gridproperties)
assume((len(gridproperties_list) > 0))
df = xtgeo.gridproperties_dataframe(gridproperties, ijk=False, activeonly=False)
assert (len(df.index) == ((gridproperties.ncol * gridproperties.nrow) * gri... |
.skipif((os.name == 'nt'), reason='Theme error writing content1: filename, directory name, or volume label syntax is incorrect')
def test_toc_urllink(cli: CliRunner, temp_with_override, file_regression):
path_output = temp_with_override.joinpath('mybook').absolute()
p_toc = path_books.joinpath('toc')
path_t... |
class Bijection():
def __init__(self, module, word_dtype, key_dtype, counter_dtype):
self.module = module
self.word_dtype = word_dtype
self.key_words = key_dtype.fields['v'][0].shape[0]
self.counter_words = counter_dtype.fields['v'][0].shape[0]
self.counter_dtype = counter_dt... |
class PacketdrillSuite(Suite):
NAME = 'packetdrill'
def discover_cases(self) -> List[DiscoveredTestCase]:
return [DiscoveredTestCase(name='exec', description='does the test exit(0)')]
def parse(self, stdout: List[str], stderr: List[str], returncode: int) -> List[TestCaseResult]:
test_cases: ... |
class ConditionHandler(Handler):
def register(self):
self._lifter.HANDLERS.update({mediumlevelil.MediumLevelILCmpE: partial(self.lift_condition, operation=OperationType.equal), mediumlevelil.MediumLevelILCmpNe: partial(self.lift_condition, operation=OperationType.not_equal), mediumlevelil.MediumLevelILCmpSg... |
def _factorise(req, intervals=None):
if (intervals is None):
intervals = []
if (not isinstance(intervals, (list, tuple, set))):
intervals = [intervals]
if intervals:
for r in req:
for i in intervals:
if (i in r):
r[i] = _as_interval(r[i... |
def _is_assignment_with_simple_binary_operation(assignment: Assignment) -> bool:
return (isinstance(assignment.value, BinaryOperation) and (assignment.value.operation in {OperationType.plus, OperationType.minus}) and any(((isinstance(operand, Constant) or _is_negated_constant_variable(operand, Constant)) for operan... |
_tuple
def alice_nominates_bob_and_ron_then_they_kick_her(chain):
header = PARAGON_GENESIS_HEADER
header = make_next_header(chain, header, ALICE_PK)
(yield header)
header = make_next_header(chain, header, ALICE_PK, BOB, NONCE_AUTH)
(yield header)
header = make_next_header(chain, header, BOB_PK, ... |
class OptionPlotoptionsItemSonificationTracksMappingRate(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):
self._c... |
(_BUILD_NIGHTHAWK_BENCHMARKS)
(_BUILD_NIGHTHAWK_BINARIES)
(_BUILD_ENVOY_BINARY)
('src.lib.cmd_exec.run_command')
def test_nh_build_failure(mock_cmd, mock_envoy_build, mock_nh_bin_build, mock_nh_bench_build):
mock_nh_bench_build.side_effect = subprocess.CalledProcessError(1, 'bar')
mock_envoy_path = '/home/ubunt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.