code stringlengths 281 23.7M |
|---|
def test_deepcopy_with_sys_streams():
provider = providers.List()
provider.add_args(sys.stdin, sys.stdout, sys.stderr)
provider_copy = providers.deepcopy(provider)
assert (provider is not provider_copy)
assert isinstance(provider_copy, providers.List)
assert (provider.args[0] is sys.stdin)
a... |
('kwargs', itertools.product([('xradius', 10), ('yradius', 10)], [('xradius', 20)], [('yradius', 20)], [('radius', 10)]))
def test_draw_rectangle_with_radius(kwargs):
with Image(width=50, height=50, background='white') as img:
was = img.signature
with Drawing() as ctx:
ctx.stroke_width =... |
class EditUserInfoView(View):
def put(self, request):
res = {'code': 332, 'msg': '!', 'self': None}
valid_email_obj = request.session.get('valid_email_obj')
if (not valid_email_obj):
res['msg'] = '!'
return JsonResponse(res)
time_stamp = valid_email_obj['time_... |
class GymHandler(Handler):
SUPPORTED_PROTOCOL = GymMessage.protocol_id
def __init__(self, **kwargs: Any):
nb_steps = kwargs.pop('nb_steps', DEFAULT_NB_STEPS)
super().__init__(**kwargs)
self.task = GymTask(self.context, nb_steps)
self._task_id: Optional[int] = None
def setup(s... |
class OptionSeriesErrorbarSonificationTracksMappingPan(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._con... |
class OptionSeriesParetoLabelStyle(Options):
def fontSize(self):
return self._config_get('0.8em')
def fontSize(self, num: float):
self._config(num, js_type=False)
def fontWeight(self):
return self._config_get('bold')
def fontWeight(self, text: str):
self._config(text, js_... |
class OptionPlotoptionsParetoSonificationTracksMappingTremolo(Options):
def depth(self) -> 'OptionPlotoptionsParetoSonificationTracksMappingTremoloDepth':
return self._config_sub_data('depth', OptionPlotoptionsParetoSonificationTracksMappingTremoloDepth)
def speed(self) -> 'OptionPlotoptionsParetoSonifi... |
def heckbert_interval(data_low, data_high, numticks=8, nicefunc=_nice, enclose=False):
if (data_high == data_low):
return (data_high, data_low, 0)
if (numticks == 0):
numticks = 1
range = nicefunc((data_high - data_low))
if (numticks > 1):
numticks -= 1
d = nicefunc((range / ... |
class AWin():
name: Sym
coords: list[AWinCoord]
strides: list[A.expr]
def __str__(win):
def coordstr(c):
op = ('=' if c.is_pt else '+')
return f'{op}{c.val}'
coords = ''
if (len(win.coords) > 0):
coords = (',' + ','.join([coordstr(c) for c in w... |
class SlateKernel(TSFCKernel):
def _cache_key(cls, expr, compiler_parameters):
return (md5((expr.expression_hash + str(sorted(compiler_parameters.items()))).encode()).hexdigest(), expr.ufl_domains()[0].comm)
def __init__(self, expr, compiler_parameters):
if self._initialized:
return
... |
class FederalAccount(models.Model):
agency_identifier = models.TextField(db_index=True)
main_account_code = models.TextField(db_index=True)
account_title = models.TextField()
federal_account_code = models.TextField(null=True)
parent_toptier_agency = models.ForeignKey('references.ToptierAgency', mode... |
def test_h4_1():
T = bytearray.fromhex('c234c1198f3b520186ab92a2f874934e')
A1 = bytearray.fromhex('bfce')
A2 = bytearray.fromhex('a713702dcfc1')
(ComputedHash, ComputedDAK) = h4(T, A1, A2, KeyID['btdk'])
Hash = bytearray.fromhex('b089c4e39d7c192c3aba3c2109d24c0dc039e700adf3a263008e65a8b00fb1fa')
... |
def test_wf1_with_subwf():
def t1(a: int) -> NamedTuple('OutputsBC', t1_int_output=int, c=str):
a = (a + 2)
return (a, ('world-' + str(a)))
def t2(a: str, b: str) -> str:
return (b + a)
def my_subwf(a: int) -> (str, str):
(x, y) = t1(a=a)
(u, v) = t1(a=x)
retu... |
.parametrize('current_data, reference_data, column_mapping, metric, expected_json', ((pd.DataFrame(), None, ColumnMapping(), DatasetSummaryMetric(almost_duplicated_threshold=0.9), {'almost_duplicated_threshold': 0.9, 'current': {'date_column': None, 'id_column': None, 'nans_by_columns': {}, 'number_of_almost_constant_c... |
.parametrize('block_hash,is_valid', ((1, False), (True, False), ((b'\x00' * 32), True), ((b'\xff' * 32), True), (('\x00' * 32), False), (encode_hex((b'\x00' * 32)), False)))
def test_block_hash_output_validation(validator, block_hash, is_valid):
if is_valid:
validator.validate_outbound_block_hash(block_hash... |
def test_raises_only_field_errors_unexpected(unknown_event_id_field_error, invalid_organization_id_field_error):
errors = [unknown_event_id_field_error, invalid_organization_id_field_error]
with pytest.raises(pytest.raises.Exception):
with raises_only_field_errors({'organization_id': 'INVALID'}):
... |
def failing_call_with_output(cmd, expected, env=None):
proc = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, env=env)
(stdout, stderr) = proc.communicate()
if WINDOWS:
print('warning: skipping part of failing_call_with_output() due to error ... |
def listNextPasesHtml(passTable, howmany):
i = 1
output = "<table class='table small'>\n"
output += '<tr><th>#</th><th>satellite</th><th>start</th><th>duration</th><th>peak</th><th>azimuth</th><th>freq</th><th>process with</th><tr>\n'
uniqueEvents = list(set([x[0] for x in passTable[0:howmany]]))
co... |
def forward(model: Model[(InT, OutT)], Xr: InT, is_train: bool) -> Tuple[(OutT, Callable)]:
Y = model.ops.reduce_mean(cast(Floats2d, Xr.data), Xr.lengths)
lengths = Xr.lengths
array_info = ArrayInfo.from_array(Y)
def backprop(dY: OutT) -> InT:
array_info.check_consistency(dY)
return Ragg... |
class Decoder():
def __init__(self, wrapper: Wrapper, serverVersion: int):
self.wrapper = wrapper
self.serverVersion = serverVersion
self.logger = logging.getLogger('ib_insync.Decoder')
self.handlers = {1: self.priceSizeTick, 2: self.wrap('tickSize', [int, int, float]), 3: self.wrap(... |
class init_cond(object):
def __init__(self, L, scaling=0.25):
self.radius = 0.15
self.xc = 0.5
self.yc = 0.75
self.scaling = scaling
def uOfXT(self, x, t):
import numpy as np
beta = (epsCoupez * he)
r = math.sqrt((((x[0] - self.xc) ** 2) + ((x[1] - self.yc... |
def prepare_data_for_plots(current_data: pd.Series, reference_data: Optional[pd.Series], column_type: ColumnType, max_categories: Optional[int]=MAX_CATEGORIES) -> Tuple[(pd.Series, Optional[pd.Series])]:
if (column_type == ColumnType.Categorical):
(current_data, reference_data) = relabel_data(current_data, ... |
class OptionPlotoptionsStreamgraphSonificationDefaultinstrumentoptionsMappingLowpassResonance(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 ma... |
.parametrize('exception_phase', (ProcessPhase.STARTING, ProcessPhase.READY, ProcessPhase.RUNNING, ProcessPhase.STOPPING))
_test
def test_exception(exception_phase: ProcessPhase) -> None:
manager = ProcessManager(processes=(ProcessInfo(module=__name__, name='proc1', args=('--manager-name', 'test_manager', '--shutdow... |
class InfoOthers(View):
def get(self, request, article_id):
category = Category_Article.objects.all()
count = User.objects.filter(follow__fan__id=article_id)
floow = User.objects.filter(fan__follow_id=article_id)
user = User.objects.get(id=article_id)
is_active = Follows.obje... |
class TestAmazon(unittest.TestCase):
def setUp(self):
frappe.set_user('Administrator')
setup_custom_fields()
def test_get_orders(self):
amazon_repository = TestAmazonRepository()
sales_orders = amazon_repository.get_orders('2000-07-23')
self.assertEqual(len(sales_orders),... |
class PatternSequenceProcessor(InlineProcessor):
PATTERNS = []
def build_single(self, m, tag, full_recursion, idx):
el1 = etree.Element(tag)
text = m.group(2)
self.parse_sub_patterns(text, el1, None, full_recursion, idx)
return el1
def build_double(self, m, tags, full_recursi... |
.integrationtest
.skipif((not has_postgres_configured), reason='PostgresSQL not configured')
def test_psycopg_composable_query_works(instrument, postgres_connection, elasticapm_client):
from psycopg import sql
cursor = postgres_connection.cursor()
query = sql.SQL("SELECT * FROM {table} WHERE {row} LIKE 't%'... |
('/settings', methods=['GET'])
def settings():
config = current_app.config.get('MASTER_CONFIG')
config_contents = pformat(config)
file_contents = ''
file_path = ''
file_name = config.get('CONFIG_FILE')
if file_name:
file_path = os.path.join(config.data_path, file_name)
with open(... |
class GenericTableModel(QStandardItemModel):
rowCountChanged = pyqtSignal()
beginViewPortRefresh = pyqtSignal()
endViewPortRefresh = pyqtSignal()
db = None
tableName = ''
totalRowCount = 0
lastColumnCount = 0
origQueryStr = QSqlQuery()
prevQueryStr = ''
realQuery = QSqlQuery()
... |
def test_reload_dir_subdirectories_are_removed(reload_directory_structure: Path) -> None:
app_dir = (reload_directory_structure / 'app')
app_sub_dir = (app_dir / 'sub')
ext_dir = (reload_directory_structure / 'ext')
ext_sub_dir = (ext_dir / 'sub')
with as_cwd(reload_directory_structure):
con... |
def convert_to_bgra_if_required(color_format: ImageFormat, color_image):
if (color_format == ImageFormat.COLOR_MJPG):
color_image = cv2.imdecode(color_image, cv2.IMREAD_COLOR)
elif (color_format == ImageFormat.COLOR_NV12):
color_image = cv2.cvtColor(color_image, cv2.COLOR_YUV2BGRA_NV12)
elif... |
class RememberThreads(object):
def __init__(self):
self._threads = []
def __call__(self, *args, **kwargs):
thread = threading.Thread(*args, **kwargs)
self._threads.append(thread)
return thread
def __enter__(self):
return self
def __exit__(self, *exc_args):
... |
class OptionPlotoptionsWordcloudSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionPlotoptionsWordcloudSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionPlotoptionsWordcloudSonificationDefaultinstrumentoptionsMappingTrem... |
class _UserIdentityType():
def new(cls, event):
user_type = event['CloudTrailEvent']['userIdentity'].get('type', 'AWSService')
klass = globals().get(f'_{user_type}Type', cls)
return klass(event)
def __init__(self, event):
self.event = event
self.ct_event = event['CloudTra... |
_tuple
def _extract_vm_config(vm_config: Dict[(str, str)]) -> Iterable[VMFork]:
if ('frontierForkBlock' in vm_config.keys()):
(yield (hex_to_block_number(vm_config['frontierForkBlock']), FrontierVM))
if ('homesteadForkBlock' in vm_config.keys()):
homestead_fork_block = hex_to_block_number(vm_con... |
def find_project_config_file(project_directory: 'Path | None'=None, use_git: bool=False) -> 'Path | None':
git_directory = git_toplevel_dir(project_directory, use_git=use_git)
if (not git_directory):
LOGGER.debug('Project-based config file could not be loaded, is project not managed with git?')
... |
class LifespanHandler():
def __init__(self):
self.startup_succeeded = False
self.shutdown_succeeded = False
async def process_startup(self, scope, event):
assert (scope['type'] == 'lifespan')
assert (event['type'] == 'lifespan.startup')
self.startup_succeeded = True
a... |
class BatchCache():
_INDEX_NAME: str = 'index.jsonl'
def __init__(self, path: Optional[Union[(str, Path)]], batch_size: int, max_batches_in_mem: int):
self._path = (Path(path) if path else None)
self._batch_size = batch_size
self.max_batches_in_mem = max_batches_in_mem
self._voca... |
class sFlowV5RawPacketHeader(object):
_PACK_STR = '!iIII'
def __init__(self, header_protocol, frame_length, stripped, header_size, header):
super(sFlowV5RawPacketHeader, self).__init__()
self.header_protocol = header_protocol
self.frame_length = frame_length
self.stripped = strip... |
.gui()
def test_delete_without_selection_does_nothing(monkeypatch, tmp_path, qtbot: QtBot):
Path((tmp_path / 'tessdata')).mkdir()
Path(((tmp_path / 'tessdata') / 'deu.traineddata')).touch()
Path(((tmp_path / 'tessdata') / 'eng.traineddata')).touch()
window = language_manager.LanguageManager(tessdata_pat... |
class OptionPlotoptionsBellcurveSonificationContexttracksMappingTime(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 OptionPlotoptionsStreamgraphSonificationTracksMappingNoteduration(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 OptionSeriesVariwideTooltip(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) -> 'OptionSeriesVariwideTooltipDatetimelabelforma... |
class OptionPlotoptionsCylinderSonificationContexttracks(Options):
def activeWhen(self) -> 'OptionPlotoptionsCylinderSonificationContexttracksActivewhen':
return self._config_sub_data('activeWhen', OptionPlotoptionsCylinderSonificationContexttracksActivewhen)
def instrument(self):
return self._c... |
def main(wf):
if wf.update_available:
wf.add_item('An update is available!', autocomplete='workflow:update', valid=False, icon=helpers.get_icon(wf, 'cloud-download'))
find_brew = helpers.brew_installed()
if (not (find_brew['INTEL'] or find_brew['ARM'])):
helpers.brew_installation_instruction... |
def print_human_readable_format(sar_data):
header_start = '>'
header_stop = '<'
chapter_start = '---->'
chapter_stop = '<----'
for user in sar_data:
click.echo('{} User account data for: {} {}\n'.format(header_start, sar_data[user]['name'], header_stop))
click.echo('email: {}'.format... |
class OptionPlotoptionsLineSonificationPointgrouping(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: bool):
self._co... |
def choose_alternative_id(alt_ids):
if (set(alt_ids.keys()) == set(['001', '002'])):
if (sys.version_info.major != 3):
print('Invalid alternative set')
assert False
if (sys.version_info.minor <= 7):
return '001'
return '002'
print('Not implemented alte... |
.requires_roxar
def test_rox_getset_cube(roxar_project):
cube = xtgeo.cube_from_roxar(roxar_project, CUBENAME1)
assert (cube.values.mean() == pytest.approx(0.000718, abs=0.001))
cube.values += 100
assert (cube.values.mean() == pytest.approx(100.000718, abs=0.001))
cube.to_roxar(roxar_project, (CUBEN... |
def has_extension(name):
try:
if (platform.system() == 'Windows'):
res = subprocess.check_output('code --list-extensions', shell=True).decode('utf-8')
else:
res = subprocess.check_output(['code', '--list-extensions']).decode('utf-8')
return (name in res)
except (O... |
def exposed_nu_retrigger_series_pages():
step = 500000
with db.session_context() as sess:
end = sess.execute('SELECT MAX(id) FROM web_pages;')
end = list(end)[0][0]
start = sess.execute('SELECT MIN(id) FROM web_pages;')
start = list(start)[0][0]
changed = 0
if (no... |
def parse(repo, tag):
with codecs.open(os.path.join(current_dir, 'tags', repo, repo, 'db', 'emoji.json'), 'r', encoding='utf-8') as f:
emojis = json.loads(f.read())
emoji_db = {}
shortnames = set()
aliases = {}
for v in emojis:
short = v['aliases'][0]
shortnames.add((':%s:' %... |
class Opacity(Filter):
NAME = 'opacity'
ALLOWED_SPACES = ('srgb-linear', 'srgb')
def filter(self, color: 'Color', amount: Optional[float], **kwargs: Any) -> None:
amount = alg.clamp((1 if (amount is None) else amount), 0, 1)
color[(- 1)] = alg.lerp(0, amount, color[(- 1)]) |
def test_model_set_reference():
parent = create_model('parent')
child = create_model('child')
grandchild = create_model('child')
parent.layers.append(child)
assert (parent.ref_names == tuple())
parent.set_ref('kid', child)
assert (parent.ref_names == ('kid',))
assert (parent.get_ref('kid... |
class TaxRate(QuickbooksTransactionEntity, QuickbooksBaseObject, ReadMixin, ListMixin):
class_dict = {'AgencyRef': Ref, 'TaxReturnLineRef': Ref}
qbo_object_name = 'TaxRate'
def __init__(self):
super(TaxRate, self).__init__()
self.Name = ''
self.Description = ''
self.RateValue... |
class DataclassMutabilityMixin(DataclassHookMixin):
initialized: bool = field(default=False, init=False)
def __post_init__(self) -> None:
self.initialized = True
def __setattr__(self, name: str, value: Any) -> None:
if self.initialized:
try:
self.__getattribute__(... |
class bsn_table_checksum_stats_reply(bsn_stats_reply):
version = 5
type = 19
stats_type = 65535
experimenter = 6035143
subtype = 11
def __init__(self, xid=None, flags=None, entries=None):
if (xid != None):
self.xid = xid
else:
self.xid = None
if (f... |
class FoldersTab(QWidget):
def __init__(self, parent):
self.parent = parent
QWidget.__init__(self)
self.setup_ui()
def setup_ui(self):
self.vbox_left = QVBoxLayout()
r_lbl = QLabel('Most Used Folders:')
r_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
self... |
class OptionSeriesSolidgaugeSonificationContexttracksMappingFrequency(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_slice_will_un_slice_the_same_camera(prepare_scene, create_pymel):
camera = prepare_scene
pm = create_pymel
dres = pm.PyNode('defaultResolution')
dres.width.set(960)
dres.height.set(540)
rs = RenderSlicer(camera=camera)
rs.slice(10, 10)
assert (dres.width.get() == 96)
assert ... |
class TraitsUIScrolledPanel(wx.lib.scrolledpanel.ScrolledPanel):
def __init__(self, parent, id=(- 1), pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.TAB_TRAVERSAL, name='scrolledpanel'):
wx.ScrolledWindow.__init__(self, parent, id, pos=pos, size=size, style=style, name=name)
self.SetSize(size... |
class KubernetesClient(object):
def __init__(self):
if ('KUBERNETES_LOAD_KUBE_CONFIG' in os.environ):
config.load_kube_config(persist_config=False)
else:
config.load_incluster_config()
self._v1 = client.CoreV1Api()
self._batch_v1 = client.BatchV1Api()
def ... |
('flytekit.core.utils.load_proto_from_file')
('flytekit.core.data_persistence.FileAccessProvider.get_data')
('flytekit.core.data_persistence.FileAccessProvider.put_data')
('flytekit.core.utils.write_proto_to_file')
def test_dispatch_execute_ignore(mock_write_to_file, mock_upload_dir, mock_get_data, mock_load_proto):
... |
class TelnetOOB():
def __init__(self, protocol):
self.protocol = protocol
self.protocol.protocol_flags['OOB'] = False
self.MSDP = False
self.GMCP = False
self.protocol.negotiationMap[MSDP] = self.decode_msdp
self.protocol.negotiationMap[GMCP] = self.decode_gmcp
... |
class AptUtils():
def checkapt():
result = CmdTask('sudo apt update', 100).run()
if (result[0] != 0):
if FileUtils.check_result(result, ['certificate', '']):
PrintUtils.print_warn('{}, /etc/apt/apt.conf.d/99verify-peer.conf'.format(result[2]))
CmdTask('tou... |
def replace_widget_ids(widget: BaseWidgetInfo, generator: WidgetIdGenerator):
widget.id = generator.get_id()
add_graph_id_mapping: Dict[(str, Union[(BaseWidgetInfo, AdditionalGraphInfo, PlotlyGraphInfo)])] = {}
for add_graph in widget.additionalGraphs:
if isinstance(add_graph, BaseWidgetInfo):
... |
class OptionPlotoptionsWindbarbSonificationDefaultinstrumentoptionsMapping(Options):
def frequency(self) -> 'OptionPlotoptionsWindbarbSonificationDefaultinstrumentoptionsMappingFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsWindbarbSonificationDefaultinstrumentoptionsMappingFrequency... |
class EcsTestClient(object):
def __init__(self, access_key_id=None, secret_access_key=None, region=None, profile=None, deployment_errors=False, client_errors=False, wait=0):
super(EcsTestClient, self).__init__()
self.access_key_id = access_key_id
self.secret_access_key = secret_access_key
... |
class RelationshipCustomerCustomer(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_... |
('cuda.gemm_rcr_fast_gelu.gen_function')
def gen_function(func_attrs, exec_cond_template, dim_info_dict):
input_ndims = len(func_attrs['input_accessors'][0].original_shapes)
weight_ndims = len(func_attrs['input_accessors'][1].original_shapes)
output_ndims = len(func_attrs['output_accessors'][0].original_sha... |
def validate_display_name(display_name, required=False):
if ((display_name is None) and (not required)):
return None
if ((not isinstance(display_name, str)) or (not display_name)):
raise ValueError('Invalid display name: "{0}". Display name must be a non-empty string.'.format(display_name))
... |
def decompress_bytes(data, offset, dictionary, pos=0):
length = int.from_bytes(data[pos:(pos + 2)], 'little')
pos += 2
bitfield_length = data[pos]
bitfield = int.from_bytes(data[(pos + 1):((pos + 1) + bitfield_length)], 'little')
o = []
subdata_end = (pos + length)
pos += (1 + bitfield_lengt... |
_tag('django_social_share/templatetags/send_email.html', takes_context=True)
def send_email(context, subject, text, obj_or_url=None, link_text='', link_class=''):
context = send_email_url(context, subject, text, obj_or_url)
context['link_class'] = link_class
context['link_text'] = (link_text or 'Share via e... |
class SignedHandler(object):
def __init__(self):
self.db_factory = transactional_session_maker()
def __call__(self, message: fedora_messaging.api.Message):
message = message.body
build_nvr = ('%(name)s-%(version)s-%(release)s' % message)
tag = message['tag']
log.info(('%s... |
_settings(DEBUG=True)
class Test(TestCase):
def create_tree(self):
tree = type('Namespace', (), {})()
tree.root = Model.objects.create(name='root')
tree.child1 = Model.objects.create(parent=tree.root, order=0, name='1')
tree.child2 = Model.objects.create(parent=tree.root, order=1, na... |
class OptionPlotoptionsHeatmapSonificationTracksMappingVolume(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 api_request(url, method, headers, body=None):
try:
headers = update_header_w_auth(headers)
except:
pass
try:
if (method.upper() == 'GET'):
auth_request = requests.get(url, headers=headers, allow_redirects=False, verify=False, timeout=10)
elif (method.upper() =... |
def assign_scaffold_names(scaffolds, perm_container, ref_genome):
MIN_RATE = 0.1
PREFIX = 'chr'
chr_index = {}
for perm in perm_container.ref_perms:
if (perm.genome_name == ref_genome):
for block in perm.blocks:
chr_index[block.block_id] = (perm.chr_name, block.sign)
... |
class TestSuperFencesBad(util.MdCase):
extension = ['pymdownx.superfences']
extension_configs = {}
def test_bad_options(self):
self.check_markdown('\n ```python option="bad"\n import test\n ```\n ', '\n <p><code>python option="bad"\n ... |
class MonitorWrapper(object):
def __init__(self, copr, monitor_data):
self.copr = copr
self.monitor_data = monitor_data
def render_packages(self):
packages = []
results = {}
current_package_id = None
for row in self.monitor_data:
if (row['package_id'] ... |
def quadrupole3d_22(ax, da, A, bx, db, B, R):
result = numpy.zeros((6, 6, 6), dtype=float)
x0 = ((ax + bx) ** (- 1.0))
x1 = (3.0 * x0)
x2 = (x0 * ((ax * A[0]) + (bx * B[0])))
x3 = (- x2)
x4 = (x3 + A[0])
x5 = (x3 + B[0])
x6 = (x4 * x5)
x7 = (2.0 * x6)
x8 = (x3 + R[0])
x9 = (x... |
class JsNvd3(JsPackage):
lib_alias = {'js': 'nvd3', 'css': 'nvd3'}
lib_selector = 'd3.select("body")'
def __init__(self, component: primitives.HtmlModel=None, page: primitives.PageModel=None, js_code: str=None, selector: str=None, data: Any=None, set_var: bool=None):
(self.component, self.page) = (c... |
class TransitionIterator():
def __init__(self, transitions: TransitionBatch, batch_size: int, shuffle_each_epoch: bool=False, rng: Optional[np.random.Generator]=None):
self.transitions = transitions
self.num_stored = len(transitions)
self._order: np.ndarray = np.arange(self.num_stored)
... |
.parametrize('media_type', ['application/json', 'application/msgpack'])
def test_empty_body(asgi, media_type):
client = _create_client_invalid_media(asgi, errors.HTTPBadRequest, {'application/msgpack': media.MessagePackHandler(), 'application/json': media.JSONHandler()})
headers = {'Content-Type': media_type}
... |
def extractAnhobbiesWordpressCom(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 request_response(func: typing.Callable[([Request], typing.Union[(typing.Awaitable[Response], Response)])]) -> ASGIApp:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
request = Request(scope, receive, send)
async def app(scope: Scope, receive: Receive, send: Send) -> None:
... |
class TestSetCustomUserClaims():
.parametrize('arg', (INVALID_STRINGS + [('a' * 129)]))
def test_invalid_uid(self, user_mgt_app, arg):
with pytest.raises(ValueError):
auth.set_custom_user_claims(arg, {'foo': 'bar'}, app=user_mgt_app)
.parametrize('arg', (INVALID_DICTS[1:] + ['"json"']))
... |
class UserInfoAdmin(admin.ModelAdmin):
def get_avatar(self: UserInfo):
if (self.sign_status in [1, 2]):
return mark_safe(f'<img src="{self.avatar_url}" style="width:30px;height:30px;border-radius:50%;">')
if self.avatar:
return mark_safe(f'<img src="{self.avatar.url.url}" sty... |
def test_origin(f):
def_origin = f.object('ORIGIN', 'DEFINING_ORIGIN', 10, 0)
assert (def_origin.type == 'ORIGIN')
assert (def_origin.origin == 10)
assert (def_origin.file_id == 'some logical file')
assert (def_origin.file_set_name == 'SET-NAME')
assert (def_origin.file_set_nr == 1042)
asser... |
def execute_lexer_test(name):
files = [f for f in os.listdir('.') if f.endswith('.m')]
for f in files:
r = run_module('miss_hit_core.m_lexer', [f])
plain_out = r.stdout
with open((f + '.out'), 'w') as fd:
fd.write(plain_out)
return ('Ran lexer test %s' % name) |
def main():
tree = EvolTree((WRKDIR + 'tree.nw'))
tree.workdir = 'data/protamine/PRM1/paml/'
random_swap(tree)
tree.link_to_evol_model((WRKDIR + 'paml/fb/fb.out'), 'fb')
check_annotation(tree)
tree.link_to_evol_model((WRKDIR + 'paml/M1/M1.out'), 'M1')
tree.link_to_evol_model((WRKDIR + 'paml/... |
class OptionSeriesDependencywheelDataAccessibility(Options):
def description(self):
return self._config_get(None)
def description(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(None)
def enabled(self, flag: bool):
self._conf... |
class CheckPayment(QuickbooksBaseObject):
class_dict = {'BankAccountRef': Ref}
qbo_object_name = 'CheckPayment'
def __init__(self):
super(CheckPayment, self).__init__()
self.PrintStatus = 'NotSet'
self.BankAccountRef = None
def __str__(self):
return self.PrintStatus |
def _dp_add_ports(dp, dp_conf, dp_id, vlans):
ports_conf = dp_conf.get('interfaces', {})
port_ranges_conf = dp_conf.get('interface_ranges', {})
test_config_condition((not isinstance(ports_conf, dict)), 'Invalid syntax in interface config')
test_config_condition((not isinstance(port_ranges_conf, dict)), ... |
def test_sub_wf_single_named_tuple():
nt = typing.NamedTuple('SingleNamedOutput', [('named1', int)])
def t1(a: int) -> nt:
a = (a + 2)
return nt(a)
def subwf(a: int) -> nt:
return t1(a=a)
def wf(b: int) -> nt:
out = subwf(a=b)
return t1(a=out.named1)
x = wf(b=... |
class OptionSeriesVectorSonificationDefaultinstrumentoptionsMappingLowpassResonance(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, ... |
def test_colors_whole_table_supports_ansi_false(data, header, footer, fg_colors, bg_colors):
os.environ['ANSI_COLORS_DISABLED'] = 'True'
result = table(data, header=header, footer=footer, divider=True, fg_colors=fg_colors, bg_colors=bg_colors)
assert (result == '\nCOL A COL B COL 3 \n ---... |
def generic_upload_dataset_if_not_exists(client: 'foundry_dev_tools.foundry_api_client.FoundryRestClient | MockFoundryRestClient', name='iris_new', upload_folder: 'Path | None'=None, foundry_schema=None) -> 'tuple[str, str, str, str, bool]':
ds_path = f'{INTEGRATION_TEST_COMPASS_ROOT_PATH}/{name}'
ds_branch = '... |
('rig')
def check_root_node_name(progress_controller=None):
if (progress_controller is None):
progress_controller = ProgressControllerBase()
progress_controller.maximum = 2
root_nodes = auxiliary.get_root_nodes()
from anima.dcc import mayaEnv
m_env = mayaEnv.Maya()
v = m_env.get_current_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.