code stringlengths 281 23.7M |
|---|
def test_register_filetype(tmp_path):
filename = (tmp_path / 'test.conf')
with filename.open('w') as f:
f.write('{"key": "value"}')
with pytest.raises(ValueError):
c = config.Config.from_file(filename)
config.Config.register_filetype(config.JSONConfig, '.conf', '.config')
c = config.... |
class KeolisIlevia(BikeShareSystem):
meta = {'system': 'Keolis', 'company': ['Keolis']}
BASE_URL = '
def __init__(self, tag, dataset, meta):
super(KeolisIlevia, self).__init__(tag, meta)
self.feed_url = KeolisIlevia.BASE_URL.format(dataset=dataset)
def update(self, scraper=None):
... |
def knowledge_delete(api_address: str, space_name: str, doc_name: str, confirm: bool=False):
client = KnowledgeApiClient(api_address)
space = KnowledgeSpaceRequest()
space.name = space_name
space_list = client.space_list(KnowledgeSpaceRequest(name=space.name))
if (not space_list):
raise Exce... |
_os(*metadata.platforms)
def main():
powershell = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
posh = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\posh.exe'
user32 = 'C:\\Windows\\System32\\user32.dll'
dll = 'C:\\Users\\Public\\mstscax.dll'
ps1 = 'C:\\Users\\Public\\Invoke-Im... |
def get_access_token(username: str, password: str, server_url: str) -> Tuple[(str, str)]:
payload = {'username': username, 'password': str_to_b64_str(password)}
response = requests.post((server_url + LOGIN_PATH), json=payload)
handle_cli_response(response, verbose=False)
user_id: str = response.json()['... |
class llc(packet_base.PacketBase):
_PACK_STR = '!BB'
_PACK_LEN = struct.calcsize(_PACK_STR)
_CTR_TYPES = {}
_CTR_PACK_STR = '!2xB'
_MIN_LEN = _PACK_LEN
def register_control_type(register_cls):
llc._CTR_TYPES[register_cls.TYPE] = register_cls
return register_cls
def __init__(s... |
def verify_setup(setup):
(G1_setup, G2_setup) = setup
G1_random_coeffs = [random.randrange((2 ** 40)) for _ in range((len(G1_setup) - 1))]
G1_lower = linear_combination(G1_setup[:(- 1)], G1_random_coeffs, b.Z1)
G1_upper = linear_combination(G1_setup[1:], G1_random_coeffs, b.Z1)
G2_random_coeffs = [r... |
class PsycopgInstrumentation(DbApi2Instrumentation):
name = 'psycopg'
instrument_list = [('psycopg', 'connect')]
def call(self, module, method, wrapped, instance, args, kwargs):
signature = 'psycopg.connect'
(host, port) = get_destination_info(kwargs.get('host'), kwargs.get('port'))
... |
class Latency():
PATTERN = re.compile('^sys(?:(\\d+)x)?$')
def __init__(self, **kwargs):
self._sys = Fraction(0, 1)
for (name, cycles) in kwargs.items():
m = self.PATTERN.match(name)
assert m, f'Wrong format: {name}'
denom = (m.group(1) or 1)
self.... |
('cuda.gemm_rrr_bias.func_decl')
def gen_function_decl(func_attrs):
func_name = func_attrs['name']
input_ndims = len(func_attrs['input_accessors'][0].original_shapes)
weight_ndims = len(func_attrs['input_accessors'][1].original_shapes)
return common_bias.FUNC_DECL_TEMPLATE.render(func_name=func_name, in... |
def create_superuser():
print("\nCreate a superuser below. The superuser is Account #1, the 'owner' account of the server. Email is optional and can be empty.\n")
from os import environ
username = environ.get('EVENNIA_SUPERUSER_USERNAME')
email = environ.get('EVENNIA_SUPERUSER_EMAIL')
password = env... |
class Formatter():
env = register_filters()
def get_format(cls, path: str) -> Tuple[(str, Optional[str])]:
i = path.find('{{')
if (i > 0):
i = path.rfind('/', 0, i)
if (i > 0):
return (path[0:i], path[(i + 1):])
return (path, None)
def format(c... |
class NotebookManager(object):
def __init__(self, connection_file):
self.connection_file = connection_file
self.nb_proc = None
self.nb_pipe_thread = None
self.nb_pipe_buffer = []
self.nb_pipe_lock = threading.Lock()
def ensure_kernel_proxy_installed():
try:
... |
_numba()
.script_launch_mode('subprocess')
def test_main(script_runner):
for inp in ['--help', '-h']:
ret = script_runner.run('empymod', inp)
assert ret.success
assert ('3D electromagnetic modeller for 1D VTI media' in ret.stdout)
ret = script_runner.run('empymod')
assert ret.success... |
class FirewallDConfigPolicy(DbusServiceObject):
persistent = True
default_polkit_auth_required = config.dbus.PK_ACTION_CONFIG
_exceptions
def __init__(self, parent, conf, policy, item_id, *args, **kwargs):
super(FirewallDConfigPolicy, self).__init__(*args, **kwargs)
self.parent = parent
... |
class OptionSeriesScatterDatalabelsFilter(Options):
def operator(self):
return self._config_get(None)
def operator(self, value: Any):
self._config(value, js_type=False)
def property(self):
return self._config_get(None)
def property(self, text: str):
self._config(text, js_... |
class OptionSeriesPolygonSonificationDefaultspeechoptionsActivewhen(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: f... |
def get_dir_hash(path: PathIn, *, func: str='md5') -> str:
path = _get_path(path)
assert_dir(path)
hash = hashlib.new(func)
files = search_files(path)
for file in sorted(files):
file_hash = get_file_hash(file, func=func)
file_hash_b = bytes(file_hash, 'utf-8')
hash.update(fil... |
class ScopeDefinition(object):
def __init__(self, bracket):
self.style = bracket.get('style', BH_STYLE)
self.open = bre.compile_search(('\\A' + bracket.get('open', '')), (bre.MULTILINE | bre.IGNORECASE))
self.close = bre.compile_search((bracket.get('close', '') + '\\Z'), (bre.MULTILINE | bre... |
class OptionSeriesVariwideStatesInactive(Options):
def animation(self) -> 'OptionSeriesVariwideStatesInactiveAnimation':
return self._config_sub_data('animation', OptionSeriesVariwideStatesInactiveAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
... |
def get_pipeline_id(app='', name=''):
return_id = None
pipelines = get_all_pipelines(app=app)
for pipeline in pipelines:
LOG.debug('ID of %(name)s: %(id)s', pipeline)
if (pipeline['name'] == name):
return_id = pipeline['id']
LOG.info('Pipeline %s found, ID: %s', name,... |
_frequency(timedelta(days=1))
def fetch_exchange(zone_key1: ZoneKey, zone_key2: ZoneKey, session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list[dict[(str, Any)]]:
sortedcodes = '->'.join(sorted([zone_key1, zone_key2]))
exchange_list = ExchangeList(lo... |
def plot_value_counts_tables(feature_name, values, curr_df, ref_df, id_prfx):
additional_plots = []
if (values is not None):
curr_df = curr_df[(curr_df['count'] != 0)]
curr_vals_inside_lst = curr_df[curr_df.x.isin(values)].sort_values('count', ascending=False)
data = np.array(['', ''])
... |
def build_violations(res):
violation_data = {'full_name': res.full_name, 'resource_type': res.type, 'locations': res.locations}
return [location_rules_engine.RuleViolation(resource_id=res.id, resource_name=res.display_name, resource_type=res.type, full_name=res.full_name, rule_index=0, rule_name='Location test ... |
class TestDispServer(TestDispServerLib.TestDispServer, comtypes.server.connectionpoints.ConnectableObjectMixin):
_com_interfaces_ = (TestDispServerLib.TestDispServer._com_interfaces_ + [comtypes.connectionpoints.IConnectionPointContainer])
_reg_threading_ = 'Both'
_reg_progid_ = 'TestDispServerLib.TestDispS... |
.parametrize('name, in_out', test_pieces)
def test_encode(name, in_out):
data = in_out['in']
result = encode_hex(encode(data)).lower()
expected = in_out['out'].lower()
if (result != expected):
pytest.fail(f'Test {name} failed (encoded {data} to {result} instead of {expected})') |
def extractThernotstudioWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
if ('WATTT' in item['tags']):
return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=... |
class Emulation(BaseEmulation):
parser = BaseEmulation.load_parser(description='Sends a phishing email to a user with a HTML attachment.')
parser.add_argument('session_key', default='default', help='Session to use for service building API service')
parser.add_argument('--recipient', required=True, help='Rec... |
class SideDoorHousing(Console2):
ui_group = 'Box'
description = '\nThis box is designed as a housing for electronic projects. It has hatches that can be re-opened with simple tools. It intentionally cannot be opened with bare hands - if build with thin enough material. The hatches are at the x sides.\n\n#### As... |
class sFlowV5ExtendedSwitchData(object):
_PACK_STR = '!IIII'
def __init__(self, src_vlan, src_priority, dest_vlan, dest_priority):
super(sFlowV5ExtendedSwitchData, self).__init__()
self.src_vlan = src_vlan
self.src_priority = src_priority
self.dest_vlan = dest_vlan
self.d... |
class TestTFUtils(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
self.env = StreamExecutionEnvironment.get_execution_environment()
self.env.add_jars('file://{}'.format(find_jar_path()))
self.env.set_parallelism(1)
self.t_env = StreamTableEnvironment.create(self.... |
class OptionSeriesBellcurveSonificationContexttracksMappingHighpassResonance(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: s... |
.django_db
def test_success(client, bureau_data, helpers):
resp = client.get(url.format(toptier_code='001', filter=f'?fiscal_year={helpers.get_mocked_current_fiscal_year()}'))
expected_results = [{'name': 'Test Bureau 1', 'id': 'test-bureau-1', 'total_obligations': 1.0, 'total_outlays': 10.0, 'total_budgetary_r... |
class DiplomaticRelation(Base):
__tablename__ = 'diplomatic_relation'
diplo_relation_id = Column(Integer, primary_key=True)
country_id = Column(ForeignKey(Country.country_id), nullable=False, index=True)
target_country_id = Column(ForeignKey(Country.country_id), nullable=False, index=True)
rivalry =... |
def continuize(system: System, dt: float=0.01, inplace: bool=False) -> System:
if (not inplace):
system = system.copy()
num_timestamps = (int((system.events[(- 1)].time // dt)) + 1)
for ball in system.balls.values():
history = BallHistory()
history.add(ball.history[0])
(rvw, ... |
def extractYuinaNovelTradBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [("since i was reborn as saito yoshiryu i'm aiming to hand over the territory to oda nobunaga ... |
class Migration(migrations.Migration):
dependencies = [('bank', '0006_auto__1030'), ('core', '0060_use_accounted_by')]
operations = [migrations.CreateModel(name='UseTransaction', fields=[('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('transaction', models.For... |
def add_path_resolver(tag, path, kind=None, Loader=None, Dumper=None, resolver=Resolver):
if ((Loader is None) and (Dumper is None)):
resolver.add_path_resolver(tag, path, kind)
return
if Loader:
if hasattr(Loader, 'add_path_resolver'):
Loader.add_path_resolver(tag, path, kin... |
class OptionSeriesBarSonificationContexttracksMappingHighpassFrequency(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 upgrade():
connection = op.get_bind()
connection.execute('pragma foreign_keys=OFF')
with op.batch_alter_table('feeding_schedules', schema=None) as batch_op:
batch_op.add_column(sa.Column('portion', sa.Float(), nullable=True))
connection.execute('update feeding_schedules set portion = 0.0625'... |
class OptionPlotoptionsSeriesSonificationTracksMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsSeriesSonificationTracksMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsSeriesSonificationTracksMappingLowpassFrequency)
def resonance(self) -> 'OptionPlo... |
class CPALTest(unittest.TestCase):
def test_decompile_v0(self):
cpal = newTable('CPAL')
cpal.decompile(CPAL_DATA_V0, ttFont=None)
self.assertEqual(cpal.version, 0)
self.assertEqual(cpal.numPaletteEntries, 2)
self.assertEqual(repr(cpal.palettes), '[[#000000FF, #66CCFFFF], [#00... |
class OptionSeriesPyramidMarkerStatesSelect(Options):
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def fillColor(self):
return self._config_get('#cccccc')
def fillColor(self, text: str):
self._config(tex... |
class TestF1ByClass(ByClassClassificationTest):
name: ClassVar[str] = 'F1 Score by Class'
def get_value(self, result: ClassMetric):
return result.f1
def get_description(self, value: Numeric) -> str:
return f'The F1 score of the label **{self.label}** is {value:.3g}. The test threshold is {se... |
class ToolExecutor():
def __init__(self, execution: IToolExecution) -> None:
self.execution = execution
def execute(self, function_call: 'FunctionCall') -> str:
return self.execution.execute(function_call)
def is_valid_tool(self, tool_name: str) -> bool:
return self.execution.is_vali... |
class TestProcessJob(TestCase):
def setUp(self):
settings = factories.ServerSettingsFactory()
settings['middleware'].append({'object': ProcessJobMiddleware})
self.server = ProcessJobServer(settings=settings)
def make_job(self, action, body):
return {'control': {'continue_on_error... |
class test(testing.TestCase):
def test_simple(self):
(u0, u1) = main(nelems=4, angle=10.0, trim=False)
with self.subTest('linear'):
self.assertAlmostEqual64(u0, '\n eNpjYMAE5ZeSL/HqJ146YeB4cbvhl/PzjPrOcVy8da7b4Og5W6Osc/rGt88+MvY+u+yC7NlcQ+GzEsYP\n z/w3nn1mvo... |
_api.route((api_url + 'tickets'), methods=['POST'])
_auth.login_required
def create_ticket():
data = (request.get_json() or {})
if (('title' not in data) or ('content' not in data) or ('category_id' not in data) or ('ticket_priority_id' not in data)):
return bad_request('Must include title, content, cat... |
def images_are_equal(img1: PILImage.Image, img2: PILImage.Image) -> bool:
if (img1.size != img2.size):
return False
pixels1 = list(img1.getdata())
pixels2 = list(img2.getdata())
for (p1, p2) in zip(pixels1, pixels2):
if (p1 != p2):
return False
return True |
def extractM2MtlTumblrCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('fakecinderella', 'Fake Cinderella', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiter... |
class Default(Node):
__slots__ = ('stmts', 'coord', '__weakref__')
def __init__(self, stmts, coord=None):
self.stmts = stmts
self.coord = coord
def children(self):
nodelist = []
for (i, child) in enumerate((self.stmts or [])):
nodelist.append((('stmts[%d]' % i), c... |
def get_sum_and_count_aggregation_results(keyword):
filter_query = QueryWithFilters.generate_transactions_elasticsearch_query({'keyword_search': [es_minimal_sanitize(keyword)]})
search = TransactionSearch().filter(filter_query)
search.aggs.bucket('prime_awards_obligation_amount', {'sum': {'field': 'federal_... |
class OptionPlotoptionsPyramid3dDragdropGuideboxDefault(Options):
def className(self):
return self._config_get('highcharts-drag-box-default')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('rgba(0, 0, 0, 0.1)')
def color... |
def parsedb_all(db_root, verbose=False):
files = 0
for bit_fn in glob.glob(('%s/segbits_*.db' % db_root)):
if ('origin_info' in bit_fn):
continue
(verbose and print(('Checking %s' % bit_fn)))
parsedb.run(bit_fn, fnout=None, strict=True, verbose=verbose)
files += 1
... |
class PostalCodeInCountryFormat(FancyValidator):
country_field = 'country'
zip_field = 'zip'
__unpackargs__ = ('country_field', 'zip_field')
messages = dict(badFormat=_("Given postal code does not match the country's format."))
_vd = {'AR': ArgentinianPostalCode, 'AT': FourDigitsPostalCode, 'BE': Fo... |
.parametrize('input_formatter, expected_string', [(None, 'user input'), ('triple_quotes', '"""\nuser input\n"""'), ('text_prefix', 'Text: """\nuser input\n"""')])
def test_input_formatter_applied_correctly(input_formatter: InputFormatter, expected_string: str) -> None:
untyped_object = Object(id='obj', examples=[('... |
def geom_to_graph(geom):
G = nx.Graph()
G.add_nodes_from([(i, {'atom': atom}) for (i, atom) in enumerate(geom.atoms)])
bonds = get_bond_sets(geom.atoms, geom.coords3d)
c3d = geom.coords3d
lengths = [np.linalg.norm((c3d[i] - c3d[j])) for (i, j) in bonds]
bonds_with_lengths = [(i, j, {'length': le... |
class ClassModal(GrpCls.ClassHtml):
def css(self) -> AttrClsContainer.AttrModal:
if (self._css_struct is None):
self._css_struct = AttrClsContainer.AttrModal(self.component)
return self._css_struct
def css_class(self) -> Classes.CatalogDiv.CatalogDiv:
if (self._css_class is N... |
class TestDialogues():
def setup_class(cls):
cls.agent_addr = 'agent address'
cls.peer_addr = 'peer address'
cls.agent_dialogues = AgentDialogues(cls.agent_addr)
cls.server_dialogues = PeerDialogues(cls.peer_addr)
def test_create_self_initiated(self):
result = self.agent_... |
def test_cancelled(clock_decision_context, request_info):
exception = Exception()
clock_decision_context.timer_cancelled(START_TIMER_ID, exception)
request_info.completion_handle.assert_called_once()
(args, kwargs) = request_info.completion_handle.call_args_list[0]
assert (args[0] is None)
asser... |
def verify_problem_solution(row, player_names):
msg = row[1]
(id, pubkey) = verify_signed_message(row)
msg_valid = msg_internal_validity(msg, id)
recipient = msg.split(' ')[5]
sender_ok = (True if (id in player_names) else False)
recipient_ok = (False if (recipient in player_names) else True)
... |
def _make_functions(namespace):
ignore = ['axes', 'text', 'orientation_axes']
for mod in registry.modules:
func_name = camel2enthought(mod.id)
class_name = mod.id
if func_name.endswith('_module'):
func_name = func_name[:(- 7)]
class_name = class_name[:(- 6)]
... |
def getSysDescr(reactor, hostname):
snmpEngine = SnmpEngine()
deferred = getCmd(snmpEngine, CommunityData('public'), UdpTransportTarget((hostname, 161), timeout=2.0, retries=0), ContextData(), ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
deferred.addCallback(success, hostname).addErrback(failure... |
class EmailParamType(click.ParamType):
name = 'email'
EMAIL_REGEX = re.compile('(^[a-zA-Z0-9_.+-]+[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$)')
def convert(self, value, param, ctx):
if self.EMAIL_REGEX.match(value):
return value
else:
self.fail(f'{value} is not a valid email', p... |
class CommandGeneratorVarBinds(MibViewControllerManager):
def makeVarBinds(self, userCache, varBinds):
mibViewController = self.getMibViewController(userCache)
resolvedVarBinds = []
for varBind in varBinds:
if isinstance(varBind, ObjectType):
pass
elif... |
def get_config(config_paths: Optional[Union[(List[str], str)]]=None, opts: Optional[list]=None) -> CN:
config = _CONFIG.clone()
if config_paths:
if isinstance(config_paths, str):
if (CONFIG_FILE_SEPARATOR in config_paths):
config_paths = config_paths.split(CONFIG_FILE_SEPARAT... |
class GoogleCalendarEvent(CalendarEvent):
def __init__(self, google_event):
self.id = google_event['id']
self.title = google_event['summary']
self.start = self._parse_date(google_event['start'])
self.end = self._parse_date(google_event['end'])
self.recurring = ('recurringEven... |
def create_test_data(db: orm.Session) -> FidesUser:
print('Seeding database with privacy requests')
(_, client) = ClientDetail.get_or_create(db=db, data={'fides_key': 'ci_create_test_data', 'hashed_secret': 'autoseededdata', 'salt': 'autoseededdata', 'scopes': [], 'roles': []})
policies = []
policies.ap... |
.skipif(True, reason='Buggy in Gnome 45')
.skipif((not shutil.which('wl-copy')), reason='Needs wl-copy')
.skipif((sys.platform != 'linux'), reason='Linux specific test')
def test_wlcopy_copy():
text = f'this is a unique test {uuid.uuid4()}'
result = wlclipboard.WlCopyHandler().copy(text=text)
with subproces... |
def test_help_output(tmp_project, capfd):
valid_sd_command = 'python manage.py simple_deploy --help'
(stdout, stderr) = msp.call_simple_deploy(tmp_project, valid_sd_command)
current_test_dir = Path(__file__).parent
reference_help_output = (current_test_dir / 'reference_files/sd_help_output.txt').read_te... |
_mode()
def generate_stream(model, tokenizer, params, device, context_len=4096, stream_interval=2):
'Fork from fastchat:
prompt = params['prompt']
l_prompt = len(prompt)
prompt = prompt.replace('ai:', 'assistant:').replace('human:', 'user:')
temperature = float(params.get('temperature', 1.0))
m... |
(False)
(False)
(True)
(False)
def row_sum_loops(arr, columns):
dtype = type(arr[(0, 0)])
res = np.empty(arr.shape[0], dtype=dtype)
for i in range(arr.shape[0]):
sum_ = dtype(0)
for j in range(columns.shape[0]):
sum_ += arr[(i, columns[j])]
res[i] = sum_
return res |
class TestLogical(BaseSkillTestCase):
path_to_skill = Path(ROOT_DIR, 'packages', 'fetchai', 'skills', 'tac_negotiation')
def setup(cls):
tac_dm_context_kwargs = {'goal_pursuit_readiness': GoalPursuitReadiness(), 'ownership_state': OwnershipState(), 'preferences': Preferences()}
super().setup(dm_... |
def sDEStoNTLMPart(sDESKey):
sBinaryDESKey = bin(int(sDESKey, 16))[2:].zfill(64)
sNewBinary = ''
for i in range(0, 64, 8):
sNewBinary += sBinaryDESKey[i:(i + 7)]
if (not (sBinaryDESKey[(i + 7):(i + 8)] == '1')):
print('Warning: Is this a valid NTLMv1 DES Key?')
sNTLMPart = he... |
def extractTinkerreleasesNet(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 ... |
def test_correct_response(client, monkeypatch, elasticsearch_transaction_index, awards_and_transactions):
setup_elasticsearch_test(monkeypatch, elasticsearch_transaction_index)
resp = client.post('/api/v2/search/spending_by_category/state_territory', content_type='application/json', data=json.dumps({'filters': ... |
def extractAirustlWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('my seatmate tries to make me fall in love with her by teasing me repeatedly, but somehow she was ... |
def test_compute_angle() -> None:
assert np.allclose(compute_angle(np.array((1, 0))), 0)
assert np.allclose(compute_angle(np.array((ROOT, ROOT))), (np.pi * 0.25))
assert np.allclose(compute_angle(np.array((0, 1))), (np.pi * 0.5))
assert np.allclose(compute_angle(np.array(((- ROOT), ROOT))), (np.pi * 0.7... |
def db_startup(app):
athlete_exists = (True if (len(app.session.query(athlete).all()) > 0) else False)
if (not athlete_exists):
dummy_athlete = athlete(name='New User')
app.session.add(dummy_athlete)
app.session.commit()
db_refresh_record = (True if (len(app.session.query(dbRefreshSt... |
class NoopTimer(Timer):
def __init__(self) -> None:
pass
def get_count(self) -> float:
return 0.0
def get_sum(self) -> float:
return 0.0
def get_max(self) -> float:
return 0.0
def get_min(self) -> float:
return 0.0
def get_mean(self) -> float:
retu... |
class Kernel():
def __init__(self, hh_excess: Point, signature: Signature, fee, metadata):
self.hh_excess = hh_excess
self.signature = signature
self.fee = fee
self.metadata = metadata
def __str__(self):
return '\n excess:\n {}\n signature (scalar):\n... |
_required
_required
_required
def dc_storage_list(request):
context = collect_view_data(request, 'dc_storage_list')
context['can_edit'] = can_edit = request.user.is_staff
context['all'] = _all = (can_edit and request.GET.get('all', False))
context['qs'] = get_query_string(request, all=_all).urlencode()
... |
def _group_split_outputs_together(sorted_graph: List[Tensor], sorted_ops: List[Operator], op_type: str) -> List[List[Operator]]:
groups = []
if (op_type not in _group_gemm_op_mapping):
return groups
for op in sorted_ops:
if (op._attrs['op'] != 'split'):
continue
if (not _... |
.parametrize('path, status, consumption, remaining', [('test_battery_basic1', 'FULL', '0.000', '0h:00m'), ('test_battery_basic2', 'FULL', '0.000', '0h:00m'), ('test_battery_basic3', 'DIS', '15.624', '4h:04m'), ('test_battery_basic4', 'DIS', '17.510', '1h:46m'), ('test_battery_basic5', 'DIS', '11.453', '4h:52m'), ('test... |
def extractYintranslationsCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('When I Returned From Another World I Was A Silver Haired Shrine Maiden', 'When I Returned From Ano... |
def remove_imgbg_in_background(profile_name, default_color=None):
from gameplan.gameplan.doctype.gp_user_profile.profile_photo import remove_background
profile = frappe.get_doc('GP User Profile', profile_name)
file = frappe.get_doc('File', {'file_url': profile.image})
profile.original_image = file.file_... |
def test_asgi_conductor_raised_error_skips_shutdown():
class SomeException(Exception):
pass
class Foo():
def __init__(self):
self.called_startup = False
self.called_shutdown = False
async def process_startup(self, scope, event):
self.called_startup = T... |
def interpolate_extrapolate(coords, energies, forces, steps, ref_step=None, err_vecs=None, max_vecs=10, gediis_thresh=0.01, gdiis_thresh=0.0025):
can_gediis = (np.sqrt(np.mean((forces[(- 1)] ** 2))) < gediis_thresh)
can_diis = ((ref_step is not None) and (np.sqrt(np.mean((ref_step ** 2))) < gdiis_thresh))
i... |
def ensure_unique_route_names(app: FastAPI) -> None:
temp_routes = set()
for route in app.routes:
if isinstance(route, APIRoute):
if (route.name in temp_routes):
raise ValueError(f'Non-unique route name: {route.name}')
temp_routes.add(route.name) |
.anyio
class TestMaxAtOnce():
class Spy():
def __init__(self, num_tasks: int) -> None:
self.num_tasks = num_tasks
self.num_running = 0
self.max_running = 0
self.async_fns = [self.async_fn for _ in range(self.num_tasks)]
self.args = [None for _ in r... |
def get_strategy(strategy_name: str, configuration: Dict[(str, Any)]) -> PostProcessorStrategy:
if (not SupportedPostProcessorStrategies.__contains__(strategy_name)):
valid_strategies = ', '.join([s.name for s in SupportedPostProcessorStrategies])
raise NoSuchStrategyException(f"Strategy '{strategy_... |
class FileContent(models.Model):
title = models.CharField(max_length=200)
file = models.FileField(_('file'), max_length=255, upload_to=os.path.join(settings.FEINCMS_UPLOAD_PREFIX, 'filecontent'))
class Meta():
abstract = True
verbose_name = _('file')
verbose_name_plural = _('files')
... |
class RecursiveCrawler(scrapy.Spider):
name = 'RecursiveCrawler'
allowed_domains = None
start_urls = None
original_url = None
log = None
config = None
helper = None
ignore_regex = None
ignore_file_extensions = None
def __init__(self, helper, url, config, ignore_regex, *args, **kw... |
class RemoteCollection(object):
def __init__(self, repo):
self._repo = repo
def __len__(self):
names = ffi.new('git_strarray *')
try:
err = C.git_remote_list(names, self._repo._repo)
check_error(err)
return names.count
finally:
C.gi... |
class Timeout(Exception):
seconds = None
exception = None
begun_at = None
is_running = None
def __init__(self, seconds: float=None, exception: Type[BaseException]=None, *args: Any, **kwargs: Any) -> None:
self.seconds = seconds
self.exception = exception
def __enter__(self) -> 'T... |
class TestSyncCollection():
def test_collection(self):
s = Storage('sqlite://:memory:', threaded=True)
s.start()
while (not s.is_connected):
time.sleep(0.01)
obj_id = '1'
obj_body = {'a': 12}
col = s.get_sync_collection('test_col')
col2 = s.get_syn... |
class ContractApiHandler(Handler):
SUPPORTED_PROTOCOL = ContractApiMessage.protocol_id
def setup(self) -> None:
def handle(self, message: Message) -> None:
contract_api_msg = cast(ContractApiMessage, message)
contract_api_dialogues = cast(ContractApiDialogues, self.context.contract_api_dialo... |
def regroup_inputs(node, rate_node=1, is_input=True, perform_checks=True):
node_name = node.ns_name
color = node.color
def _regroup_inputs(source):
def subscribe(observer, scheduler=None):
def on_next(value):
if is_input:
node_tick = value[0].info.node... |
class ip6tables(ip4tables):
ipv = 'ipv6'
name = 'ip6tables'
def build_rpfilter_rules(self, log_denied=False):
rules = []
rules.append(['-I', 'PREROUTING', '-t', 'mangle', '-m', 'rpfilter', '--invert', '--validmark', '-j', 'DROP'])
if (log_denied != 'off'):
rules.append(['... |
class _MockCallableDSL():
CALLABLE_MOCKS: Dict[(Union[(int, Tuple[(int, str)])], Union[Callable[([Type[object]], Any)]])] = {}
_NAME: str = 'mock_callable'
def _validate_patch(self, name: str='mock_callable', other_name: str='mock_async_callable', coroutine_function: bool=False, callable_returns_coroutine: ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.